module Brick.Widgets.Edit
( Editor(editContents, editorName, editDrawContents)
, editor
, getEditContents
, applyEdit
, editContentsL
, editDrawContentsL
, renderEditor
, editAttr
)
where
import Lens.Micro
import Graphics.Vty (Event(..), Key(..), Modifier(..))
import qualified Data.Text.Zipper as Z
import Brick.Types
import Brick.Widgets.Core
import Brick.AttrMap
data Editor =
Editor { editContents :: Z.TextZipper String
, editDrawContents :: [String] -> Widget
, editorName :: Name
}
suffixLenses ''Editor
instance HandleEvent Editor where
handleEvent e ed =
let f = case e of
EvKey (KChar 'a') [MCtrl] -> Z.gotoBOL
EvKey (KChar 'e') [MCtrl] -> Z.gotoEOL
EvKey (KChar 'd') [MCtrl] -> Z.deleteChar
EvKey (KChar 'k') [MCtrl] -> Z.killToEOL
EvKey KEnter [] -> Z.breakLine
EvKey KDel [] -> Z.deleteChar
EvKey (KChar c) [] | c /= '\t' -> Z.insertChar c
EvKey KUp [] -> Z.moveUp
EvKey KDown [] -> Z.moveDown
EvKey KLeft [] -> Z.moveLeft
EvKey KRight [] -> Z.moveRight
EvKey KBS [] -> Z.deletePrevChar
_ -> id
in return $ applyEdit f ed
editor :: Name
-> ([String] -> Widget)
-> Maybe Int
-> String
-> Editor
editor name draw limit s = Editor (Z.stringZipper (lines s) limit) draw name
applyEdit :: (Z.TextZipper String -> Z.TextZipper String)
-> Editor
-> Editor
applyEdit f e = e & editContentsL %~ f
editAttr :: AttrName
editAttr = "edit"
getEditContents :: Editor -> [String]
getEditContents e = Z.getText $ e^.editContentsL
renderEditor :: Editor -> Widget
renderEditor e =
let cp = Z.cursorPosition $ e^.editContentsL
cursorLoc = Location (cp^._2, cp^._1)
limit = case e^.editContentsL.to Z.getLineLimit of
Nothing -> id
Just lim -> vLimit lim
in withAttr editAttr $
limit $
viewport (e^.editorNameL) Both $
showCursor (e^.editorNameL) cursorLoc $
visibleRegion cursorLoc (1, 1) $
e^.editDrawContentsL $
getEditContents e