-- | This module provides bracketed paste support as described at
--
-- http://cirw.in/blog/bracketed-paste
module Graphics.Vty.Input.Paste
  ( parseBracketedPaste
  , bracketedPasteStarted
  , bracketedPasteFinished
  )
where

import qualified Data.ByteString.Char8 as BS8
import Data.ByteString.Char8 (ByteString)

import Graphics.Vty.Input.Events
import Graphics.Vty.Input.Classify.Types

bracketedPasteStart :: ByteString
bracketedPasteStart :: ByteString
bracketedPasteStart = String -> ByteString
BS8.pack String
"\ESC[200~"

bracketedPasteEnd :: ByteString
bracketedPasteEnd :: ByteString
bracketedPasteEnd = String -> ByteString
BS8.pack String
"\ESC[201~"

-- | Does the input start a bracketed paste?
bracketedPasteStarted :: ByteString -> Bool
bracketedPasteStarted :: ByteString -> Bool
bracketedPasteStarted = ByteString -> ByteString -> Bool
BS8.isPrefixOf ByteString
bracketedPasteStart

-- | Does the input contain a complete bracketed paste?
bracketedPasteFinished :: ByteString -> Bool
bracketedPasteFinished :: ByteString -> Bool
bracketedPasteFinished = ByteString -> ByteString -> Bool
BS8.isInfixOf ByteString
bracketedPasteEnd

-- | Parse a bracketed paste. This should only be called on a string if
-- both 'bracketedPasteStarted' and 'bracketedPasteFinished' return
-- 'True'.
parseBracketedPaste :: ByteString -> KClass
parseBracketedPaste :: ByteString -> KClass
parseBracketedPaste ByteString
s =
    Event -> ByteString -> KClass
Valid (ByteString -> Event
EvPaste ByteString
p) (Int -> ByteString -> ByteString
BS8.drop Int
endLen ByteString
rest')
    where
        startLen :: Int
startLen = ByteString -> Int
BS8.length ByteString
bracketedPasteStart
        endLen :: Int
endLen   = ByteString -> Int
BS8.length ByteString
bracketedPasteEnd
        (ByteString
_, ByteString
rest ) = ByteString -> ByteString -> (ByteString, ByteString)
BS8.breakSubstring ByteString
bracketedPasteStart ByteString
s
        (ByteString
p, ByteString
rest') = ByteString -> ByteString -> (ByteString, ByteString)
BS8.breakSubstring ByteString
bracketedPasteEnd forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> ByteString -> ByteString
BS8.drop Int
startLen forall a b. (a -> b) -> a -> b
$ ByteString
rest