open new file in editor

This commit is contained in:
Armin Friedl 2016-08-09 00:36:23 +02:00
parent 46d9c6e437
commit 3abab0ec68

View file

@ -37,7 +37,7 @@ import Data.Maybe
import Data.Monoid (mempty, (<>))
import Data.String (fromString)
import Data.Tuple
import Lens.Micro ((%~), (&), (^.))
import Lens.Micro ((%~), (&), (.~), (^.))
import Lens.Micro.TH (makeLenses)
@ -96,9 +96,10 @@ uiMap = attrMap Vty.defAttr
drawUI :: HeditState -> [Widget Names]
drawUI st = vBox [titleBar, title, titleBar, commands] : [editWidget]
-- the where is a bit ugly, for an intuitive understanding just don't look at it
where editWidget = padTop (Pad 5) $ EditWidget.renderEditor True (st^.hedit)
where editWidget = padTop (Pad 4) $ EditWidget.renderEditor True (st^.hedit)
hBorder = BorderWidgets.hBorder
commands = withAttr (attrName "commands") $ padLeft Max $ hBox [ str "^S...Save"
commands = withAttr (attrName "commands") $ padLeft Max $ hBox [ str "^O...Open"
, str "^S...Save"
, str ""
, str "^C/Esc...Quit "
]
@ -114,6 +115,7 @@ appEvent :: HeditState -> Vty.Event -> EventM Names (Next HeditState)
appEvent st ev
| ev `elem` [esc, ctrl 'c'] = quit
| ev == ctrl 's' = save >> BrickMain.continue st
| ev == ctrl 'o' = askForFileAndOpen
| ev == tab = insertFourSpaces >>= BrickMain.continue
| otherwise = forwardToWidget >>= BrickMain.continue
-- forget about the where, you can safely assume that what the
@ -125,12 +127,20 @@ appEvent st ev
forwardToWidget = handleEventLensed st hedit EditWidget.handleEditorEvent ev
tab = Vty.EvKey (Vty.KChar '\t') []
insertFourSpaces = return $ insertString (replicate 4 ' ') st
askForFileAndOpen = suspendAndResume $ do
putStrLn "Please enter file path: "
f <- getLine
exists <- doesFileExist f
content <- if exists then readFile f else return []
return $ st & file .~ f
& hedit .~ EditWidget.editor Hedit drawHeditText Nothing content
-- just don't ask what this does --- inserts a string, returns the state. end of story.
insertString :: String -> HeditState -> HeditState
insertString string st = st & hedit %~ insertString' string -- uses some fancy lense magic
where insertString' [] e = e
insertString' (a:aa) e = insertString' aa $ insertChar
insertString' (a:aa) e = insertString' aa insertChar
-- inserts char a returns resulting editor
where insertChar = EditWidget.applyEdit (TextZipper.insertChar a) e