hledger-ui-1.2/Hledger/0000755000000000000000000000000013035210046013133 5ustar0000000000000000hledger-ui-1.2/Hledger/UI/0000755000000000000000000000000013066746043013467 5ustar0000000000000000hledger-ui-1.2/doc/0000755000000000000000000000000013067102144012332 5ustar0000000000000000hledger-ui-1.2/hledger-ui.hs0000644000000000000000000000013313035210046014137 0ustar0000000000000000#!/usr/bin/env runhaskell module Main (module Hledger.UI) where import Hledger.UI (main) hledger-ui-1.2/Hledger/UI.hs0000644000000000000000000000075313035210046014011 0ustar0000000000000000{-| Re-export the modules of the hledger-ui program. -} module Hledger.UI ( module Hledger.UI.Main, module Hledger.UI.UIOptions, module Hledger.UI.Theme, tests_Hledger_UI ) where import Test.HUnit import Hledger.UI.Main import Hledger.UI.UIOptions import Hledger.UI.Theme tests_Hledger_UI :: Test tests_Hledger_UI = TestList [ -- tests_Hledger_UI_Main -- tests_Hledger_UI_UIOptions ] hledger-ui-1.2/Hledger/UI/AccountsScreen.hs0000644000000000000000000004215113035510426016733 0ustar0000000000000000-- The accounts screen, showing accounts and balances like the CLI balance command. {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Hledger.UI.AccountsScreen (accountsScreen ,asInit ,asSetSelectedAccount ) where import Brick import Brick.Widgets.List import Brick.Widgets.Edit import Brick.Widgets.Border (borderAttr) import Control.Monad import Control.Monad.IO.Class (liftIO) import Data.List import Data.Maybe import Data.Monoid import qualified Data.Text as T import Data.Time.Calendar (Day) import qualified Data.Vector as V import Graphics.Vty (Event(..),Key(..),Modifier(..)) import Lens.Micro.Platform import System.Console.ANSI import System.FilePath (takeFileName) import Hledger import Hledger.Cli hiding (progname,prognameandversion,green) import Hledger.UI.UIOptions import Hledger.UI.UITypes import Hledger.UI.UIState import Hledger.UI.UIUtils import Hledger.UI.Editor import Hledger.UI.RegisterScreen import Hledger.UI.ErrorScreen accountsScreen :: Screen accountsScreen = AccountsScreen{ sInit = asInit ,sDraw = asDraw ,sHandle = asHandle ,_asList = list AccountsList V.empty 1 ,_asSelectedAccount = "" } asInit :: Day -> Bool -> UIState -> UIState asInit d reset ui@UIState{ aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}, ajournal=j, aScreen=s@AccountsScreen{} } = ui{aopts=uopts', aScreen=s & asList .~ newitems'} where newitems = list AccountsList (V.fromList displayitems) 1 -- keep the selection near the last selected account -- (may need to move to the next leaf account when entering flat mode) newitems' = listMoveTo selidx newitems where selidx = case (reset, listSelectedElement $ _asList s) of (True, _) -> 0 (_, Nothing) -> 0 (_, Just (_,AccountsScreenItem{asItemAccountName=a})) -> fromMaybe (fromMaybe 0 mprefixmatch) mexactmatch where mexactmatch = findIndex ((a ==) . asItemAccountName) displayitems mprefixmatch = findIndex ((a `isAccountNamePrefixOf`) . asItemAccountName) displayitems uopts' = uopts{cliopts_=copts{reportopts_=ropts'}} ropts' = ropts{accountlistmode_=if flat_ ropts then ALFlat else ALTree} q = queryFromOpts d ropts -- maybe convert balances to market value convert | value_ ropts' = balanceReportValue j valuedate | otherwise = id where valuedate = fromMaybe d $ queryEndDate False q -- run the report (items,_total) = convert $ report ropts' q j where -- still using the old balanceReport for change reports as it -- does not include every account from before the report period report | balancetype_ ropts == HistoricalBalance = singleBalanceReport | otherwise = balanceReport -- pre-render the list items displayitem (fullacct, shortacct, indent, bal) = AccountsScreenItem{asItemIndentLevel = indent ,asItemAccountName = fullacct ,asItemDisplayAccountName = replaceHiddenAccountsNameWith "All" $ if flat_ ropts' then fullacct else shortacct ,asItemRenderedAmounts = map showAmountWithoutPrice amts -- like showMixedAmountOneLineWithoutPrice } where Mixed amts = normaliseMixedAmountSquashPricesForDisplay $ stripPrices bal stripPrices (Mixed as) = Mixed $ map stripprice as where stripprice a = a{aprice=NoPrice} displayitems = map displayitem items asInit _ _ _ = error "init function called with wrong screen type, should not happen" asDraw :: UIState -> [Widget Name] asDraw UIState{aopts=UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}} ,ajournal=j ,aScreen=s@AccountsScreen{} ,aMode=mode } = case mode of Help -> [helpDialog, maincontent] -- Minibuffer e -> [minibuffer e, maincontent] _ -> [maincontent] where maincontent = Widget Greedy Greedy $ do c <- getContext let availwidth = -- ltrace "availwidth" $ c^.availWidthL - 2 -- XXX due to margin ? shouldn't be necessary (cf UIUtils) displayitems = s ^. asList . listElementsL maxacctwidthseen = -- ltrace "maxacctwidthseen" $ V.maximum $ V.map (\AccountsScreenItem{..} -> asItemIndentLevel + Hledger.Cli.textWidth asItemDisplayAccountName) $ -- V.filter (\(indent,_,_,_) -> (indent-1) <= fromMaybe 99999 mdepth) $ displayitems maxbalwidthseen = -- ltrace "maxbalwidthseen" $ V.maximum $ V.map (\AccountsScreenItem{..} -> sum (map strWidth asItemRenderedAmounts) + 2 * (length asItemRenderedAmounts - 1)) displayitems maxbalwidth = -- ltrace "maxbalwidth" $ max 0 (availwidth - 2 - 4) -- leave 2 whitespace plus least 4 for accts balwidth = -- ltrace "balwidth" $ min maxbalwidth maxbalwidthseen maxacctwidth = -- ltrace "maxacctwidth" $ availwidth - 2 - balwidth acctwidth = -- ltrace "acctwidth" $ min maxacctwidth maxacctwidthseen -- XXX how to minimise the balance column's jumping around -- as you change the depth limit ? colwidths = (acctwidth, balwidth) render $ defaultLayout toplabel bottomlabel $ renderList (asDrawItem colwidths) True (_asList s) where ishistorical = balancetype_ ropts == HistoricalBalance toplabel = files -- <+> withAttr (borderAttr <> "query") (str (if flat_ ropts then " flat" else "")) <+> nonzero <+> str (if ishistorical then " accounts" else " account changes") -- <+> str (if ishistorical then " balances" else " changes") <+> borderPeriodStr (if ishistorical then "at end of" else "in") (period_ ropts) <+> borderQueryStr querystr <+> togglefilters <+> borderDepthStr mdepth <+> str " (" <+> cur <+> str "/" <+> total <+> str ")" <+> (if ignore_assertions_ copts then withAttr (borderAttr <> "query") (str " ignoring balance assertions") else str "") where files = case journalFilePaths j of [] -> str "" f:_ -> withAttr ("border" <> "bold") $ str $ takeFileName f -- [f,_:[]] -> (withAttr ("border" <> "bold") $ str $ takeFileName f) <+> str " (& 1 included file)" -- f:fs -> (withAttr ("border" <> "bold") $ str $ takeFileName f) <+> str (" (& " ++ show (length fs) ++ " included files)") querystr = query_ ropts mdepth = depth_ ropts togglefilters = case concat [ uiShowClearedStatus $ clearedstatus_ ropts ,if real_ ropts then ["real"] else [] ] of [] -> str "" fs -> str " from " <+> withAttr (borderAttr <> "query") (str $ intercalate ", " fs) <+> str " txns" nonzero | empty_ ropts = str "" | otherwise = withAttr (borderAttr <> "query") (str " nonzero") cur = str (case _asList s ^. listSelectedL of Nothing -> "-" Just i -> show (i + 1)) total = str $ show $ V.length $ s ^. asList . listElementsL bottomlabel = case mode of Minibuffer ed -> minibuffer ed _ -> quickhelp where selectedstr = withAttr (borderAttr <> "query") . str quickhelp = borderKeysStr' [ ("?", str "help") ,("right", str "register") ,("H" ,if ishistorical then selectedstr "historical" <+> str "/period" else str "historical/" <+> selectedstr "period") ,("F" ,if flat_ ropts then str "tree/" <+> selectedstr "flat" else selectedstr "tree" <+> str "/flat") ,("-+", str "depth") --,("/", "filter") --,("DEL", "unfilter") --,("ESC", "cancel/top") ,("a", str "add") -- ,("g", "reload") ,("q", str "quit") ] asDraw _ = error "draw function called with wrong screen type, should not happen" asDrawItem :: (Int,Int) -> Bool -> AccountsScreenItem -> Widget Name asDrawItem (acctwidth, balwidth) selected AccountsScreenItem{..} = Widget Greedy Fixed $ do -- c <- getContext -- let showitem = intercalate "\n" . balanceReportItemAsText defreportopts fmt render $ addamts asItemRenderedAmounts $ str (T.unpack $ fitText (Just acctwidth) (Just acctwidth) True True $ T.replicate (asItemIndentLevel) " " <> asItemDisplayAccountName) <+> str " " <+> str (balspace asItemRenderedAmounts) where balspace as = replicate n ' ' where n = max 0 (balwidth - (sum (map strWidth as) + 2 * (length as - 1))) addamts :: [String] -> Widget Name -> Widget Name addamts [] w = w addamts [a] w = (<+> renderamt a) w -- foldl' :: (b -> a -> b) -> b -> t a -> b -- foldl' (Widget -> String -> Widget) -> Widget -> [String] -> Widget addamts (a:as) w = foldl' addamt (addamts [a] w) as addamt :: Widget Name -> String -> Widget Name addamt w a = ((<+> renderamt a) . (<+> str ", ")) w renderamt :: String -> Widget Name renderamt a | '-' `elem` a = withAttr (sel $ "list" <> "balance" <> "negative") $ str a | otherwise = withAttr (sel $ "list" <> "balance" <> "positive") $ str a sel | selected = (<> "selected") | otherwise = id asHandle :: UIState -> BrickEvent Name AppEvent -> EventM Name (Next UIState) asHandle ui0@UIState{ aScreen=scr@AccountsScreen{..} ,aopts=UIOpts{cliopts_=copts} ,ajournal=j ,aMode=mode } ev = do d <- liftIO getCurrentDay -- c <- getContext -- let h = c^.availHeightL -- moveSel n l = listMoveBy n l -- save the currently selected account, in case we leave this screen and lose the selection let selacct = case listSelectedElement _asList of Just (_, AccountsScreenItem{..}) -> asItemAccountName Nothing -> scr ^. asSelectedAccount ui = ui0{aScreen=scr & asSelectedAccount .~ selacct} case mode of Minibuffer ed -> case ev of VtyEvent (EvKey KEsc []) -> continue $ closeMinibuffer ui VtyEvent (EvKey KEnter []) -> continue $ regenerateScreens j d $ setFilter s $ closeMinibuffer ui where s = chomp $ unlines $ map strip $ getEditContents ed VtyEvent ev -> do ed' <- handleEditorEvent ev ed continue $ ui{aMode=Minibuffer ed'} AppEvent _ -> continue ui MouseDown _ _ _ _ -> continue ui MouseUp _ _ _ -> continue ui Help -> case ev of VtyEvent (EvKey (KChar 'q') []) -> halt ui _ -> helpHandle ui ev Normal -> case ev of VtyEvent (EvKey (KChar 'q') []) -> halt ui -- EvKey (KChar 'l') [MCtrl] -> do VtyEvent (EvKey KEsc []) -> continue $ resetScreens d ui VtyEvent (EvKey (KChar c) []) | c `elem` ['?'] -> continue $ setMode Help ui -- XXX AppEvents currently handled only in Normal mode -- XXX be sure we don't leave unconsumed events piling up AppEvent (DateChange old _) | isStandardPeriod p && p `periodContainsDate` old -> continue $ regenerateScreens j d $ setReportPeriod (DayPeriod d) ui where p = reportPeriod ui e | e `elem` [VtyEvent (EvKey (KChar 'g') []), AppEvent FileChange] -> liftIO (uiReloadJournal copts d ui) >>= continue VtyEvent (EvKey (KChar 'I') []) -> continue $ uiCheckBalanceAssertions d (toggleIgnoreBalanceAssertions ui) VtyEvent (EvKey (KChar 'a') []) -> suspendAndResume $ clearScreen >> setCursorPosition 0 0 >> add copts j >> uiReloadJournalIfChanged copts d j ui VtyEvent (EvKey (KChar 'A') []) -> suspendAndResume $ void (runIadd (journalFilePath j)) >> uiReloadJournalIfChanged copts d j ui VtyEvent (EvKey (KChar 'E') []) -> suspendAndResume $ void (runEditor endPos (journalFilePath j)) >> uiReloadJournalIfChanged copts d j ui VtyEvent (EvKey (KChar '0') []) -> continue $ regenerateScreens j d $ setDepth (Just 0) ui VtyEvent (EvKey (KChar '1') []) -> continue $ regenerateScreens j d $ setDepth (Just 1) ui VtyEvent (EvKey (KChar '2') []) -> continue $ regenerateScreens j d $ setDepth (Just 2) ui VtyEvent (EvKey (KChar '3') []) -> continue $ regenerateScreens j d $ setDepth (Just 3) ui VtyEvent (EvKey (KChar '4') []) -> continue $ regenerateScreens j d $ setDepth (Just 4) ui VtyEvent (EvKey (KChar '5') []) -> continue $ regenerateScreens j d $ setDepth (Just 5) ui VtyEvent (EvKey (KChar '6') []) -> continue $ regenerateScreens j d $ setDepth (Just 6) ui VtyEvent (EvKey (KChar '7') []) -> continue $ regenerateScreens j d $ setDepth (Just 7) ui VtyEvent (EvKey (KChar '8') []) -> continue $ regenerateScreens j d $ setDepth (Just 8) ui VtyEvent (EvKey (KChar '9') []) -> continue $ regenerateScreens j d $ setDepth (Just 9) ui VtyEvent (EvKey (KChar '-') []) -> continue $ regenerateScreens j d $ decDepth ui VtyEvent (EvKey (KChar '_') []) -> continue $ regenerateScreens j d $ decDepth ui VtyEvent (EvKey (KChar c) []) | c `elem` ['+','='] -> continue $ regenerateScreens j d $ incDepth ui VtyEvent (EvKey (KChar 't') []) -> continue $ regenerateScreens j d $ setReportPeriod (DayPeriod d) ui VtyEvent (EvKey (KChar 'H') []) -> continue $ regenerateScreens j d $ toggleHistorical ui VtyEvent (EvKey (KChar 'F') []) -> continue $ regenerateScreens j d $ toggleFlat ui VtyEvent (EvKey (KChar 'Z') []) -> scrollTop >> (continue $ regenerateScreens j d $ toggleEmpty ui) VtyEvent (EvKey (KChar 'C') []) -> scrollTop >> (continue $ regenerateScreens j d $ toggleCleared ui) VtyEvent (EvKey (KChar 'U') []) -> scrollTop >> (continue $ regenerateScreens j d $ toggleUncleared ui) VtyEvent (EvKey (KChar 'R') []) -> scrollTop >> (continue $ regenerateScreens j d $ toggleReal ui) VtyEvent (EvKey (KDown) [MShift]) -> continue $ regenerateScreens j d $ shrinkReportPeriod d ui VtyEvent (EvKey (KUp) [MShift]) -> continue $ regenerateScreens j d $ growReportPeriod d ui VtyEvent (EvKey (KRight) [MShift]) -> continue $ regenerateScreens j d $ nextReportPeriod journalspan ui VtyEvent (EvKey (KLeft) [MShift]) -> continue $ regenerateScreens j d $ previousReportPeriod journalspan ui VtyEvent (EvKey (KChar '/') []) -> continue $ regenerateScreens j d $ showMinibuffer ui VtyEvent (EvKey k []) | k `elem` [KBS, KDel] -> (continue $ regenerateScreens j d $ resetFilter ui) VtyEvent (EvKey k []) | k `elem` [KLeft, KChar 'h'] -> continue $ popScreen ui VtyEvent (EvKey k []) | k `elem` [KRight, KChar 'l'] -> scrollTopRegister >> continue (screenEnter d scr ui) where scr = rsSetAccount selacct isdepthclipped registerScreen isdepthclipped = case getDepth ui of Just d -> accountNameLevel selacct >= d Nothing -> False -- fall through to the list's event handler (handles up/down) VtyEvent ev -> do let ev' = case ev of EvKey (KChar 'k') [] -> EvKey (KUp) [] EvKey (KChar 'j') [] -> EvKey (KDown) [] _ -> ev newitems <- handleListEvent ev' _asList continue $ ui{aScreen=scr & asList .~ newitems & asSelectedAccount .~ selacct } -- continue =<< handleEventLensed ui someLens ev AppEvent _ -> continue ui MouseDown _ _ _ _ -> continue ui MouseUp _ _ _ -> continue ui where -- Encourage a more stable scroll position when toggling list items. -- We scroll to the top, and the viewport will automatically -- scroll down just far enough to reveal the selection, which -- usually leaves it at bottom of screen). -- XXX better: scroll so selection is in middle of screen ? scrollTop = vScrollToBeginning $ viewportScroll AccountsViewport scrollTopRegister = vScrollToBeginning $ viewportScroll RegisterViewport journalspan = journalDateSpan False j asHandle _ _ = error "event handler called with wrong screen type, should not happen" asSetSelectedAccount a s@AccountsScreen{} = s & asSelectedAccount .~ a asSetSelectedAccount _ s = s hledger-ui-1.2/Hledger/UI/Editor.hs0000644000000000000000000000717213035510426015246 0ustar0000000000000000{- | Editor integration. -} -- {-# LANGUAGE OverloadedStrings #-} module Hledger.UI.Editor where import Control.Applicative ((<|>)) import Data.List import Safe import System.Environment import System.Exit import System.FilePath import System.Process import Hledger -- | Editors we know how to create more specific command lines for. data EditorType = Emacs | EmacsClient | Vi | Other -- | A position we can move to in a text editor: a line and optional column number. -- 1 (or 0) means the first and -1 means the last (and -2 means the second last, etc. -- though this may not be well supported.) type TextPosition = (Int, Maybe Int) endPos :: Maybe TextPosition endPos = Just (-1,Nothing) -- | Run the hledger-iadd executable (an alternative to the built-in add command), -- or raise an error. runIadd :: FilePath -> IO ExitCode runIadd f = runCommand ("hledger-iadd -f " ++ f) >>= waitForProcess -- | Try running the user's preferred text editor, or a default edit command, -- on the main journal file, blocking until it exits, and returning the exit code; -- or raise an error. runEditor :: Maybe TextPosition -> FilePath -> IO ExitCode runEditor mpos f = editorOpenPositionCommand mpos f >>= runCommand >>= waitForProcess -- Get the basic shell command to start the user's preferred text editor. -- This is the value of environment variable $HLEDGER_UI_EDITOR, or $EDITOR, or -- a default (emacsclient -a '' -nw, start/connect to an emacs daemon in terminal mode). editorCommand :: IO String editorCommand = do hledger_ui_editor_env <- lookupEnv "HLEDGER_UI_EDITOR" editor_env <- lookupEnv "EDITOR" let Just cmd = hledger_ui_editor_env <|> editor_env <|> Just "emacsclient -a '' -nw" return cmd -- | Get a shell command to start the user's preferred text editor, or a default, -- and optionally jump to a given position in the file. This will be the basic -- editor command, with the appropriate options added, if we know how. -- Currently we know how to do this for emacs and vi. -- Some examples: -- $EDITOR=notepad -> "notepad FILE" -- $EDITOR=vi -> "vi +LINE FILE" -- $EDITOR=vi, line -1 -> "vi + FILE" -- $EDITOR=emacs -> "emacs +LINE:COL FILE" -- $EDITOR=emacs, line -1 -> "emacs FILE -f end-of-buffer" -- $EDITOR not set -> "emacs -nw FILE -f end-of-buffer" -- editorOpenPositionCommand :: Maybe TextPosition -> FilePath -> IO String editorOpenPositionCommand mpos f = do cmd <- editorCommand let f' = singleQuoteIfNeeded f return $ case (identifyEditor cmd, mpos) of (EmacsClient, Just (l,mc)) | l >= 0 -> cmd ++ " " ++ emacsposopt l mc ++ " " ++ f' (EmacsClient, Just (l,mc)) | l < 0 -> cmd ++ " " ++ emacsposopt 999999999 mc ++ " " ++ f' (Emacs, Just (l,mc)) | l >= 0 -> cmd ++ " " ++ emacsposopt l mc ++ " " ++ f' (Emacs, Just (l,_)) | l < 0 -> cmd ++ " " ++ f' ++ " -f end-of-buffer" (Vi, Just (l,_)) -> cmd ++ " " ++ viposopt l ++ " " ++ f' _ -> cmd ++ " " ++ f' where emacsposopt l mc = "+" ++ show l ++ maybe "" ((":"++).show) mc viposopt l = "+" ++ if l >= 0 then show l else "" -- Identify which text editor is used in the basic editor command, if possible. identifyEditor :: String -> EditorType identifyEditor cmd | "emacsclient" `isPrefixOf` exe = EmacsClient | "emacs" `isPrefixOf` exe = Emacs | exe `elem` ["vi","vim","ex","view","gvim","gview","evim","eview","rvim","rview","rgvim","rgview"] = Vi | otherwise = Other where exe = lowercase $ takeFileName $ headDef "" $ words' cmd hledger-ui-1.2/Hledger/UI/ErrorScreen.hs0000644000000000000000000001464613035510426016255 0ustar0000000000000000-- The error screen, showing a current error condition (such as a parse error after reloading the journal) {-# LANGUAGE OverloadedStrings, FlexibleContexts, RecordWildCards #-} module Hledger.UI.ErrorScreen (errorScreen ,uiCheckBalanceAssertions ,uiReloadJournal ,uiReloadJournalIfChanged ) where import Brick -- import Brick.Widgets.Border (borderAttr) import Control.Monad import Control.Monad.IO.Class (liftIO) import Data.Monoid import Data.Time.Calendar (Day) import Graphics.Vty (Event(..),Key(..)) import Text.Megaparsec import Hledger.Cli hiding (progname,prognameandversion,green) import Hledger.UI.UIOptions import Hledger.UI.UITypes import Hledger.UI.UIState import Hledger.UI.UIUtils import Hledger.UI.Editor errorScreen :: Screen errorScreen = ErrorScreen{ sInit = esInit ,sDraw = esDraw ,sHandle = esHandle ,esError = "" } esInit :: Day -> Bool -> UIState -> UIState esInit _ _ ui@UIState{aScreen=ErrorScreen{}} = ui esInit _ _ _ = error "init function called with wrong screen type, should not happen" esDraw :: UIState -> [Widget Name] esDraw UIState{ --aopts=UIOpts{cliopts_=copts@CliOpts{}} aScreen=ErrorScreen{..} ,aMode=mode} = case mode of Help -> [helpDialog, maincontent] -- Minibuffer e -> [minibuffer e, maincontent] _ -> [maincontent] where maincontent = Widget Greedy Greedy $ do render $ defaultLayout toplabel bottomlabel $ withAttr "error" $ str $ esError where toplabel = withAttr ("border" <> "bold") (str "Oops. Please fix this problem then press g to reload") -- <+> (if ignore_assertions_ copts then withAttr (borderAttr <> "query") (str " ignoring") else str " not ignoring") bottomlabel = case mode of -- Minibuffer ed -> minibuffer ed _ -> quickhelp where quickhelp = borderKeysStr [ ("h", "help") ,("ESC", "cancel/top") ,("E", "editor") ,("g", "reload") ,("q", "quit") ] esDraw _ = error "draw function called with wrong screen type, should not happen" esHandle :: UIState -> BrickEvent Name AppEvent -> EventM Name (Next UIState) esHandle ui@UIState{ aScreen=ErrorScreen{..} ,aopts=UIOpts{cliopts_=copts} ,ajournal=j ,aMode=mode } ev = case mode of Help -> case ev of VtyEvent (EvKey (KChar 'q') []) -> halt ui _ -> helpHandle ui ev _ -> do d <- liftIO getCurrentDay case ev of VtyEvent (EvKey (KChar 'q') []) -> halt ui VtyEvent (EvKey KEsc []) -> continue $ uiCheckBalanceAssertions d $ resetScreens d ui VtyEvent (EvKey (KChar c) []) | c `elem` ['h','?'] -> continue $ setMode Help ui VtyEvent (EvKey (KChar 'E') []) -> suspendAndResume $ void (runEditor pos f) >> uiReloadJournalIfChanged copts d j (popScreen ui) where (pos,f) = case parsewithString hledgerparseerrorpositionp esError of Right (f,l,c) -> (Just (l, Just c),f) Left _ -> (endPos, journalFilePath j) e | e `elem` [VtyEvent (EvKey (KChar 'g') []), AppEvent FileChange] -> liftIO (uiReloadJournal copts d (popScreen ui)) >>= continue . uiCheckBalanceAssertions d -- (ej, _) <- liftIO $ journalReloadIfChanged copts d j -- case ej of -- Left err -> continue ui{aScreen=s{esError=err}} -- show latest parse error -- Right j' -> continue $ regenerateScreens j' d $ popScreen ui -- return to previous screen, and reload it VtyEvent (EvKey (KChar 'I') []) -> continue $ uiCheckBalanceAssertions d (popScreen $ toggleIgnoreBalanceAssertions ui) _ -> continue ui esHandle _ _ = error "event handler called with wrong screen type, should not happen" -- | Parse the file name, line and column number from a hledger parse error message, if possible. -- Temporary, we should keep the original parse error location. XXX hledgerparseerrorpositionp :: ParsecT Dec String t (String, Int, Int) hledgerparseerrorpositionp = do anyChar `manyTill` char '"' f <- anyChar `manyTill` (oneOf ['"','\n']) string " (line " l <- read <$> some digitChar string ", column " c <- read <$> some digitChar return (f, l, c) -- Unconditionally reload the journal, regenerating the current screen -- and all previous screens in the history. -- If reloading fails, enter the error screen, or if we're already -- on the error screen, update the error displayed. -- The provided CliOpts are used for reloading, and then saved -- in the UIState if reloading is successful (otherwise the -- ui state keeps its old cli opts.) -- Defined here so it can reference the error screen. uiReloadJournal :: CliOpts -> Day -> UIState -> IO UIState uiReloadJournal copts d ui = do ej <- journalReload copts return $ case ej of Right j -> regenerateScreens j d ui{aopts=(aopts ui){cliopts_=copts}} Left err -> case ui of UIState{aScreen=s@ErrorScreen{}} -> ui{aScreen=s{esError=err}} _ -> screenEnter d errorScreen{esError=err} ui -- Like uiReloadJournal, but does not bother re-parsing the journal if -- the file(s) have not changed since last loaded. Always regenerates -- the current and previous screens though, since opts or date may have changed. uiReloadJournalIfChanged :: CliOpts -> Day -> Journal -> UIState -> IO UIState uiReloadJournalIfChanged copts d j ui = do (ej, _changed) <- journalReloadIfChanged copts d j return $ case ej of Right j' -> regenerateScreens j' d ui{aopts=(aopts ui){cliopts_=copts}} Left err -> case ui of UIState{aScreen=s@ErrorScreen{}} -> ui{aScreen=s{esError=err}} _ -> screenEnter d errorScreen{esError=err} ui -- Re-check any balance assertions in the current journal, and if any -- fail, enter (or update) the error screen. Or if balance assertions -- are disabled, do nothing. uiCheckBalanceAssertions :: Day -> UIState -> UIState uiCheckBalanceAssertions d ui@UIState{aopts=UIOpts{cliopts_=copts}, ajournal=j} | ignore_assertions_ copts = ui | otherwise = case journalCheckBalanceAssertions j of Right _ -> ui Left err -> case ui of UIState{aScreen=s@ErrorScreen{}} -> ui{aScreen=s{esError=err}} _ -> screenEnter d errorScreen{esError=err} ui hledger-ui-1.2/Hledger/UI/Main.hs0000644000000000000000000002176213066173044014712 0ustar0000000000000000{-| hledger-ui - a hledger add-on providing a curses-style interface. Copyright (c) 2007-2015 Simon Michael Released under GPL version 3 or later. -} {-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} module Hledger.UI.Main where -- import Control.Applicative -- import Lens.Micro.Platform ((^.)) import Control.Concurrent (threadDelay) import Control.Concurrent.Async import Control.Monad -- import Control.Monad.IO.Class (liftIO) #if !MIN_VERSION_vty(0,15,0) import Data.Default (def) #endif -- import Data.Monoid -- import Data.List import Data.Maybe -- import Data.Text (Text) import qualified Data.Text as T -- import Data.Time.Calendar import Graphics.Vty (mkVty) import Safe import System.Exit import System.Directory import System.FilePath import System.FSNotify import Brick #if MIN_VERSION_brick(0,16,0) import qualified Brick.BChan as BC #else import Control.Concurrent.Chan (newChan, writeChan) #endif import Hledger import Hledger.Cli hiding (progname,prognameandversion,green) import Hledger.UI.UIOptions import Hledger.UI.UITypes import Hledger.UI.UIState (toggleHistorical) import Hledger.UI.Theme import Hledger.UI.AccountsScreen import Hledger.UI.RegisterScreen ---------------------------------------------------------------------- #if MIN_VERSION_brick(0,16,0) newChan :: IO (BC.BChan a) newChan = BC.newBChan 10 writeChan :: BC.BChan a -> a -> IO () writeChan = BC.writeBChan #endif main :: IO () main = do opts <- getHledgerUIOpts -- when (debug_ $ cliopts_ opts) $ printf "%s\n" prognameandversion >> printf "opts: %s\n" (show opts) run opts where run opts | "h" `inRawOpts` (rawopts_ $ cliopts_ opts) = putStr (showModeUsage uimode) >> exitSuccess | "help" `inRawOpts` (rawopts_ $ cliopts_ opts) = printHelpForTopic (topicForMode uimode) >> exitSuccess | "man" `inRawOpts` (rawopts_ $ cliopts_ opts) = runManForTopic (topicForMode uimode) >> exitSuccess | "info" `inRawOpts` (rawopts_ $ cliopts_ opts) = runInfoForTopic (topicForMode uimode) >> exitSuccess | "version" `inRawOpts` (rawopts_ $ cliopts_ opts) = putStrLn prognameandversion >> exitSuccess | "binary-filename" `inRawOpts` (rawopts_ $ cliopts_ opts) = putStrLn (binaryfilename progname) | otherwise = withJournalDoUICommand opts runBrickUi -- XXX withJournalDo specialised for UIOpts withJournalDoUICommand :: UIOpts -> (UIOpts -> Journal -> IO ()) -> IO () withJournalDoUICommand uopts@UIOpts{cliopts_=copts} cmd = do rulespath <- rulesFilePathFromOpts copts journalpath <- journalFilePathFromOpts copts ej <- readJournalFiles Nothing rulespath (not $ ignore_assertions_ copts) journalpath either error' (cmd uopts . journalApplyAliases (aliasesFromOpts copts)) ej runBrickUi :: UIOpts -> Journal -> IO () runBrickUi uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}} j = do d <- getCurrentDay let -- depth: is a bit different from other queries. In hledger cli, -- - reportopts{depth_} indicates --depth options -- - reportopts{query_} is the query arguments as a string -- - the report query is based on both of these. -- For hledger-ui, for now, move depth: arguments out of reportopts{query_} -- and into reportopts{depth_}, so that depth and other kinds of filter query -- can be displayed independently. uopts' = uopts{ cliopts_=copts{ reportopts_= ropts{ -- incorporate any depth: query args into depth_, -- any date: query args into period_ depth_ =depthfromoptsandargs, period_=periodfromoptsandargs, query_ =unwords -- as in ReportOptions, with same limitations [v | (k,v) <- rawopts_ copts, k=="args", not $ any (`isPrefixOf` v) ["depth","date"]], -- always disable boring account name eliding, unlike the CLI, for a more regular tree no_elide_=True, -- show items with zero amount by default, unlike the CLI empty_=True, -- show historical balances by default, unlike the CLI balancetype_=HistoricalBalance } } } where q = queryFromOpts d ropts depthfromoptsandargs = case queryDepth q of 99999 -> Nothing d -> Just d datespanfromargs = queryDateSpan (date2_ ropts) $ fst $ parseQuery d (T.pack $ query_ ropts) periodfromoptsandargs = dateSpanAsPeriod $ spansIntersect [periodAsDateSpan $ period_ ropts, datespanfromargs] -- XXX move this stuff into Options, UIOpts theme = maybe defaultTheme (fromMaybe defaultTheme . getTheme) $ maybestringopt "theme" $ rawopts_ copts mregister = maybestringopt "register" $ rawopts_ copts (scr, prevscrs) = case mregister of Nothing -> (accountsScreen, []) -- with --register, start on the register screen, and also put -- the accounts screen on the prev screens stack so you can exit -- to that as usual. Just apat -> (rsSetAccount acct False registerScreen, [ascr']) where acct = headDef (error' $ "--register "++apat++" did not match any account") $ filter (regexMatches apat . T.unpack) $ journalAccountNames j -- Initialising the accounts screen is awkward, requiring -- another temporary UIState value.. ascr' = aScreen $ asInit d True $ UIState{ aopts=uopts' ,ajournal=j ,aScreen=asSetSelectedAccount acct accountsScreen ,aPrevScreens=[] ,aMode=Normal } ui = (sInit scr) d True $ (if change_ uopts' then toggleHistorical else id) $ -- XXX UIState{ aopts=uopts' ,ajournal=j ,aScreen=scr ,aPrevScreens=prevscrs ,aMode=Normal } brickapp :: App (UIState) AppEvent Name brickapp = App { appStartEvent = return , appAttrMap = const theme , appChooseCursor = showFirstCursor , appHandleEvent = \ui ev -> sHandle (aScreen ui) ui ev , appDraw = \ui -> sDraw (aScreen ui) ui } if not (watch_ uopts') then void $ defaultMain brickapp ui else do -- a channel for sending misc. events to the app eventChan <- newChan -- start a background thread reporting changes in the current date -- use async for proper child termination in GHCI let watchDate old = do threadDelay 1000000 -- 1 s new <- getCurrentDay when (new /= old) $ do let dc = DateChange old new -- dbg1IO "datechange" dc -- XXX don't uncomment until dbg*IO fixed to use traceIO, GHC may block/end thread -- traceIO $ show dc writeChan eventChan dc watchDate new withAsync (getCurrentDay >>= watchDate) $ \_ -> do -- start one or more background threads reporting changes in the directories of our files -- XXX many quick successive saves causes the problems listed in BUGS -- with Debounce increased to 1s it easily gets stuck on an error or blank screen -- until you press g, but it becomes responsive again quickly. -- withManagerConf defaultConfig{confDebounce=Debounce 1} $ \mgr -> do -- with Debounce at the default 1ms it clears transient errors itself -- but gets tied up for ages withManager $ \mgr -> do dbg1IO "fsnotify using polling ?" $ isPollingManager mgr files <- mapM canonicalizePath $ map fst $ jfiles j let directories = nub $ sort $ map takeDirectory files dbg1IO "files" files dbg1IO "directories to watch" directories forM_ directories $ \d -> watchDir mgr d -- predicate: ignore changes not involving our files (\fev -> case fev of Modified f _ -> f `elem` files -- Added f _ -> f `elem` files -- Removed f _ -> f `elem` files -- we don't handle adding/removing journal files right now -- and there might be some of those events from tmp files -- clogging things up so let's ignore them _ -> False ) -- action: send event to app (\fev -> do -- return $ dbglog "fsnotify" $ showFSNEvent fev -- not working dbg1IO "fsnotify" $ showFSNEvent fev writeChan eventChan FileChange ) -- and start the app. Must be inside the withManager block #if MIN_VERSION_vty(0,15,0) let myVty = mkVty mempty #else let myVty = mkVty def #endif void $ customMain myVty (Just eventChan) brickapp ui showFSNEvent (Added f _) = "Added " ++ show f showFSNEvent (Modified f _) = "Modified " ++ show f showFSNEvent (Removed f _) = "Removed " ++ show f hledger-ui-1.2/Hledger/UI/RegisterScreen.hs0000644000000000000000000004022413066173044016744 0ustar0000000000000000-- The account register screen, showing transactions in an account, like hledger-web's register. {-# LANGUAGE OverloadedStrings, FlexibleContexts, RecordWildCards #-} module Hledger.UI.RegisterScreen (registerScreen ,rsSetAccount ) where import Lens.Micro.Platform ((^.)) import Control.Monad import Control.Monad.IO.Class (liftIO) import Data.List import Data.List.Split (splitOn) import Data.Monoid import Data.Maybe import qualified Data.Text as T import Data.Time.Calendar (Day) import qualified Data.Vector as V import Graphics.Vty (Event(..),Key(..),Modifier(..)) import Brick import Brick.Widgets.List import Brick.Widgets.Edit import Brick.Widgets.Border (borderAttr) import System.Console.ANSI import Hledger import Hledger.Cli hiding (progname,prognameandversion,green) import Hledger.UI.UIOptions -- import Hledger.UI.Theme import Hledger.UI.UITypes import Hledger.UI.UIState import Hledger.UI.UIUtils import Hledger.UI.Editor import Hledger.UI.TransactionScreen import Hledger.UI.ErrorScreen registerScreen :: Screen registerScreen = RegisterScreen{ sInit = rsInit ,sDraw = rsDraw ,sHandle = rsHandle ,rsList = list RegisterList V.empty 1 ,rsAccount = "" ,rsForceInclusive = False } rsSetAccount :: AccountName -> Bool -> Screen -> Screen rsSetAccount a forceinclusive scr@RegisterScreen{} = scr{rsAccount=replaceHiddenAccountsNameWith "*" a, rsForceInclusive=forceinclusive} rsSetAccount _ _ scr = scr rsInit :: Day -> Bool -> UIState -> UIState rsInit d reset ui@UIState{aopts=UIOpts{cliopts_=CliOpts{reportopts_=ropts}}, ajournal=j, aScreen=s@RegisterScreen{..}} = ui{aScreen=s{rsList=newitems'}} where -- gather arguments and queries -- XXX temp inclusive = not (flat_ ropts) || rsForceInclusive thisacctq = Acct $ (if inclusive then accountNameToAccountRegex else accountNameToAccountOnlyRegex) rsAccount ropts' = ropts{ depth_=Nothing } q = queryFromOpts d ropts' -- reportq = filterQuery (not . queryIsDepth) q (_label,items) = accountTransactionsReport ropts' j q thisacctq items' = (if empty_ ropts' then id else filter (not . isZeroMixedAmount . fifth6)) $ -- without --empty, exclude no-change txns reverse -- most recent last items -- generate pre-rendered list items. This helps calculate column widths. displayitems = map displayitem items' where displayitem (t, _, _issplit, otheracctsstr, change, bal) = RegisterScreenItem{rsItemDate = showDate $ transactionRegisterDate q thisacctq t ,rsItemDescription = T.unpack $ tdescription t ,rsItemOtherAccounts = case splitOn ", " otheracctsstr of [s] -> s ss -> intercalate ", " ss -- _ -> "" -- should do this if accounts field width < 30 ,rsItemChangeAmount = showMixedAmountOneLineWithoutPrice change ,rsItemBalanceAmount = showMixedAmountOneLineWithoutPrice bal ,rsItemTransaction = t } -- build the List newitems = list RegisterList (V.fromList displayitems) 1 -- keep the selection on the previously selected transaction if possible, -- (eg after toggling nonzero mode), otherwise select the last element. newitems' = listMoveTo newselidx newitems where newselidx = case (reset, listSelectedElement rsList) of (True, _) -> endidx (_, Nothing) -> endidx (_, Just (_,RegisterScreenItem{rsItemTransaction=Transaction{tindex=ti}})) -> fromMaybe endidx $ findIndex ((==ti) . tindex . rsItemTransaction) displayitems endidx = length displayitems rsInit _ _ _ = error "init function called with wrong screen type, should not happen" rsDraw :: UIState -> [Widget Name] rsDraw UIState{aopts=UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}} ,aScreen=RegisterScreen{..} ,aMode=mode } = case mode of Help -> [helpDialog, maincontent] -- Minibuffer e -> [minibuffer e, maincontent] _ -> [maincontent] where displayitems = V.toList $ rsList ^. listElementsL maincontent = Widget Greedy Greedy $ do -- calculate column widths, based on current available width c <- getContext let totalwidth = c^.availWidthL - 2 -- XXX due to margin ? shouldn't be necessary (cf UIUtils) -- the date column is fixed width datewidth = 10 -- multi-commodity amounts rendered on one line can be -- arbitrarily wide. Give the two amounts as much space as -- they need, while reserving a minimum of space for other -- columns and whitespace. If they don't get all they need, -- allocate it to them proportionally to their maximum widths. whitespacewidth = 10 -- inter-column whitespace, fixed width minnonamtcolswidth = datewidth + 2 + 2 -- date column plus at least 2 for desc and accts maxamtswidth = max 0 (totalwidth - minnonamtcolswidth - whitespacewidth) maxchangewidthseen = maximum' $ map (strWidth . rsItemChangeAmount) displayitems maxbalwidthseen = maximum' $ map (strWidth . rsItemBalanceAmount) displayitems changewidthproportion = fromIntegral maxchangewidthseen / fromIntegral (maxchangewidthseen + maxbalwidthseen) maxchangewidth = round $ changewidthproportion * fromIntegral maxamtswidth maxbalwidth = maxamtswidth - maxchangewidth changewidth = min maxchangewidth maxchangewidthseen balwidth = min maxbalwidth maxbalwidthseen -- assign the remaining space to the description and accounts columns -- maxdescacctswidth = totalwidth - (whitespacewidth - 4) - changewidth - balwidth maxdescacctswidth = -- trace (show (totalwidth, datewidth, changewidth, balwidth, whitespacewidth)) $ max 0 (totalwidth - datewidth - changewidth - balwidth - whitespacewidth) -- allocating proportionally. -- descwidth' = maximum' $ map (strWidth . second6) displayitems -- acctswidth' = maximum' $ map (strWidth . third6) displayitems -- descwidthproportion = (descwidth' + acctswidth') / descwidth' -- maxdescwidth = min (maxdescacctswidth - 7) (maxdescacctswidth / descwidthproportion) -- maxacctswidth = maxdescacctswidth - maxdescwidth -- descwidth = min maxdescwidth descwidth' -- acctswidth = min maxacctswidth acctswidth' -- allocating equally. descwidth = maxdescacctswidth `div` 2 acctswidth = maxdescacctswidth - descwidth colwidths = (datewidth,descwidth,acctswidth,changewidth,balwidth) render $ defaultLayout toplabel bottomlabel $ renderList (rsDrawItem colwidths) True rsList where ishistorical = balancetype_ ropts == HistoricalBalance inclusive = not (flat_ ropts) || rsForceInclusive toplabel = withAttr ("border" <> "bold") (str $ T.unpack $ replaceHiddenAccountsNameWith "All" rsAccount) -- <+> withAttr (borderAttr <> "query") (str $ if inclusive then "" else " exclusive") <+> togglefilters <+> str " transactions" -- <+> str (if ishistorical then " historical total" else " period total") <+> borderQueryStr (query_ ropts) -- <+> str " and subs" <+> borderPeriodStr "in" (period_ ropts) <+> str " (" <+> cur <+> str "/" <+> total <+> str ")" <+> (if ignore_assertions_ copts then withAttr (borderAttr <> "query") (str " ignoring balance assertions") else str "") where togglefilters = case concat [ uiShowClearedStatus $ clearedstatus_ ropts ,if real_ ropts then ["real"] else [] ,if empty_ ropts then [] else ["nonzero"] ] of [] -> str "" fs -> withAttr (borderAttr <> "query") (str $ " " ++ intercalate ", " fs) cur = str $ case rsList ^. listSelectedL of Nothing -> "-" Just i -> show (i + 1) total = str $ show $ length displayitems -- query = query_ $ reportopts_ $ cliopts_ opts bottomlabel = case mode of Minibuffer ed -> minibuffer ed _ -> quickhelp where selectedstr = withAttr (borderAttr <> "query") . str quickhelp = borderKeysStr' [ ("?", str "help") ,("left", str "back") ,("right", str "transaction") ,("H" ,if ishistorical then selectedstr "historical" <+> str "/period" else str "historical/" <+> selectedstr "period") ,("F" ,if inclusive then selectedstr "inclusive" <+> str "/exclusive" else str "inclusive/" <+> selectedstr "exclusive") -- ,("a", "add") -- ,("g", "reload") -- ,("q", "quit") ] rsDraw _ = error "draw function called with wrong screen type, should not happen" rsDrawItem :: (Int,Int,Int,Int,Int) -> Bool -> RegisterScreenItem -> Widget Name rsDrawItem (datewidth,descwidth,acctswidth,changewidth,balwidth) selected RegisterScreenItem{..} = Widget Greedy Fixed $ do render $ str (fitString (Just datewidth) (Just datewidth) True True rsItemDate) <+> str " " <+> str (fitString (Just descwidth) (Just descwidth) True True rsItemDescription) <+> str " " <+> str (fitString (Just acctswidth) (Just acctswidth) True True rsItemOtherAccounts) <+> str " " <+> withAttr changeattr (str (fitString (Just changewidth) (Just changewidth) True False rsItemChangeAmount)) <+> str " " <+> withAttr balattr (str (fitString (Just balwidth) (Just balwidth) True False rsItemBalanceAmount)) where changeattr | '-' `elem` rsItemChangeAmount = sel $ "list" <> "amount" <> "decrease" | otherwise = sel $ "list" <> "amount" <> "increase" balattr | '-' `elem` rsItemBalanceAmount = sel $ "list" <> "balance" <> "negative" | otherwise = sel $ "list" <> "balance" <> "positive" sel | selected = (<> "selected") | otherwise = id rsHandle :: UIState -> BrickEvent Name AppEvent -> EventM Name (Next UIState) rsHandle ui@UIState{ aScreen=s@RegisterScreen{..} ,aopts=UIOpts{cliopts_=copts} ,ajournal=j ,aMode=mode } ev = do d <- liftIO getCurrentDay case mode of Minibuffer ed -> case ev of VtyEvent (EvKey KEsc []) -> continue $ closeMinibuffer ui VtyEvent (EvKey KEnter []) -> continue $ regenerateScreens j d $ setFilter s $ closeMinibuffer ui where s = chomp $ unlines $ map strip $ getEditContents ed VtyEvent ev -> do ed' <- handleEditorEvent ev ed continue $ ui{aMode=Minibuffer ed'} AppEvent _ -> continue ui MouseDown _ _ _ _ -> continue ui MouseUp _ _ _ -> continue ui Help -> case ev of VtyEvent (EvKey (KChar 'q') []) -> halt ui _ -> helpHandle ui ev Normal -> case ev of VtyEvent (EvKey (KChar 'q') []) -> halt ui VtyEvent (EvKey KEsc []) -> continue $ resetScreens d ui VtyEvent (EvKey (KChar c) []) | c `elem` ['?'] -> continue $ setMode Help ui AppEvent (DateChange old _) | isStandardPeriod p && p `periodContainsDate` old -> continue $ regenerateScreens j d $ setReportPeriod (DayPeriod d) ui where p = reportPeriod ui e | e `elem` [VtyEvent (EvKey (KChar 'g') []), AppEvent FileChange] -> liftIO (uiReloadJournal copts d ui) >>= continue VtyEvent (EvKey (KChar 'I') []) -> continue $ uiCheckBalanceAssertions d (toggleIgnoreBalanceAssertions ui) VtyEvent (EvKey (KChar 'a') []) -> suspendAndResume $ clearScreen >> setCursorPosition 0 0 >> add copts j >> uiReloadJournalIfChanged copts d j ui VtyEvent (EvKey (KChar 'A') []) -> suspendAndResume $ void (runIadd (journalFilePath j)) >> uiReloadJournalIfChanged copts d j ui VtyEvent (EvKey (KChar 't') []) -> continue $ regenerateScreens j d $ setReportPeriod (DayPeriod d) ui VtyEvent (EvKey (KChar 'E') []) -> suspendAndResume $ void (runEditor pos f) >> uiReloadJournalIfChanged copts d j ui where (pos,f) = case listSelectedElement rsList of Nothing -> (endPos, journalFilePath j) Just (_, RegisterScreenItem{ rsItemTransaction=Transaction{tsourcepos=GenericSourcePos f l c}}) -> (Just (l, Just c),f) Just (_, RegisterScreenItem{ rsItemTransaction=Transaction{tsourcepos=JournalSourcePos f (l,_)}}) -> (Just (l, Nothing),f) VtyEvent (EvKey (KChar 'H') []) -> continue $ regenerateScreens j d $ toggleHistorical ui VtyEvent (EvKey (KChar 'F') []) -> scrollTop >> (continue $ regenerateScreens j d $ toggleFlat ui) VtyEvent (EvKey (KChar 'Z') []) -> scrollTop >> (continue $ regenerateScreens j d $ toggleEmpty ui) VtyEvent (EvKey (KChar 'C') []) -> scrollTop >> (continue $ regenerateScreens j d $ toggleCleared ui) VtyEvent (EvKey (KChar 'U') []) -> scrollTop >> (continue $ regenerateScreens j d $ toggleUncleared ui) VtyEvent (EvKey (KChar 'R') []) -> scrollTop >> (continue $ regenerateScreens j d $ toggleReal ui) VtyEvent (EvKey (KChar '/') []) -> (continue $ regenerateScreens j d $ showMinibuffer ui) VtyEvent (EvKey (KDown) [MShift]) -> continue $ regenerateScreens j d $ shrinkReportPeriod d ui VtyEvent (EvKey (KUp) [MShift]) -> continue $ regenerateScreens j d $ growReportPeriod d ui VtyEvent (EvKey (KRight) [MShift]) -> continue $ regenerateScreens j d $ nextReportPeriod journalspan ui VtyEvent (EvKey (KLeft) [MShift]) -> continue $ regenerateScreens j d $ previousReportPeriod journalspan ui VtyEvent (EvKey k []) | k `elem` [KBS, KDel] -> (continue $ regenerateScreens j d $ resetFilter ui) VtyEvent (EvKey k []) | k `elem` [KLeft, KChar 'h'] -> continue $ popScreen ui VtyEvent (EvKey k []) | k `elem` [KRight, KChar 'l'] -> do case listSelectedElement rsList of Just (_, RegisterScreenItem{rsItemTransaction=t}) -> let ts = map rsItemTransaction $ V.toList $ listElements rsList numberedts = zip [1..] ts i = fromIntegral $ maybe 0 (+1) $ elemIndex t ts -- XXX in continue $ screenEnter d transactionScreen{tsTransaction=(i,t) ,tsTransactions=numberedts ,tsAccount=rsAccount} ui Nothing -> continue ui -- fall through to the list's event handler (handles [pg]up/down) VtyEvent ev -> do let ev' = case ev of EvKey (KChar 'k') [] -> EvKey (KUp) [] EvKey (KChar 'j') [] -> EvKey (KDown) [] _ -> ev newitems <- handleListEvent ev' rsList continue ui{aScreen=s{rsList=newitems}} -- continue =<< handleEventLensed ui someLens ev AppEvent _ -> continue ui MouseDown _ _ _ _ -> continue ui MouseUp _ _ _ -> continue ui where -- Encourage a more stable scroll position when toggling list items (cf AccountsScreen.hs) scrollTop = vScrollToBeginning $ viewportScroll RegisterViewport journalspan = journalDateSpan False j rsHandle _ _ = error "event handler called with wrong screen type, should not happen" hledger-ui-1.2/Hledger/UI/Theme.hs0000644000000000000000000001202313035210046015044 0ustar0000000000000000-- | The all-important theming engine! -- -- Cf -- https://hackage.haskell.org/package/vty/docs/Graphics-Vty-Attributes.html -- http://hackage.haskell.org/package/brick/docs/Brick-AttrMap.html -- http://hackage.haskell.org/package/brick-0.1/docs/Brick-Util.html -- http://hackage.haskell.org/package/brick-0.1/docs/Brick-Widgets-Core.html#g:5 -- http://hackage.haskell.org/package/brick-0.1/docs/Brick-Widgets-Border.html {-# LANGUAGE OverloadedStrings #-} module Hledger.UI.Theme ( defaultTheme ,getTheme ,themes ,themeNames ) where import qualified Data.Map as M import Data.Maybe import Data.Monoid import Graphics.Vty import Brick import Brick.Widgets.Border import Brick.Widgets.List defaultTheme :: AttrMap defaultTheme = fromMaybe (snd $ head themesList) $ getTheme "white" -- the theme named here should exist; -- otherwise it will take the first one from the list, -- which must be non-empty. -- | Look up the named theme, if it exists. getTheme :: String -> Maybe AttrMap getTheme name = M.lookup name themes -- | A selection of named themes specifying terminal colours and styles. -- One of these is active at a time. -- -- A hledger-ui theme is a vty/brick AttrMap. Each theme specifies a -- default style (Attr), plus extra styles which are applied when -- their (hierarchical) name matches the widget rendering context. -- "More specific styles, if present, are used and only fall back to -- more general ones when the more specific ones are absent, but also -- these styles get merged, so that if a more specific style only -- provides the foreground color, its more general parent style can -- set the background color, too." -- For example: rendering a widget named "b" inside a widget named "a", -- - if a style named "a" <> "b" exists, it will be used. Anything it -- does not specify will be taken from a style named "a" if that -- exists, otherwise from the default style. -- - otherwise if a style named "a" exists, it will be used, and -- anything it does not specify will be taken from the default style. -- - otherwise (you guessed it) the default style is used. -- themes :: M.Map String AttrMap themes = M.fromList themesList themeNames :: [String] themeNames = map fst themesList (&) = withStyle themesList :: [(String, AttrMap)] themesList = [ ("default", attrMap (black `on` white & bold) [ -- default style for this theme ("error", currentAttr `withForeColor` red), (borderAttr , white `on` black & dim), (borderAttr <> "bold", white `on` black & bold), (borderAttr <> "query", cyan `on` black & bold), (borderAttr <> "depth", yellow `on` black & bold), (borderAttr <> "keys", white `on` black & bold), (borderAttr <> "minibuffer", white `on` black & bold), -- ("normal" , black `on` white), ("list" , black `on` white), -- regular list items ("list" <> "selected" , white `on` blue & bold), -- selected list items -- ("list" <> "selected" , black `on` brightYellow), -- ("list" <> "accounts" , white `on` brightGreen), ("list" <> "amount" <> "increase", currentAttr `withForeColor` green), ("list" <> "amount" <> "decrease", currentAttr `withForeColor` red), ("list" <> "balance" <> "positive", currentAttr `withForeColor` black), ("list" <> "balance" <> "negative", currentAttr `withForeColor` red), ("list" <> "amount" <> "increase" <> "selected", brightGreen `on` blue & bold), ("list" <> "amount" <> "decrease" <> "selected", brightRed `on` blue & bold), ("list" <> "balance" <> "positive" <> "selected", white `on` blue & bold), ("list" <> "balance" <> "negative" <> "selected", brightRed `on` blue & bold) ]), ("terminal", attrMap defAttr [ -- use the current terminal's default style (borderAttr , white `on` black), -- ("normal" , defAttr), (listAttr , defAttr), (listSelectedAttr , defAttr & reverseVideo & bold) -- ("status" , defAttr & reverseVideo) ]), ("greenterm", attrMap (green `on` black) [ -- (listAttr , green `on` black), (listSelectedAttr , black `on` green & bold) ]) -- ("colorful", attrMap -- defAttr [ -- (listAttr , defAttr & reverseVideo), -- (listSelectedAttr , defAttr `withForeColor` white `withBackColor` red) -- -- ("status" , defAttr `withForeColor` black `withBackColor` green) -- ]) ] -- halfbrightattr = defAttr & dim -- reverseattr = defAttr & reverseVideo -- redattr = defAttr `withForeColor` red -- greenattr = defAttr `withForeColor` green -- reverseredattr = defAttr & reverseVideo `withForeColor` red -- reversegreenattr= defAttr & reverseVideo `withForeColor` green hledger-ui-1.2/Hledger/UI/TransactionScreen.hs0000644000000000000000000002022313066173044017442 0ustar0000000000000000-- The transaction screen, showing a single transaction's general journal entry. {-# LANGUAGE OverloadedStrings, TupleSections, RecordWildCards #-} -- , FlexibleContexts module Hledger.UI.TransactionScreen (transactionScreen ,rsSelect ) where import Control.Monad import Control.Monad.IO.Class (liftIO) import Data.List import Data.Monoid import qualified Data.Text as T import Data.Time.Calendar (Day) import Graphics.Vty (Event(..),Key(..)) import Brick import Brick.Widgets.List (listMoveTo) import Brick.Widgets.Border (borderAttr) import Hledger import Hledger.Cli hiding (progname,prognameandversion,green) import Hledger.UI.UIOptions -- import Hledger.UI.Theme import Hledger.UI.UITypes import Hledger.UI.UIState import Hledger.UI.UIUtils import Hledger.UI.Editor import Hledger.UI.ErrorScreen transactionScreen :: Screen transactionScreen = TransactionScreen{ sInit = tsInit ,sDraw = tsDraw ,sHandle = tsHandle ,tsTransaction = (1,nulltransaction) ,tsTransactions = [(1,nulltransaction)] ,tsAccount = "" } tsInit :: Day -> Bool -> UIState -> UIState tsInit _d _reset ui@UIState{aopts=UIOpts{cliopts_=CliOpts{reportopts_=_ropts}} ,ajournal=_j ,aScreen=TransactionScreen{..}} = ui tsInit _ _ _ = error "init function called with wrong screen type, should not happen" tsDraw :: UIState -> [Widget Name] tsDraw UIState{aopts=UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}} ,aScreen=TransactionScreen{ tsTransaction=(i,t) ,tsTransactions=nts ,tsAccount=acct} ,aMode=mode} = case mode of Help -> [helpDialog, maincontent] -- Minibuffer e -> [minibuffer e, maincontent] _ -> [maincontent] where maincontent = Widget Greedy Greedy $ do render $ defaultLayout toplabel bottomlabel $ str $ showTransactionUnelidedOneLineAmounts $ -- (if real_ ropts then filterTransactionPostings (Real True) else id) -- filter postings by --real t where toplabel = str "Transaction " -- <+> withAttr ("border" <> "bold") (str $ "#" ++ show (tindex t)) -- <+> str (" ("++show i++" of "++show (length nts)++" in "++acct++")") <+> (str $ "#" ++ show (tindex t)) <+> str " (" <+> withAttr ("border" <> "bold") (str $ show i) <+> str (" of "++show (length nts)) <+> togglefilters <+> borderQueryStr (query_ ropts) <+> str (" in "++T.unpack (replaceHiddenAccountsNameWith "All" acct)++")") <+> (if ignore_assertions_ copts then withAttr (borderAttr <> "query") (str " ignoring balance assertions") else str "") where togglefilters = case concat [ uiShowClearedStatus $ clearedstatus_ ropts ,if real_ ropts then ["real"] else [] ,if empty_ ropts then [] else ["nonzero"] ] of [] -> str "" fs -> withAttr (borderAttr <> "query") (str $ " " ++ intercalate ", " fs) bottomlabel = case mode of -- Minibuffer ed -> minibuffer ed _ -> quickhelp where quickhelp = borderKeysStr [ ("?", "help") ,("left", "back") ,("up/down", "prev/next") --,("ESC", "cancel/top") -- ,("a", "add") ,("E", "editor") ,("g", "reload") ,("q", "quit") ] tsDraw _ = error "draw function called with wrong screen type, should not happen" tsHandle :: UIState -> BrickEvent Name AppEvent -> EventM Name (Next UIState) tsHandle ui@UIState{aScreen=s@TransactionScreen{tsTransaction=(i,t) ,tsTransactions=nts ,tsAccount=acct} ,aopts=UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}} ,ajournal=j ,aMode=mode } ev = case mode of Help -> case ev of VtyEvent (EvKey (KChar 'q') []) -> halt ui _ -> helpHandle ui ev _ -> do d <- liftIO getCurrentDay let (iprev,tprev) = maybe (i,t) ((i-1),) $ lookup (i-1) nts (inext,tnext) = maybe (i,t) ((i+1),) $ lookup (i+1) nts case ev of VtyEvent (EvKey (KChar 'q') []) -> halt ui VtyEvent (EvKey KEsc []) -> continue $ resetScreens d ui VtyEvent (EvKey (KChar c) []) | c `elem` ['?'] -> continue $ setMode Help ui VtyEvent (EvKey (KChar 'E') []) -> suspendAndResume $ void (runEditor pos f) >> uiReloadJournalIfChanged copts d j ui where (pos,f) = case tsourcepos t of GenericSourcePos f l c -> (Just (l, Just c),f) JournalSourcePos f (l1,_) -> (Just (l1, Nothing),f) AppEvent (DateChange old _) | isStandardPeriod p && p `periodContainsDate` old -> continue $ regenerateScreens j d $ setReportPeriod (DayPeriod d) ui where p = reportPeriod ui e | e `elem` [VtyEvent (EvKey (KChar 'g') []), AppEvent FileChange] -> do d <- liftIO getCurrentDay ej <- liftIO $ journalReload copts case ej of Left err -> continue $ screenEnter d errorScreen{esError=err} ui Right j' -> do -- got to redo the register screen's transactions report, to get the latest transactions list for this screen -- XXX duplicates rsInit let ropts' = ropts {depth_=Nothing ,balancetype_=HistoricalBalance } q = filterQuery (not . queryIsDepth) $ queryFromOpts d ropts' thisacctq = Acct $ accountNameToAccountRegex acct -- includes subs items = reverse $ snd $ accountTransactionsReport ropts j' q thisacctq ts = map first6 items numberedts = zip [1..] ts -- select the best current transaction from the new list -- stay at the same index if possible, or if we are now past the end, select the last, otherwise select the first (i',t') = case lookup i numberedts of Just t'' -> (i,t'') Nothing | null numberedts -> (0,nulltransaction) | i > fst (last numberedts) -> last numberedts | otherwise -> head numberedts ui' = ui{aScreen=s{tsTransaction=(i',t') ,tsTransactions=numberedts ,tsAccount=acct}} continue $ regenerateScreens j' d ui' VtyEvent (EvKey (KChar 'I') []) -> continue $ uiCheckBalanceAssertions d (toggleIgnoreBalanceAssertions ui) -- if allowing toggling here, we should refresh the txn list from the parent register screen -- EvKey (KChar 'E') [] -> continue $ regenerateScreens j d $ stToggleEmpty ui -- EvKey (KChar 'C') [] -> continue $ regenerateScreens j d $ stToggleCleared ui -- EvKey (KChar 'R') [] -> continue $ regenerateScreens j d $ stToggleReal ui VtyEvent (EvKey k []) | k `elem` [KUp, KChar 'k'] -> continue $ regenerateScreens j d ui{aScreen=s{tsTransaction=(iprev,tprev)}} VtyEvent (EvKey k []) | k `elem` [KDown, KChar 'j'] -> continue $ regenerateScreens j d ui{aScreen=s{tsTransaction=(inext,tnext)}} VtyEvent (EvKey k []) | k `elem` [KLeft, KChar 'h'] -> continue ui'' where ui'@UIState{aScreen=scr} = popScreen ui ui'' = ui'{aScreen=rsSelect (fromIntegral i) scr} _ -> continue ui tsHandle _ _ = error "event handler called with wrong screen type, should not happen" -- | Select the nth item on the register screen. rsSelect i scr@RegisterScreen{..} = scr{rsList=l'} where l' = listMoveTo (i-1) rsList rsSelect _ scr = scr hledger-ui-1.2/Hledger/UI/UIOptions.hs0000644000000000000000000000672013066746043015721 0ustar0000000000000000{-# LANGUAGE CPP #-} {-| -} module Hledger.UI.UIOptions where import Data.Default #if !MIN_VERSION_base(4,8,0) import Data.Functor.Compat ((<$>)) #endif import Data.List (intercalate) import Hledger.Cli hiding (progname,version,prognameandversion) import Hledger.UI.Theme (themeNames) progname, version :: String progname = "hledger-ui" #ifdef VERSION version = VERSION #else version = "" #endif prognameandversion :: String prognameandversion = progname ++ " " ++ version :: String uiflags = [ -- flagNone ["debug-ui"] (\opts -> setboolopt "rules-file" opts) "run with no terminal output, showing console" flagNone ["watch"] (\opts -> setboolopt "watch" opts) "watch for data and date changes and reload automatically" ,flagReq ["theme"] (\s opts -> Right $ setopt "theme" s opts) "THEME" ("use this custom display theme ("++intercalate ", " themeNames++")") ,flagReq ["register"] (\s opts -> Right $ setopt "register" s opts) "ACCTREGEX" "start in the (first) matched account's register" ,flagNone ["change"] (\opts -> setboolopt "change" opts) "show period balances (changes) at startup instead of historical balances" -- ,flagNone ["cumulative"] (\opts -> setboolopt "cumulative" opts) -- "show balance change accumulated across periods (in multicolumn reports)" -- ,flagNone ["historical","H"] (\opts -> setboolopt "historical" opts) -- "show historical ending balance in each period (includes postings before report start date)\n " ,flagNone ["flat"] (\opts -> setboolopt "flat" opts) "show full account names, unindented" -- ,flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "with --flat, omit this many leading account name components" -- ,flagReq ["format"] (\s opts -> Right $ setopt "format" s opts) "FORMATSTR" "use this custom line format" -- ,flagNone ["no-elide"] (\opts -> setboolopt "no-elide" opts) "don't compress empty parent accounts on one line" ] --uimode :: Mode [([Char], [Char])] uimode = (mode "hledger-ui" [("command","ui")] "browse accounts, postings and entries in a full-window curses interface" (argsFlag "[PATTERNS]") []){ modeGroupFlags = Group { groupUnnamed = uiflags ,groupHidden = [] ,groupNamed = [(generalflagsgroup1)] } ,modeHelpSuffix=[ -- "Reads your ~/.hledger.journal file, or another specified by $LEDGER_FILE or -f, and starts the full-window curses ui." ] } -- hledger-ui options, used in hledger-ui and above data UIOpts = UIOpts { watch_ :: Bool ,change_ :: Bool ,cliopts_ :: CliOpts } deriving (Show) defuiopts = UIOpts def def def -- instance Default CliOpts where def = defcliopts rawOptsToUIOpts :: RawOpts -> IO UIOpts rawOptsToUIOpts rawopts = checkUIOpts <$> do cliopts <- rawOptsToCliOpts rawopts return defuiopts { watch_ = boolopt "watch" rawopts ,change_ = boolopt "change" rawopts ,cliopts_ = cliopts } checkUIOpts :: UIOpts -> UIOpts checkUIOpts opts = either usageError (const opts) $ do case maybestringopt "theme" $ rawopts_ $ cliopts_ opts of Just t | not $ elem t themeNames -> Left $ "invalid theme name: "++t _ -> Right () getHledgerUIOpts :: IO UIOpts getHledgerUIOpts = processArgs uimode >>= return . decodeRawOpts >>= rawOptsToUIOpts hledger-ui-1.2/Hledger/UI/UIState.hs0000644000000000000000000002407113035510426015333 0ustar0000000000000000{- | UIState operations. -} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Hledger.UI.UIState where import Brick import Brick.Widgets.Edit import Data.List import Data.Text.Zipper (gotoEOL) import Data.Time.Calendar (Day) import Hledger import Hledger.Cli.CliOptions import Hledger.UI.UITypes import Hledger.UI.UIOptions -- | Toggle between showing only cleared items or all items. toggleCleared :: UIState -> UIState toggleCleared ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=toggleCleared ropts}}} where toggleCleared ropts@ReportOpts{clearedstatus_=Just Cleared} = ropts{clearedstatus_=Nothing} toggleCleared ropts = ropts{clearedstatus_=Just Cleared} -- | Toggle between showing only pending items or all items. togglePending :: UIState -> UIState togglePending ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=togglePending ropts}}} where togglePending ropts@ReportOpts{clearedstatus_=Just Pending} = ropts{clearedstatus_=Nothing} togglePending ropts = ropts{clearedstatus_=Just Pending} -- | Toggle between showing only uncleared items or all items. toggleUncleared :: UIState -> UIState toggleUncleared ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=toggleUncleared ropts}}} where toggleUncleared ropts@ReportOpts{clearedstatus_=Just Uncleared} = ropts{clearedstatus_=Nothing} toggleUncleared ropts = ropts{clearedstatus_=Just Uncleared} -- | Toggle between showing all and showing only nonempty (more precisely, nonzero) items. toggleEmpty :: UIState -> UIState toggleEmpty ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=toggleEmpty ropts}}} where toggleEmpty ropts = ropts{empty_=not $ empty_ ropts} -- | Toggle between flat and tree mode. If in the third "default" mode, go to flat mode. toggleFlat :: UIState -> UIState toggleFlat ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=toggleFlatMode ropts}}} where toggleFlatMode ropts@ReportOpts{accountlistmode_=ALFlat} = ropts{accountlistmode_=ALTree} toggleFlatMode ropts = ropts{accountlistmode_=ALFlat} -- | Toggle between historical balances and period balances. toggleHistorical :: UIState -> UIState toggleHistorical ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{balancetype_=b}}}} where b | balancetype_ ropts == HistoricalBalance = PeriodChange | otherwise = HistoricalBalance -- | Toggle between showing all and showing only real (non-virtual) items. toggleReal :: UIState -> UIState toggleReal ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=toggleReal ropts}}} where toggleReal ropts = ropts{real_=not $ real_ ropts} -- | Toggle the ignoring of balance assertions. toggleIgnoreBalanceAssertions :: UIState -> UIState toggleIgnoreBalanceAssertions ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{}}} = ui{aopts=uopts{cliopts_=copts{ignore_assertions_=not $ ignore_assertions_ copts}}} -- | Step through larger report periods, up to all. growReportPeriod :: Day -> UIState -> UIState growReportPeriod _d ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{period_=periodGrow $ period_ ropts}}}} -- | Step through smaller report periods, down to a day. shrinkReportPeriod :: Day -> UIState -> UIState shrinkReportPeriod d ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{period_=periodShrink d $ period_ ropts}}}} -- | Step the report start/end dates to the next period of same duration, -- remaining inside the given enclosing span. nextReportPeriod :: DateSpan -> UIState -> UIState nextReportPeriod enclosingspan ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts@ReportOpts{period_=p}}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{period_=periodNextIn enclosingspan p}}}} -- | Step the report start/end dates to the next period of same duration, -- remaining inside the given enclosing span. previousReportPeriod :: DateSpan -> UIState -> UIState previousReportPeriod enclosingspan ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts@ReportOpts{period_=p}}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{period_=periodPreviousIn enclosingspan p}}}} -- | If a standard report period is set, step it forward/backward if needed so that -- it encloses the given date. moveReportPeriodToDate :: Day -> UIState -> UIState moveReportPeriodToDate d ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts@ReportOpts{period_=p}}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{period_=periodMoveTo d p}}}} -- | Get the report period. reportPeriod :: UIState -> Period reportPeriod UIState{aopts=UIOpts{cliopts_=CliOpts{reportopts_=ReportOpts{period_=p}}}} = p -- | Set the report period. setReportPeriod :: Period -> UIState -> UIState setReportPeriod p ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{period_=p}}}} -- | Apply a new filter query. setFilter :: String -> UIState -> UIState setFilter s ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{query_=s}}}} -- | Clear all filters/flags. resetFilter :: UIState -> UIState resetFilter ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{ accountlistmode_=ALTree ,empty_=True ,clearedstatus_=Nothing ,real_=False ,query_="" --,period_=PeriodAll }}}} resetDepth :: UIState -> UIState resetDepth ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{depth_=Nothing}}}} -- | Get the maximum account depth in the current journal. maxDepth :: UIState -> Int maxDepth UIState{ajournal=j} = maximum $ map accountNameLevel $ journalAccountNames j -- | Decrement the current depth limit towards 0. If there was no depth limit, -- set it to one less than the maximum account depth. decDepth :: UIState -> UIState decDepth ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts@ReportOpts{..}}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{depth_=dec depth_}}}} where dec (Just d) = Just $ max 0 (d-1) dec Nothing = Just $ maxDepth ui - 1 -- | Increment the current depth limit. If this makes it equal to the -- the maximum account depth, remove the depth limit. incDepth :: UIState -> UIState incDepth ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts@ReportOpts{..}}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{depth_=inc depth_}}}} where inc (Just d) | d < (maxDepth ui - 1) = Just $ d+1 inc _ = Nothing -- | Set the current depth limit to the specified depth, or remove the depth limit. -- Also remove the depth limit if the specified depth is greater than the current -- maximum account depth. If the specified depth is negative, reset the depth limit -- to whatever was specified at uiartup. setDepth :: Maybe Int -> UIState -> UIState setDepth mdepth ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{depth_=mdepth'}}}} where mdepth' = case mdepth of Nothing -> Nothing Just d | d < 0 -> depth_ ropts | d >= maxDepth ui -> Nothing | otherwise -> mdepth getDepth :: UIState -> Maybe Int getDepth UIState{aopts=UIOpts{cliopts_=CliOpts{reportopts_=ropts}}} = depth_ ropts -- | Open the minibuffer, setting its content to the current query with the cursor at the end. showMinibuffer :: UIState -> UIState showMinibuffer ui = setMode (Minibuffer e) ui where e = applyEdit gotoEOL $ editor MinibufferEditor (str . unlines) (Just 1) oldq oldq = query_ $ reportopts_ $ cliopts_ $ aopts ui -- | Close the minibuffer, discarding any edit in progress. closeMinibuffer :: UIState -> UIState closeMinibuffer = setMode Normal setMode :: Mode -> UIState -> UIState setMode m ui = ui{aMode=m} -- | Regenerate the content for the current and previous screens, from a new journal and current date. regenerateScreens :: Journal -> Day -> UIState -> UIState regenerateScreens j d ui@UIState{aScreen=s,aPrevScreens=ss} = -- XXX clumsy due to entanglement of UIState and Screen. -- sInit operates only on an appstate's current screen, so -- remove all the screens from the appstate and then add them back -- one at a time, regenerating as we go. let first:rest = reverse $ s:ss :: [Screen] ui0 = ui{ajournal=j, aScreen=first, aPrevScreens=[]} :: UIState ui1 = (sInit first) d False ui0 :: UIState ui2 = foldl' (\ui s -> (sInit s) d False $ pushScreen s ui) ui1 rest :: UIState in ui2 pushScreen :: Screen -> UIState -> UIState pushScreen scr ui = ui{aPrevScreens=(aScreen ui:aPrevScreens ui) ,aScreen=scr } popScreen :: UIState -> UIState popScreen ui@UIState{aPrevScreens=s:ss} = ui{aScreen=s, aPrevScreens=ss} popScreen ui = ui resetScreens :: Day -> UIState -> UIState resetScreens d ui@UIState{aScreen=s,aPrevScreens=ss} = (sInit topscreen) d True $ resetDepth $ resetFilter $ closeMinibuffer ui{aScreen=topscreen, aPrevScreens=[]} where topscreen = case ss of _:_ -> last ss [] -> s -- | Enter a new screen, saving the old screen & state in the -- navigation history and initialising the new screen's state. screenEnter :: Day -> Screen -> UIState -> UIState screenEnter d scr ui = (sInit scr) d True $ pushScreen scr ui hledger-ui-1.2/Hledger/UI/UITypes.hs0000644000000000000000000001553513035510426015364 0ustar0000000000000000{- | Overview: hledger-ui's UIState holds the currently active screen and any previously visited screens (and their states). The brick App delegates all event-handling and rendering to the UIState's active screen. Screens have their own screen state, render function, event handler, and app state update function, so they have full control. @ Brick.defaultMain brickapp st where brickapp :: App (UIState) V.Event brickapp = App { appLiftVtyEvent = id , appStartEvent = return , appAttrMap = const theme , appChooseCursor = showFirstCursor , appHandleEvent = \st ev -> sHandle (aScreen st) st ev , appDraw = \st -> sDraw (aScreen st) st } st :: UIState st = (sInit s) d UIState{ aopts=uopts' ,ajournal=j ,aScreen=s ,aPrevScreens=prevscrs ,aMinibuffer=Nothing } @ -} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Hledger.UI.UITypes where import Data.Time.Calendar (Day) import Brick import Brick.Widgets.List import Brick.Widgets.Edit (Editor) import Lens.Micro.Platform import Text.Show.Functions () -- import the Show instance for functions. Warning, this also re-exports it import Hledger import Hledger.UI.UIOptions -- | hledger-ui's application state. This holds one or more stateful screens. -- As you navigate through screens, the old ones are saved in a stack. -- The app can be in one of several modes: normal screen operation, -- showing a help dialog, entering data in the minibuffer etc. data UIState = UIState { aopts :: UIOpts -- ^ the command-line options and query arguments currently in effect ,ajournal :: Journal -- ^ the journal being viewed ,aPrevScreens :: [Screen] -- ^ previously visited screens, most recent first ,aScreen :: Screen -- ^ the currently active screen ,aMode :: Mode -- ^ the currently active mode } deriving (Show) -- | The mode modifies the screen's rendering and event handling. -- It resets to Normal when entering a new screen. data Mode = Normal | Help | Minibuffer (Editor String Name) deriving (Show,Eq) -- Ignore the editor when comparing Modes. instance Eq (Editor l n) where _ == _ = True -- Unique names required for widgets, viewports, cursor locations etc. data Name = HelpDialog | MinibufferEditor | AccountsViewport | AccountsList | RegisterViewport | RegisterList deriving (Ord, Show, Eq) data AppEvent = FileChange -- one of the Journal's files has been added/modified/removed | DateChange Day Day -- the current date has changed since last checked (with the old and new values) deriving (Eq, Show) -- | hledger-ui screen types & instances. -- Each screen type has generically named initialisation, draw, and event handling functions, -- and zero or more uniquely named screen state fields, which hold the data for a particular -- instance of this screen. Note the latter create partial functions, which means that some invalid -- cases need to be handled, and also that their lenses are traversals, not single-value getters. data Screen = AccountsScreen { sInit :: Day -> Bool -> UIState -> UIState -- ^ function to initialise or update this screen's state ,sDraw :: UIState -> [Widget Name] -- ^ brick renderer for this screen ,sHandle :: UIState -> BrickEvent Name AppEvent -> EventM Name (Next UIState) -- ^ brick event handler for this screen -- state fields.These ones have lenses: ,_asList :: List Name AccountsScreenItem -- ^ list widget showing account names & balances ,_asSelectedAccount :: AccountName -- ^ a backup of the account name from the list widget's selected item (or "") } | RegisterScreen { sInit :: Day -> Bool -> UIState -> UIState ,sDraw :: UIState -> [Widget Name] ,sHandle :: UIState -> BrickEvent Name AppEvent -> EventM Name (Next UIState) -- ,rsList :: List Name RegisterScreenItem -- ^ list widget showing transactions affecting this account ,rsAccount :: AccountName -- ^ the account this register is for ,rsForceInclusive :: Bool -- ^ should this register always include subaccount transactions, -- even when in flat mode ? (ie because entered from a -- depth-clipped accounts screen item) } | TransactionScreen { sInit :: Day -> Bool -> UIState -> UIState ,sDraw :: UIState -> [Widget Name] ,sHandle :: UIState -> BrickEvent Name AppEvent -> EventM Name (Next UIState) -- ,tsTransaction :: NumberedTransaction -- ^ the transaction we are currently viewing, and its position in the list ,tsTransactions :: [NumberedTransaction] -- ^ list of transactions we can step through ,tsAccount :: AccountName -- ^ the account whose register we entered this screen from } | ErrorScreen { sInit :: Day -> Bool -> UIState -> UIState ,sDraw :: UIState -> [Widget Name] ,sHandle :: UIState -> BrickEvent Name AppEvent -> EventM Name (Next UIState) -- ,esError :: String -- ^ error message to show } deriving (Show) -- | An item in the accounts screen's list of accounts and balances. data AccountsScreenItem = AccountsScreenItem { asItemIndentLevel :: Int -- ^ indent level ,asItemAccountName :: AccountName -- ^ full account name ,asItemDisplayAccountName :: AccountName -- ^ full or short account name to display ,asItemRenderedAmounts :: [String] -- ^ rendered amounts } deriving (Show) -- | An item in the register screen's list of transactions in the current account. data RegisterScreenItem = RegisterScreenItem { rsItemDate :: String -- ^ date ,rsItemDescription :: String -- ^ description ,rsItemOtherAccounts :: String -- ^ other accounts ,rsItemChangeAmount :: String -- ^ the change to the current account from this transaction ,rsItemBalanceAmount :: String -- ^ the balance or running total after this transaction ,rsItemTransaction :: Transaction -- ^ the full transaction } deriving (Show) type NumberedTransaction = (Integer, Transaction) -- dummy monoid instance needed make lenses work with List fields not common across constructors --instance Monoid (List n a) -- where -- mempty = list "" V.empty 1 -- XXX problem in 0.7, every list requires a unique Name -- mappend l1 l2 = l1 & listElementsL .~ (l1^.listElementsL <> l2^.listElementsL) concat <$> mapM makeLenses [ ''Screen ] hledger-ui-1.2/Hledger/UI/UIUtils.hs0000644000000000000000000002165113035510426015354 0ustar0000000000000000{- | Rendering & misc. helpers. -} {-# LANGUAGE OverloadedStrings #-} module Hledger.UI.UIUtils where import Brick import Brick.Widgets.Border import Brick.Widgets.Border.Style -- import Brick.Widgets.Center import Brick.Widgets.Dialog import Brick.Widgets.Edit import Data.List import Data.Monoid import Graphics.Vty (Event(..),Key(..),Color,Attr,currentAttr) import Lens.Micro.Platform import System.Process import Hledger import Hledger.UI.UITypes import Hledger.UI.UIState runInfo = runCommand "hledger-ui --info" >>= waitForProcess runMan = runCommand "hledger-ui --man" >>= waitForProcess runHelp = runCommand "hledger-ui --help | less" >>= waitForProcess -- ui uiShowClearedStatus mc = case mc of Just Cleared -> ["cleared"] Just Pending -> ["pending"] Just Uncleared -> ["uncleared"] Nothing -> [] -- | Draw the help dialog, called when help mode is active. helpDialog :: Widget Name helpDialog = Widget Fixed Fixed $ do c <- getContext render $ renderDialog (dialog (Just "Help (?/LEFT/ESC to close)") Nothing (c^.availWidthL)) $ -- (Just (0,[("ok",())])) padTopBottom 1 $ padLeftRight 1 $ vBox [ hBox [ padLeftRight 1 $ vBox [ str "NAVIGATION" ,renderKey ("UP/DOWN/k/j/PGUP/PGDN/HOME/END", "") ,str " move selection" ,renderKey ("RIGHT/l", "more detail") ,renderKey ("LEFT/h", "previous screen") ,renderKey ("ESC", "cancel / reset to top") ,str " " ,str "MISC" ,renderKey ("?", "toggle help") ,renderKey ("a", "add transaction (hledger add)") ,renderKey ("A", "add transaction (hledger-iadd)") ,renderKey ("E", "open editor") ,renderKey ("g", "reload data") ,renderKey ("I", "toggle balance assertions") ,renderKey ("q", "quit") ,str " " ,str "MANUAL" ,str "from help dialog:" ,renderKey ("t", "text") ,renderKey ("m", "man page") ,renderKey ("i", "info") ] ,padLeftRight 1 $ vBox [ str "FILTERING" ,renderKey ("SHIFT-DOWN/UP", "shrink/grow report period") ,renderKey ("SHIFT-RIGHT/LEFT", "next/previous report period") ,renderKey ("t", "set report period to today") ,str " " ,renderKey ("/", "set a filter query") ,renderKey ("C", "toggle cleared/all") ,renderKey ("U", "toggle uncleared/all") ,renderKey ("R", "toggle real/all") ,renderKey ("Z", "toggle nonzero/all") ,renderKey ("DEL/BS", "remove filters") ,str " " ,str "accounts screen:" ,renderKey ("-+0123456789", "set depth limit") ,renderKey ("H", "toggle period balance (shows change) or\nhistorical balance (includes older postings)") ,renderKey ("F", "toggle tree (amounts include subaccounts) or\nflat mode (amounts exclude subaccounts\nexcept when account is depth-clipped)") ,str " " ,str "register screen:" ,renderKey ("H", "toggle period or historical total") ,renderKey ("F", "toggle subaccount transaction inclusion\n(and tree/flat mode)") ] ] -- ,vBox [ -- str " " -- ,hCenter $ padLeftRight 1 $ -- hCenter (str "MANUAL") -- <=> -- hCenter (hBox [ -- renderKey ("t", "text") -- ,str " " -- ,renderKey ("m", "man page") -- ,str " " -- ,renderKey ("i", "info") -- ]) -- ] ] where renderKey (key,desc) = withAttr (borderAttr <> "keys") (str key) <+> str " " <+> str desc -- | Event handler used when help mode is active. helpHandle :: UIState -> BrickEvent Name AppEvent -> EventM Name (Next UIState) helpHandle ui ev = case ev of VtyEvent (EvKey k []) | k `elem` [KEsc, KLeft, KChar 'h', KChar '?'] -> continue $ setMode Normal ui VtyEvent (EvKey (KChar 't') []) -> suspendAndResume $ runHelp >> return ui' VtyEvent (EvKey (KChar 'm') []) -> suspendAndResume $ runMan >> return ui' VtyEvent (EvKey (KChar 'i') []) -> suspendAndResume $ runInfo >> return ui' _ -> continue ui where ui' = setMode Normal ui -- | Draw the minibuffer. minibuffer :: Editor String Name -> Widget Name minibuffer ed = forceAttr (borderAttr <> "minibuffer") $ hBox $ [txt "filter: ", renderEditor True ed] -- | Wrap a widget in the default hledger-ui screen layout. defaultLayout :: Widget Name -> Widget Name -> Widget Name -> Widget Name defaultLayout toplabel bottomlabel = topBottomBorderWithLabels (str " "<+>toplabel<+>str " ") (str " "<+>bottomlabel<+>str " ") . margin 1 0 Nothing -- topBottomBorderWithLabel2 label . -- padLeftRight 1 -- XXX should reduce inner widget's width by 2, but doesn't -- "the layout adjusts... if you use the core combinators" borderQueryStr :: String -> Widget Name borderQueryStr "" = str "" borderQueryStr qry = str " matching " <+> withAttr (borderAttr <> "query") (str qry) borderDepthStr :: Maybe Int -> Widget Name borderDepthStr Nothing = str "" borderDepthStr (Just d) = str " to " <+> withAttr (borderAttr <> "query") (str $ "depth "++show d) borderPeriodStr :: String -> Period -> Widget Name borderPeriodStr _ PeriodAll = str "" borderPeriodStr preposition p = str (" "++preposition++" ") <+> withAttr (borderAttr <> "query") (str $ showPeriod p) borderKeysStr :: [(String,String)] -> Widget Name borderKeysStr = borderKeysStr' . map (\(a,b) -> (a, str b)) borderKeysStr' :: [(String,Widget Name)] -> Widget Name borderKeysStr' keydescs = hBox $ intersperse sep $ [withAttr (borderAttr <> "keys") (str keys) <+> str ":" <+> desc | (keys, desc) <- keydescs] where -- sep = str " | " sep = str " " -- temporary shenanigans: -- | Convert the special account name "*" (from balance report with depth limit 0) to something clearer. replaceHiddenAccountsNameWith :: AccountName -> AccountName -> AccountName replaceHiddenAccountsNameWith anew a | a == hiddenAccountsName = anew | a == "*" = anew | otherwise = a hiddenAccountsName = "..." -- for now -- generic topBottomBorderWithLabel :: Widget Name -> Widget Name -> Widget Name topBottomBorderWithLabel label = \wrapped -> Widget Greedy Greedy $ do c <- getContext let (_w,h) = (c^.availWidthL, c^.availHeightL) h' = h - 2 wrapped' = vLimit (h') wrapped debugmsg = "" -- " debug: "++show (_w,h') render $ hBorderWithLabel (label <+> str debugmsg) <=> wrapped' <=> hBorder topBottomBorderWithLabels :: Widget Name -> Widget Name -> Widget Name -> Widget Name topBottomBorderWithLabels toplabel bottomlabel = \wrapped -> Widget Greedy Greedy $ do c <- getContext let (_w,h) = (c^.availWidthL, c^.availHeightL) h' = h - 2 wrapped' = vLimit (h') wrapped debugmsg = "" -- " debug: "++show (_w,h') render $ hBorderWithLabel (toplabel <+> str debugmsg) <=> wrapped' <=> hBorderWithLabel bottomlabel -- XXX should be equivalent to the above, but isn't (page down goes offscreen) _topBottomBorderWithLabel2 :: Widget Name -> Widget Name -> Widget Name _topBottomBorderWithLabel2 label = \wrapped -> let debugmsg = "" in hBorderWithLabel (label <+> str debugmsg) <=> wrapped <=> hBorder -- XXX superseded by pad, in theory -- | Wrap a widget in a margin with the given horizontal and vertical -- thickness, using the current background colour or the specified -- colour. -- XXX May disrupt border style of inner widgets. -- XXX Should reduce the available size visible to inner widget, but doesn't seem to (cf rsDraw2). margin :: Int -> Int -> Maybe Color -> Widget Name -> Widget Name margin h v mcolour = \w -> Widget Greedy Greedy $ do c <- getContext let w' = vLimit (c^.availHeightL - v*2) $ hLimit (c^.availWidthL - h*2) w attr = maybe currentAttr (\c -> c `on` c) mcolour render $ withBorderAttr attr $ withBorderStyle (borderStyleFromChar ' ') $ applyN v (hBorder <=>) $ applyN h (vBorder <+>) $ applyN v (<=> hBorder) $ applyN h (<+> vBorder) $ w' -- withBorderAttr attr . -- withBorderStyle (borderStyleFromChar ' ') . -- applyN n border withBorderAttr :: Attr -> Widget Name -> Widget Name withBorderAttr attr = updateAttrMap (applyAttrMappings [(borderAttr, attr)]) hledger-ui-1.2/doc/hledger-ui.10000644000000000000000000003440713067574771014474 0ustar0000000000000000 .TH "hledger\-ui" "1" "March 2017" "hledger\-ui 1.2" "hledger User Manuals" .SH NAME .PP hledger\-ui \- curses\-style interface for the hledger accounting tool .SH SYNOPSIS .PP \f[C]hledger\-ui\ [OPTIONS]\ [QUERYARGS]\f[] .PD 0 .P .PD \f[C]hledger\ ui\ \-\-\ [OPTIONS]\ [QUERYARGS]\f[] .SH DESCRIPTION .PP hledger is a cross\-platform program for tracking money, time, or any other commodity, using double\-entry accounting and a simple, editable file format. hledger is inspired by and largely compatible with ledger(1). .PP hledger\-ui is hledger\[aq]s curses\-style interface, providing an efficient full\-window text UI for viewing accounts and transactions, and some limited data entry capability. It is easier than hledger\[aq]s command\-line interface, and sometimes quicker and more convenient than the web interface. .PP Like hledger, it reads data from one or more files in hledger journal, timeclock, timedot, or CSV format specified with \f[C]\-f\f[], or \f[C]$LEDGER_FILE\f[], or \f[C]$HOME/.hledger.journal\f[] (on windows, perhaps \f[C]C:/Users/USER/.hledger.journal\f[]). For more about this see hledger(1), hledger_journal(5) etc. .SH OPTIONS .PP Note: if invoking hledger\-ui as a hledger subcommand, write \f[C]\-\-\f[] before options as shown above. .PP Any QUERYARGS are interpreted as a hledger search query which filters the data. .TP .B \f[C]\-\-watch\f[] watch for data and date changes and reload automatically .RS .RE .TP .B \f[C]\-\-theme=default|terminal|greenterm\f[] use this custom display theme .RS .RE .TP .B \f[C]\-\-register=ACCTREGEX\f[] start in the (first) matched account\[aq]s register screen .RS .RE .TP .B \f[C]\-\-change\f[] show period balances (changes) at startup instead of historical balances .RS .RE .TP .B \f[C]\-\-flat\f[] show full account names, unindented .RS .RE .PP hledger input options: .TP .B \f[C]\-f\ FILE\ \-\-file=FILE\f[] use a different input file. For stdin, use \- (default: \f[C]$LEDGER_FILE\f[] or \f[C]$HOME/.hledger.journal\f[]) .RS .RE .TP .B \f[C]\-\-rules\-file=RULESFILE\f[] Conversion rules file to use when reading CSV (default: FILE.rules) .RS .RE .TP .B \f[C]\-\-alias=OLD=NEW\f[] rename accounts named OLD to NEW .RS .RE .TP .B \f[C]\-\-anon\f[] anonymize accounts and payees .RS .RE .TP .B \f[C]\-\-pivot\ TAGNAME\f[] use some other field/tag for account names .RS .RE .TP .B \f[C]\-I\ \-\-ignore\-assertions\f[] ignore any failing balance assertions .RS .RE .PP hledger reporting options: .TP .B \f[C]\-b\ \-\-begin=DATE\f[] include postings/txns on or after this date .RS .RE .TP .B \f[C]\-e\ \-\-end=DATE\f[] include postings/txns before this date .RS .RE .TP .B \f[C]\-D\ \-\-daily\f[] multiperiod/multicolumn report by day .RS .RE .TP .B \f[C]\-W\ \-\-weekly\f[] multiperiod/multicolumn report by week .RS .RE .TP .B \f[C]\-M\ \-\-monthly\f[] multiperiod/multicolumn report by month .RS .RE .TP .B \f[C]\-Q\ \-\-quarterly\f[] multiperiod/multicolumn report by quarter .RS .RE .TP .B \f[C]\-Y\ \-\-yearly\f[] multiperiod/multicolumn report by year .RS .RE .TP .B \f[C]\-p\ \-\-period=PERIODEXP\f[] set start date, end date, and/or reporting interval all at once (overrides the flags above) .RS .RE .TP .B \f[C]\-\-date2\f[] show, and match with \-b/\-e/\-p/date:, secondary dates instead .RS .RE .TP .B \f[C]\-C\ \-\-cleared\f[] include only cleared postings/txns .RS .RE .TP .B \f[C]\-\-pending\f[] include only pending postings/txns .RS .RE .TP .B \f[C]\-U\ \-\-uncleared\f[] include only uncleared (and pending) postings/txns .RS .RE .TP .B \f[C]\-R\ \-\-real\f[] include only non\-virtual postings .RS .RE .TP .B \f[C]\-\-depth=N\f[] hide accounts/postings deeper than N .RS .RE .TP .B \f[C]\-E\ \-\-empty\f[] show items with zero amount, normally hidden .RS .RE .TP .B \f[C]\-B\ \-\-cost\f[] convert amounts to their cost at transaction time (using the transaction price, if any) .RS .RE .TP .B \f[C]\-V\ \-\-value\f[] convert amounts to their market value on the report end date (using the most recent applicable market price, if any) .RS .RE .PP hledger help options: .TP .B \f[C]\-h\f[] show general usage (or after COMMAND, command usage) .RS .RE .TP .B \f[C]\-\-help\f[] show this program\[aq]s manual as plain text (or after an add\-on COMMAND, the add\-on\[aq]s manual) .RS .RE .TP .B \f[C]\-\-man\f[] show this program\[aq]s manual with man .RS .RE .TP .B \f[C]\-\-info\f[] show this program\[aq]s manual with info .RS .RE .TP .B \f[C]\-\-version\f[] show version .RS .RE .TP .B \f[C]\-\-debug[=N]\f[] show debug output (levels 1\-9, default: 1) .RS .RE .SH KEYS .PP \f[C]?\f[] shows a help dialog listing all keys. (Some of these also appear in the quick help at the bottom of each screen.) Press \f[C]?\f[] again (or \f[C]ESCAPE\f[], or \f[C]LEFT\f[]) to close it. The following keys work on most screens: .PP The cursor keys navigate: \f[C]right\f[] (or \f[C]enter\f[]) goes deeper, \f[C]left\f[] returns to the previous screen, \f[C]up\f[]/\f[C]down\f[]/\f[C]page\ up\f[]/\f[C]page\ down\f[]/\f[C]home\f[]/\f[C]end\f[] move up and down through lists. Vi\-style \f[C]h\f[]/\f[C]j\f[]/\f[C]k\f[]/\f[C]l\f[] movement keys are also supported. A tip: movement speed is limited by your keyboard repeat rate, to move faster you may want to adjust it. (If you\[aq]re on a mac, the Karabiner app is one way to do that.) .PP With shift pressed, the cursor keys adjust the report period, limiting the transactions to be shown (by default, all are shown). \f[C]shift\-down/up\f[] steps downward and upward through these standard report period durations: year, quarter, month, week, day. Then, \f[C]shift\-left/right\f[] moves to the previous/next period. \f[C]t\f[] sets the report period to today. With the \f[C]\-\-watch\f[] option, when viewing a "current" period (the current day, week, month, quarter, or year), the period will move automatically to track the current date. To set a non\-standard period, you can use \f[C]/\f[] and a \f[C]date:\f[] query. .PP \f[C]/\f[] lets you set a general filter query limiting the data shown, using the same query terms as in hledger and hledger\-web. While editing the query, you can use CTRL\-a/e/d/k, BS, cursor keys; press \f[C]ENTER\f[] to set it, or \f[C]ESCAPE\f[]to cancel. There are also keys for quickly adjusting some common filters like account depth and cleared/uncleared (see below). \f[C]BACKSPACE\f[] or \f[C]DELETE\f[] removes all filters, showing all transactions. .PP \f[C]ESCAPE\f[] removes all filters and jumps back to the top screen. Or, it cancels a minibuffer edit or help dialog in progress. .PP \f[C]g\f[] reloads from the data file(s) and updates the current screen and any previous screens. (With large files, this could cause a noticeable pause.) .PP \f[C]I\f[] toggles balance assertion checking. Disabling balance assertions temporarily can be useful for troubleshooting. .PP \f[C]a\f[] runs command\-line hledger\[aq]s add command, and reloads the updated file. This allows some basic data entry. .PP \f[C]E\f[] runs $HLEDGER_UI_EDITOR, or $EDITOR, or a default (\f[C]emacsclient\ \-a\ ""\ \-nw\f[]) on the journal file. With some editors (emacs, vi), the cursor will be positioned at the current transaction when invoked from the register and transaction screens, and at the error location (if possible) when invoked from the error screen. .PP \f[C]q\f[] quits the application. .PP Additional screen\-specific keys are described below. .SH SCREENS .SS Accounts screen .PP This is normally the first screen displayed. It lists accounts and their balances, like hledger\[aq]s balance command. By default, it shows all accounts and their latest ending balances (including the balances of subaccounts). if you specify a query on the command line, it shows just the matched accounts and the balances from matched transactions. .PP Account names are normally indented to show the hierarchy (tree mode). To see less detail, set a depth limit by pressing a number key, \f[C]1\f[] to \f[C]9\f[]. \f[C]0\f[] shows even less detail, collapsing all accounts to a single total. \f[C]\-\f[] and \f[C]+\f[] (or \f[C]=\f[]) decrease and increase the depth limit. To remove the depth limit, set it higher than the maximum account depth, or press \f[C]ESCAPE\f[]. .PP \f[C]F\f[] toggles flat mode, in which accounts are shown as a flat list, with their full names. In this mode, account balances exclude subaccounts, except for accounts at the depth limit (as with hledger\[aq]s balance command). .PP \f[C]H\f[] toggles between showing historical balances or period balances. Historical balances (the default) are ending balances at the end of the report period, taking into account all transactions before that date (filtered by the filter query if any), including transactions before the start of the report period. In other words, historical balances are what you would see on a bank statement for that account (unless disturbed by a filter query). Period balances ignore transactions before the report start date, so they show the change in balance during the report period. They are more useful eg when viewing a time log. .PP \f[C]C\f[] toggles cleared mode, in which uncleared transactions and postings are not shown. \f[C]U\f[] toggles uncleared mode, in which only uncleared transactions/postings are shown. .PP \f[C]R\f[] toggles real mode, in which virtual postings are ignored. .PP \f[C]Z\f[] toggles nonzero mode, in which only accounts with nonzero balances are shown (hledger\-ui shows zero items by default, unlike command\-line hledger). .PP Press \f[C]right\f[] or \f[C]enter\f[] to view an account\[aq]s transactions register. .SS Register screen .PP This screen shows the transactions affecting a particular account, like a check register. Each line represents one transaction and shows: .IP \[bu] 2 the other account(s) involved, in abbreviated form. (If there are both real and virtual postings, it shows only the accounts affected by real postings.) .IP \[bu] 2 the overall change to the current account\[aq]s balance; positive for an inflow to this account, negative for an outflow. .IP \[bu] 2 the running historical total or period total for the current account, after the transaction. This can be toggled with \f[C]H\f[]. Similar to the accounts screen, the historical total is affected by transactions (filtered by the filter query) before the report start date, while the period total is not. If the historical total is not disturbed by a filter query, it will be the running historical balance you would see on a bank register for the current account. .PP If the accounts screen was in tree mode, the register screen will include transactions from both the current account and its subaccounts. If the accounts screen was in flat mode, and a non\-depth\-clipped account was selected, the register screen will exclude transactions from subaccounts. In other words, the register always shows the transactions responsible for the period balance shown on the accounts screen. As on the accounts screen, this can be toggled with \f[C]F\f[]. .PP \f[C]C\f[] toggles cleared mode, in which uncleared transactions and postings are not shown. \f[C]U\f[] toggles uncleared mode, in which only uncleared transactions/postings are shown. .PP \f[C]R\f[] toggles real mode, in which virtual postings are ignored. .PP \f[C]Z\f[] toggles nonzero mode, in which only transactions posting a nonzero change are shown (hledger\-ui shows zero items by default, unlike command\-line hledger). .PP Press \f[C]right\f[] (or \f[C]enter\f[]) to view the selected transaction in detail. .SS Transaction screen .PP This screen shows a single transaction, as a general journal entry, similar to hledger\[aq]s print command and journal format (hledger_journal(5)). .PP The transaction\[aq]s date(s) and any cleared flag, transaction code, description, comments, along with all of its account postings are shown. Simple transactions have two postings, but there can be more (or in certain cases, fewer). .PP \f[C]up\f[] and \f[C]down\f[] will step through all transactions listed in the previous account register screen. In the title bar, the numbers in parentheses show your position within that account register. They will vary depending on which account register you came from (remember most transactions appear in multiple account registers). The #N number preceding them is the transaction\[aq]s position within the complete unfiltered journal, which is a more stable id (at least until the next reload). .SS Error screen .PP This screen will appear if there is a problem, such as a parse error, when you press g to reload. Once you have fixed the problem, press g again to reload and resume normal operation. (Or, you can press escape to cancel the reload attempt.) .SH ENVIRONMENT .PP \f[B]COLUMNS\f[] The screen width to use. Default: the full terminal width. .PP \f[B]LEDGER_FILE\f[] The journal file path when not specified with \f[C]\-f\f[]. Default: \f[C]~/.hledger.journal\f[] (on windows, perhaps \f[C]C:/Users/USER/.hledger.journal\f[]). .SH FILES .PP Reads data from one or more files in hledger journal, timeclock, timedot, or CSV format specified with \f[C]\-f\f[], or \f[C]$LEDGER_FILE\f[], or \f[C]$HOME/.hledger.journal\f[] (on windows, perhaps \f[C]C:/Users/USER/.hledger.journal\f[]). .SH BUGS .PP The need to precede options with \f[C]\-\-\f[] when invoked from hledger is awkward. .PP \f[C]\-f\-\f[] doesn\[aq]t work (hledger\-ui can\[aq]t read from stdin). .PP \f[C]\-V\f[] affects only the accounts screen. .PP When you press \f[C]g\f[], the current and all previous screens are regenerated, which may cause a noticeable pause with large files. Also there is no visual indication that this is in progress. .PP \f[C]\-\-watch\f[] is not yet fully robust. It works well for normal usage, but many file changes in a short time (eg saving the file thousands of times with an editor macro) can cause problems at least on OSX. Symptoms include: unresponsive UI, periodic resetting of the cursor position, momentary display of parse errors, high CPU usage eventually subsiding, and possibly a small but persistent build\-up of CPU usage until the program is restarted. .SH "REPORTING BUGS" Report bugs at http://bugs.hledger.org (or on the #hledger IRC channel or hledger mail list) .SH AUTHORS Simon Michael and contributors .SH COPYRIGHT Copyright (C) 2007-2016 Simon Michael. .br Released under GNU GPL v3 or later. .SH SEE ALSO hledger(1), hledger\-ui(1), hledger\-web(1), hledger\-api(1), hledger_csv(5), hledger_journal(5), hledger_timeclock(5), hledger_timedot(5), ledger(1) http://hledger.org hledger-ui-1.2/doc/hledger-ui.1.info0000644000000000000000000003032713067574767015430 0ustar0000000000000000This is hledger-ui.1.info, produced by makeinfo version 6.0 from stdin.  File: hledger-ui.1.info, Node: Top, Next: OPTIONS, Up: (dir) hledger-ui(1) hledger-ui 1.2 **************************** hledger-ui is hledger's curses-style interface, providing an efficient full-window text UI for viewing accounts and transactions, and some limited data entry capability. It is easier than hledger's command-line interface, and sometimes quicker and more convenient than the web interface. Like hledger, it reads data from one or more files in hledger journal, timeclock, timedot, or CSV format specified with '-f', or '$LEDGER_FILE', or '$HOME/.hledger.journal' (on windows, perhaps 'C:/Users/USER/.hledger.journal'). For more about this see hledger(1), hledger_journal(5) etc. * Menu: * OPTIONS:: * KEYS:: * SCREENS::  File: hledger-ui.1.info, Node: OPTIONS, Next: KEYS, Prev: Top, Up: Top 1 OPTIONS ********* Note: if invoking hledger-ui as a hledger subcommand, write '--' before options as shown above. Any QUERYARGS are interpreted as a hledger search query which filters the data. '--watch' watch for data and date changes and reload automatically '--theme=default|terminal|greenterm' use this custom display theme '--register=ACCTREGEX' start in the (first) matched account's register screen '--change' show period balances (changes) at startup instead of historical balances '--flat' show full account names, unindented hledger input options: '-f FILE --file=FILE' use a different input file. For stdin, use - (default: '$LEDGER_FILE' or '$HOME/.hledger.journal') '--rules-file=RULESFILE' Conversion rules file to use when reading CSV (default: FILE.rules) '--alias=OLD=NEW' rename accounts named OLD to NEW '--anon' anonymize accounts and payees '--pivot TAGNAME' use some other field/tag for account names '-I --ignore-assertions' ignore any failing balance assertions hledger reporting options: '-b --begin=DATE' include postings/txns on or after this date '-e --end=DATE' include postings/txns before this date '-D --daily' multiperiod/multicolumn report by day '-W --weekly' multiperiod/multicolumn report by week '-M --monthly' multiperiod/multicolumn report by month '-Q --quarterly' multiperiod/multicolumn report by quarter '-Y --yearly' multiperiod/multicolumn report by year '-p --period=PERIODEXP' set start date, end date, and/or reporting interval all at once (overrides the flags above) '--date2' show, and match with -b/-e/-p/date:, secondary dates instead '-C --cleared' include only cleared postings/txns '--pending' include only pending postings/txns '-U --uncleared' include only uncleared (and pending) postings/txns '-R --real' include only non-virtual postings '--depth=N' hide accounts/postings deeper than N '-E --empty' show items with zero amount, normally hidden '-B --cost' convert amounts to their cost at transaction time (using the transaction price, if any) '-V --value' convert amounts to their market value on the report end date (using the most recent applicable market price, if any) hledger help options: '-h' show general usage (or after COMMAND, command usage) '--help' show this program's manual as plain text (or after an add-on COMMAND, the add-on's manual) '--man' show this program's manual with man '--info' show this program's manual with info '--version' show version '--debug[=N]' show debug output (levels 1-9, default: 1)  File: hledger-ui.1.info, Node: KEYS, Next: SCREENS, Prev: OPTIONS, Up: Top 2 KEYS ****** '?' shows a help dialog listing all keys. (Some of these also appear in the quick help at the bottom of each screen.) Press '?' again (or 'ESCAPE', or 'LEFT') to close it. The following keys work on most screens: The cursor keys navigate: 'right' (or 'enter') goes deeper, 'left' returns to the previous screen, 'up'/'down'/'page up'/'page down'/'home'/'end' move up and down through lists. Vi-style 'h'/'j'/'k'/'l' movement keys are also supported. A tip: movement speed is limited by your keyboard repeat rate, to move faster you may want to adjust it. (If you're on a mac, the Karabiner app is one way to do that.) With shift pressed, the cursor keys adjust the report period, limiting the transactions to be shown (by default, all are shown). 'shift-down/up' steps downward and upward through these standard report period durations: year, quarter, month, week, day. Then, 'shift-left/right' moves to the previous/next period. 't' sets the report period to today. With the '--watch' option, when viewing a "current" period (the current day, week, month, quarter, or year), the period will move automatically to track the current date. To set a non-standard period, you can use '/' and a 'date:' query. '/' lets you set a general filter query limiting the data shown, using the same query terms as in hledger and hledger-web. While editing the query, you can use CTRL-a/e/d/k, BS, cursor keys; press 'ENTER' to set it, or 'ESCAPE'to cancel. There are also keys for quickly adjusting some common filters like account depth and cleared/uncleared (see below). 'BACKSPACE' or 'DELETE' removes all filters, showing all transactions. 'ESCAPE' removes all filters and jumps back to the top screen. Or, it cancels a minibuffer edit or help dialog in progress. 'g' reloads from the data file(s) and updates the current screen and any previous screens. (With large files, this could cause a noticeable pause.) 'I' toggles balance assertion checking. Disabling balance assertions temporarily can be useful for troubleshooting. 'a' runs command-line hledger's add command, and reloads the updated file. This allows some basic data entry. 'E' runs $HLEDGER_UI_EDITOR, or $EDITOR, or a default ('emacsclient -a "" -nw') on the journal file. With some editors (emacs, vi), the cursor will be positioned at the current transaction when invoked from the register and transaction screens, and at the error location (if possible) when invoked from the error screen. 'q' quits the application. Additional screen-specific keys are described below.  File: hledger-ui.1.info, Node: SCREENS, Prev: KEYS, Up: Top 3 SCREENS ********* * Menu: * Accounts screen:: * Register screen:: * Transaction screen:: * Error screen::  File: hledger-ui.1.info, Node: Accounts screen, Next: Register screen, Up: SCREENS 3.1 Accounts screen =================== This is normally the first screen displayed. It lists accounts and their balances, like hledger's balance command. By default, it shows all accounts and their latest ending balances (including the balances of subaccounts). if you specify a query on the command line, it shows just the matched accounts and the balances from matched transactions. Account names are normally indented to show the hierarchy (tree mode). To see less detail, set a depth limit by pressing a number key, '1' to '9'. '0' shows even less detail, collapsing all accounts to a single total. '-' and '+' (or '=') decrease and increase the depth limit. To remove the depth limit, set it higher than the maximum account depth, or press 'ESCAPE'. 'F' toggles flat mode, in which accounts are shown as a flat list, with their full names. In this mode, account balances exclude subaccounts, except for accounts at the depth limit (as with hledger's balance command). 'H' toggles between showing historical balances or period balances. Historical balances (the default) are ending balances at the end of the report period, taking into account all transactions before that date (filtered by the filter query if any), including transactions before the start of the report period. In other words, historical balances are what you would see on a bank statement for that account (unless disturbed by a filter query). Period balances ignore transactions before the report start date, so they show the change in balance during the report period. They are more useful eg when viewing a time log. 'C' toggles cleared mode, in which uncleared transactions and postings are not shown. 'U' toggles uncleared mode, in which only uncleared transactions/postings are shown. 'R' toggles real mode, in which virtual postings are ignored. 'Z' toggles nonzero mode, in which only accounts with nonzero balances are shown (hledger-ui shows zero items by default, unlike command-line hledger). Press 'right' or 'enter' to view an account's transactions register.  File: hledger-ui.1.info, Node: Register screen, Next: Transaction screen, Prev: Accounts screen, Up: SCREENS 3.2 Register screen =================== This screen shows the transactions affecting a particular account, like a check register. Each line represents one transaction and shows: * the other account(s) involved, in abbreviated form. (If there are both real and virtual postings, it shows only the accounts affected by real postings.) * the overall change to the current account's balance; positive for an inflow to this account, negative for an outflow. * the running historical total or period total for the current account, after the transaction. This can be toggled with 'H'. Similar to the accounts screen, the historical total is affected by transactions (filtered by the filter query) before the report start date, while the period total is not. If the historical total is not disturbed by a filter query, it will be the running historical balance you would see on a bank register for the current account. If the accounts screen was in tree mode, the register screen will include transactions from both the current account and its subaccounts. If the accounts screen was in flat mode, and a non-depth-clipped account was selected, the register screen will exclude transactions from subaccounts. In other words, the register always shows the transactions responsible for the period balance shown on the accounts screen. As on the accounts screen, this can be toggled with 'F'. 'C' toggles cleared mode, in which uncleared transactions and postings are not shown. 'U' toggles uncleared mode, in which only uncleared transactions/postings are shown. 'R' toggles real mode, in which virtual postings are ignored. 'Z' toggles nonzero mode, in which only transactions posting a nonzero change are shown (hledger-ui shows zero items by default, unlike command-line hledger). Press 'right' (or 'enter') to view the selected transaction in detail.  File: hledger-ui.1.info, Node: Transaction screen, Next: Error screen, Prev: Register screen, Up: SCREENS 3.3 Transaction screen ====================== This screen shows a single transaction, as a general journal entry, similar to hledger's print command and journal format (hledger_journal(5)). The transaction's date(s) and any cleared flag, transaction code, description, comments, along with all of its account postings are shown. Simple transactions have two postings, but there can be more (or in certain cases, fewer). 'up' and 'down' will step through all transactions listed in the previous account register screen. In the title bar, the numbers in parentheses show your position within that account register. They will vary depending on which account register you came from (remember most transactions appear in multiple account registers). The #N number preceding them is the transaction's position within the complete unfiltered journal, which is a more stable id (at least until the next reload).  File: hledger-ui.1.info, Node: Error screen, Prev: Transaction screen, Up: SCREENS 3.4 Error screen ================ This screen will appear if there is a problem, such as a parse error, when you press g to reload. Once you have fixed the problem, press g again to reload and resume normal operation. (Or, you can press escape to cancel the reload attempt.)  Tag Table: Node: Top73 Node: OPTIONS825 Ref: #options924 Node: KEYS3650 Ref: #keys3747 Node: SCREENS6335 Ref: #screens6422 Node: Accounts screen6512 Ref: #accounts-screen6642 Node: Register screen8691 Ref: #register-screen8848 Node: Transaction screen10737 Ref: #transaction-screen10897 Node: Error screen11767 Ref: #error-screen11891  End Tag Table hledger-ui-1.2/doc/hledger-ui.1.txt0000644000000000000000000003543013067574771015307 0ustar0000000000000000 hledger-ui(1) hledger User Manuals hledger-ui(1) NAME hledger-ui - curses-style interface for the hledger accounting tool SYNOPSIS hledger-ui [OPTIONS] [QUERYARGS] hledger ui -- [OPTIONS] [QUERYARGS] DESCRIPTION hledger is a cross-platform program for tracking money, time, or any other commodity, using double-entry accounting and a simple, editable file format. hledger is inspired by and largely compatible with ledger(1). hledger-ui is hledger's curses-style interface, providing an efficient full-window text UI for viewing accounts and transactions, and some limited data entry capability. It is easier than hledger's com- mand-line interface, and sometimes quicker and more convenient than the web interface. Like hledger, it reads data from one or more files in hledger journal, timeclock, timedot, or CSV format specified with -f, or $LEDGER_FILE, or $HOME/.hledger.journal (on windows, perhaps C:/Users/USER/.hledger.journal). For more about this see hledger(1), hledger_journal(5) etc. OPTIONS Note: if invoking hledger-ui as a hledger subcommand, write -- before options as shown above. Any QUERYARGS are interpreted as a hledger search query which filters the data. --watch watch for data and date changes and reload automatically --theme=default|terminal|greenterm use this custom display theme --register=ACCTREGEX start in the (first) matched account's register screen --change show period balances (changes) at startup instead of historical balances --flat show full account names, unindented hledger input options: -f FILE --file=FILE use a different input file. For stdin, use - (default: $LEDGER_FILE or $HOME/.hledger.journal) --rules-file=RULESFILE Conversion rules file to use when reading CSV (default: FILE.rules) --alias=OLD=NEW rename accounts named OLD to NEW --anon anonymize accounts and payees --pivot TAGNAME use some other field/tag for account names -I --ignore-assertions ignore any failing balance assertions hledger reporting options: -b --begin=DATE include postings/txns on or after this date -e --end=DATE include postings/txns before this date -D --daily multiperiod/multicolumn report by day -W --weekly multiperiod/multicolumn report by week -M --monthly multiperiod/multicolumn report by month -Q --quarterly multiperiod/multicolumn report by quarter -Y --yearly multiperiod/multicolumn report by year -p --period=PERIODEXP set start date, end date, and/or reporting interval all at once (overrides the flags above) --date2 show, and match with -b/-e/-p/date:, secondary dates instead -C --cleared include only cleared postings/txns --pending include only pending postings/txns -U --uncleared include only uncleared (and pending) postings/txns -R --real include only non-virtual postings --depth=N hide accounts/postings deeper than N -E --empty show items with zero amount, normally hidden -B --cost convert amounts to their cost at transaction time (using the transaction price, if any) -V --value convert amounts to their market value on the report end date (using the most recent applicable market price, if any) hledger help options: -h show general usage (or after COMMAND, command usage) --help show this program's manual as plain text (or after an add-on COMMAND, the add-on's manual) --man show this program's manual with man --info show this program's manual with info --version show version --debug[=N] show debug output (levels 1-9, default: 1) KEYS ? shows a help dialog listing all keys. (Some of these also appear in the quick help at the bottom of each screen.) Press ? again (or ESCAPE, or LEFT) to close it. The following keys work on most screens: The cursor keys navigate: right (or enter) goes deeper, left returns to the previous screen, up/down/page up/page down/home/end move up and down through lists. Vi-style h/j/k/l movement keys are also supported. A tip: movement speed is limited by your keyboard repeat rate, to move faster you may want to adjust it. (If you're on a mac, the Karabiner app is one way to do that.) With shift pressed, the cursor keys adjust the report period, limiting the transactions to be shown (by default, all are shown). shift-down/up steps downward and upward through these standard report period durations: year, quarter, month, week, day. Then, shift-left/right moves to the previous/next period. t sets the report period to today. With the --watch option, when viewing a "current" period (the current day, week, month, quarter, or year), the period will move automatically to track the current date. To set a non-stan- dard period, you can use / and a date: query. / lets you set a general filter query limiting the data shown, using the same query terms as in hledger and hledger-web. While editing the query, you can use CTRL-a/e/d/k, BS, cursor keys; press ENTER to set it, or ESCAPEto cancel. There are also keys for quickly adjusting some common filters like account depth and cleared/uncleared (see below). BACKSPACE or DELETE removes all filters, showing all transactions. ESCAPE removes all filters and jumps back to the top screen. Or, it cancels a minibuffer edit or help dialog in progress. g reloads from the data file(s) and updates the current screen and any previous screens. (With large files, this could cause a noticeable pause.) I toggles balance assertion checking. Disabling balance assertions temporarily can be useful for troubleshooting. a runs command-line hledger's add command, and reloads the updated file. This allows some basic data entry. E runs $HLEDGER_UI_EDITOR, or $EDITOR, or a default (emac- sclient -a "" -nw) on the journal file. With some editors (emacs, vi), the cursor will be positioned at the current transaction when invoked from the register and transaction screens, and at the error location (if possible) when invoked from the error screen. q quits the application. Additional screen-specific keys are described below. SCREENS Accounts screen This is normally the first screen displayed. It lists accounts and their balances, like hledger's balance command. By default, it shows all accounts and their latest ending balances (including the balances of subaccounts). if you specify a query on the command line, it shows just the matched accounts and the balances from matched transactions. Account names are normally indented to show the hierarchy (tree mode). To see less detail, set a depth limit by pressing a number key, 1 to 9. 0 shows even less detail, collapsing all accounts to a single total. - and + (or =) decrease and increase the depth limit. To remove the depth limit, set it higher than the maximum account depth, or press ESCAPE. F toggles flat mode, in which accounts are shown as a flat list, with their full names. In this mode, account balances exclude subaccounts, except for accounts at the depth limit (as with hledger's balance com- mand). H toggles between showing historical balances or period balances. His- torical balances (the default) are ending balances at the end of the report period, taking into account all transactions before that date (filtered by the filter query if any), including transactions before the start of the report period. In other words, historical balances are what you would see on a bank statement for that account (unless disturbed by a filter query). Period balances ignore transactions before the report start date, so they show the change in balance during the report period. They are more useful eg when viewing a time log. C toggles cleared mode, in which uncleared transactions and postings are not shown. U toggles uncleared mode, in which only uncleared transactions/postings are shown. R toggles real mode, in which virtual postings are ignored. Z toggles nonzero mode, in which only accounts with nonzero balances are shown (hledger-ui shows zero items by default, unlike command-line hledger). Press right or enter to view an account's transactions register. Register screen This screen shows the transactions affecting a particular account, like a check register. Each line represents one transaction and shows: o the other account(s) involved, in abbreviated form. (If there are both real and virtual postings, it shows only the accounts affected by real postings.) o the overall change to the current account's balance; positive for an inflow to this account, negative for an outflow. o the running historical total or period total for the current account, after the transaction. This can be toggled with H. Similar to the accounts screen, the historical total is affected by transactions (filtered by the filter query) before the report start date, while the period total is not. If the historical total is not disturbed by a filter query, it will be the running historical balance you would see on a bank register for the current account. If the accounts screen was in tree mode, the register screen will include transactions from both the current account and its subaccounts. If the accounts screen was in flat mode, and a non-depth-clipped account was selected, the register screen will exclude transactions from subaccounts. In other words, the register always shows the trans- actions responsible for the period balance shown on the accounts screen. As on the accounts screen, this can be toggled with F. C toggles cleared mode, in which uncleared transactions and postings are not shown. U toggles uncleared mode, in which only uncleared transactions/postings are shown. R toggles real mode, in which virtual postings are ignored. Z toggles nonzero mode, in which only transactions posting a nonzero change are shown (hledger-ui shows zero items by default, unlike com- mand-line hledger). Press right (or enter) to view the selected transaction in detail. Transaction screen This screen shows a single transaction, as a general journal entry, similar to hledger's print command and journal format (hledger_jour- nal(5)). The transaction's date(s) and any cleared flag, transaction code, description, comments, along with all of its account postings are shown. Simple transactions have two postings, but there can be more (or in certain cases, fewer). up and down will step through all transactions listed in the previous account register screen. In the title bar, the numbers in parentheses show your position within that account register. They will vary depending on which account register you came from (remember most trans- actions appear in multiple account registers). The #N number preceding them is the transaction's position within the complete unfiltered jour- nal, which is a more stable id (at least until the next reload). Error screen This screen will appear if there is a problem, such as a parse error, when you press g to reload. Once you have fixed the problem, press g again to reload and resume normal operation. (Or, you can press escape to cancel the reload attempt.) ENVIRONMENT COLUMNS The screen width to use. Default: the full terminal width. LEDGER_FILE The journal file path when not specified with -f. Default: ~/.hledger.journal (on windows, perhaps C:/Users/USER/.hledger.jour- nal). FILES Reads data from one or more files in hledger journal, timeclock, time- dot, or CSV format specified with -f, or $LEDGER_FILE, or $HOME/.hledger.journal (on windows, perhaps C:/Users/USER/.hledger.journal). BUGS The need to precede options with -- when invoked from hledger is awk- ward. -f- doesn't work (hledger-ui can't read from stdin). -V affects only the accounts screen. When you press g, the current and all previous screens are regenerated, which may cause a noticeable pause with large files. Also there is no visual indication that this is in progress. --watch is not yet fully robust. It works well for normal usage, but many file changes in a short time (eg saving the file thousands of times with an editor macro) can cause problems at least on OSX. Symp- toms include: unresponsive UI, periodic resetting of the cursor posi- tion, momentary display of parse errors, high CPU usage eventually sub- siding, and possibly a small but persistent build-up of CPU usage until the program is restarted. REPORTING BUGS Report bugs at http://bugs.hledger.org (or on the #hledger IRC channel or hledger mail list) AUTHORS Simon Michael and contributors COPYRIGHT Copyright (C) 2007-2016 Simon Michael. Released under GNU GPL v3 or later. SEE ALSO hledger(1), hledger-ui(1), hledger-web(1), hledger-api(1), hledger_csv(5), hledger_journal(5), hledger_timeclock(5), hledger_time- dot(5), ledger(1) http://hledger.org hledger-ui 1.2 March 2017 hledger-ui(1) hledger-ui-1.2/LICENSE0000644000000000000000000010451313035210046012572 0ustar0000000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . hledger-ui-1.2/Setup.hs0000644000000000000000000000005613035210046013216 0ustar0000000000000000import Distribution.Simple main = defaultMain hledger-ui-1.2/hledger-ui.cabal0000644000000000000000000000625613067575305014624 0ustar0000000000000000-- This file has been generated from package.yaml by hpack version 0.17.0. -- -- see: https://github.com/sol/hpack name: hledger-ui version: 1.2 synopsis: Curses-style user interface for the hledger accounting tool description: This is hledger's curses-style interface. It is simpler and more convenient for browsing data than the command-line interface, but lighter and faster than hledger-web. . hledger is a cross-platform program for tracking money, time, or any other commodity, using double-entry accounting and a simple, editable file format. It is inspired by and largely compatible with ledger(1). hledger provides command-line, curses and web interfaces, and aims to be a reliable, practical tool for daily use. category: Finance, Console stability: stable homepage: http://hledger.org bug-reports: http://bugs.hledger.org author: Simon Michael maintainer: Simon Michael license: GPL-3 license-file: LICENSE tested-with: GHC==7.10.3, GHC==8.0 build-type: Simple cabal-version: >= 1.10 extra-source-files: CHANGES README data-files: doc/hledger-ui.1 doc/hledger-ui.1.info doc/hledger-ui.1.txt source-repository head type: git location: https://github.com/simonmichael/hledger flag oldtime description: If building with time < 1.5, also depend on old-locale. Set automatically by cabal. manual: False default: False flag threaded description: Build with support for multithreaded execution manual: False default: True executable hledger-ui main-is: hledger-ui.hs hs-source-dirs: ./. ghc-options: -Wall -fno-warn-unused-do-bind -fno-warn-name-shadowing -fno-warn-missing-signatures -fno-warn-type-defaults -fno-warn-orphans cpp-options: -DVERSION="1.2" build-depends: hledger >= 1.2 && < 1.3 , hledger-lib >= 1.2 && < 1.3 , ansi-terminal >= 0.6.2.3 && < 0.7 , async , base >= 4.8 && < 5 , base-compat >= 0.8.1 , cmdargs >= 0.8 , containers , data-default , directory , filepath , fsnotify >= 0.2 && < 0.3 , HUnit , microlens >= 0.4 && < 0.5 , microlens-platform >= 0.2.3.1 && < 0.4 , megaparsec >=5.0 && < 5.3 , pretty-show >=1.6.4 , process >= 1.2 , safe >= 0.2 , split >= 0.1 && < 0.3 , text >= 1.2 && < 1.3 , text-zipper >= 0.4 && < 0.11 , transformers , vector if os(windows) buildable: False else build-depends: brick >= 0.12 && < 0.18 , vty >= 5.5 && < 5.16 if flag(threaded) ghc-options: -threaded if flag(oldtime) build-depends: time < 1.5 , old-locale else build-depends: time >= 1.5 other-modules: Hledger.UI Hledger.UI.AccountsScreen Hledger.UI.Editor Hledger.UI.ErrorScreen Hledger.UI.Main Hledger.UI.RegisterScreen Hledger.UI.Theme Hledger.UI.TransactionScreen Hledger.UI.UIOptions Hledger.UI.UIState Hledger.UI.UITypes Hledger.UI.UIUtils default-language: Haskell2010 hledger-ui-1.2/CHANGES0000644000000000000000000001512113067576516012602 0ustar0000000000000000User-visible changes in hledger-ui. See also the hledger and project change logs. # 1.2 (2016/3/31) Fix a pattern match failure when pressing E on the transaction screen (fixes #508) Accounts with ? in name had empty registers (fixes #498) (Bryan Richter) Allow brick 0.16 (Joshua Chia) and brick 0.17/vty 0.15 (Peter Simons) Allow megaparsec 5.2 (fixes #503) Allow text-zipper 0.10 # 1.1.1 (2017/1/20) - allow brick 0.16 (Joshua Chia) - drop obsolete --no-elide flag # 1.1 (2016/12/31) - with --watch, the display updates automatically to show file or date changes hledger-ui --watch will reload data when the journal file (or any included file) changes. Also, when viewing a current standard period (ie this day/week/month/quarter/year), the period will move as needed to track the current system date. - the --change flag shows period changes at startup instead of historical ending balances - the A key runs the hledger-iadd tool, if installed - always reload when g is pressed Previously it would check the modification time and reload only if it looked newer than the last reload. - mark hledger-ui as "stable" - allow brick 0.15, vty 5.14, text-zipper 0.9 # 1.0.4 (2016/11/2) - allow brick 0.13 # 1.0.3 (2016/10/31) - use brick 0.12 # 1.0.2 (2016/10/27) - use latest brick 0.11 # 1.0.1 (2016/10/27) - allow megaparsec 5.0 or 5.1 # 1.0 (2016/10/26) ## accounts screen - at depth 0, show accounts on one "All" line and show all transactions in the register - 0 now sets depth limit to 0 instead of clearing it - always use --no-elide for a more regular accounts tree ## register screen - registers can now include/exclude subaccount transactions. The register screen now includes subaccounts' transactions if the accounts screen was in tree mode, or when showing an account which was at the depth limit. Ie, it always shows the transactions contributing to the balance displayed on the accounts screen. As on the accounts screen, F toggles between tree mode/subaccount txns included by default and flat mode/subaccount txns excluded by default. (At least, it does when it would make a difference.) - register transactions are filtered by realness and status (#354). Two fixes for the account transactions report when --real/--cleared/real:/status: are in effect, affecting hledger-ui and hledger-web: 1. exclude transactions which affect the current account via an excluded posting type. Eg when --real is in effect, a transaction posting to the current account with only virtual postings will not appear in the report. 2. when showing historical balances, don't count excluded posting types in the starting balance. Eg with --real, the starting balance will be the sum of only the non-virtual prior postings. This is complicated and there might be some ways to confuse it still, causing wrongly included/excluded transactions or wrong historical balances/running totals (transactions with both real and virtual postings to the current account, perhaps ?) - show more accurate dates when postings have their own dates. If postings to the register account matched by the register's filter query have their own dates, we show the earliest of these as the transaction date. ## misc - H toggles between showing "historical" or "period" balances (#392). By default hledger-ui now shows historical balances, which include transactions before the report start date (like hledger balance --historical). Use the H key to toggle to "period" mode, where balances start from 0 on the report start date. - shift arrow keys allow quick period browsing - shift-down narrows to the next smaller standard period (year/quarter/month/week/day), shift-up does the reverse - when narrowed to a standard period, shift-right/left moves to the next/previous period - \`t\` sets the period to today. - a runs the add command - E runs $HLEDGER_UI_EDITOR or $EDITOR or a default editor (vi) on the journal file. When using emacs or vi, if a transaction is selected the cursor will be positioned at its journal entry. - / key sets the filter query; BACKSPACE/DELETE clears it - Z toggles display of zero items (like --empty), and they are shown by default. -E/--empty is now the default for hledger-ui, so accounts with 0 balance and transactions posting 0 change are shown by default. The Z key toggles this, entering "nonzero" mode which hides zero items. - R toggles inclusion of only real (non-virtual) postings - U toggles inclusion of only uncleared transactions/postings - I toggles balance assertions checking, useful for troubleshooting - vi-style movement keys are now supported (for help, you must now use ? not h) (#357) - ESC cancels minibuffer/help or clears the filter query and jumps to top screen - ENTER has been reserved for later use - reloading now preserves any options and modes in effect - reloading on the error screen now updates the message rather than entering a new error screen - the help dialog is more detailed, includes the hledger-ui manual, and uses the full terminal width if needed - the header/footer content is more efficient; historical/period and tree/flat modes are now indicated in the footer - date: query args on the command line now affect the report period. A date2: arg or --date2 flag might also affect it (untested). - hledger-ui now uses the quicker-building microlens 0.27.3 (2016/1/12) - allow brick 0.4 0.27.2 (2016/1/11) - allow brick 0.3.x 0.27.1 (2015/12/3) - allow lens 4.13 - make reloading work on the transaction screen 0.27 (2015/10/30) - hledger-ui is a new curses-style UI, intended to be a standard part of the hledger toolset for all users (except on native MS Windows, where the vty lib is not yet supported). The UI is quite simple, allowing just browsing of accounts and transactions, but it has a number of improvements over the old hledger-vty, which it replaces: - adapts to screen size - handles wide characters - shows multi-commodity amounts on one line - manages cursor and scroll position better - allows depth adjustment - allows --flat toggle - allows --cleared toggle - allows journal reloading - shows a more useful transaction register, like hledger-web - offers multiple color themes - includes some built-in help hledger-ui is built with brick, a new higher-level UI library based on vty, making it relatively easy to grow and maintain. hledger-ui-1.2/README0000644000000000000000000000201513035210046012437 0ustar0000000000000000A curses-style text user interface for the hledger accounting tool. hledger-ui is the new name for hledger-vty. Revived in 2015, this package is intended to be installed as standard by all hledger users, except those on (native) Windows, where it is not supported. hledger-ui currently allows browsing the balance, register and print reports, with drill-down and scrolling. # HACKING ## Backlog: ``` reg: show historical running balance acc: fix -H, show historical balances switch to multibalance report ? adjust filter accounts screen register screen reg: improve other account names test showing only real postings when there are reals and virtuals journal entry view dialog blog reg: support -V redraw on ctrl-l/cmd-r reload on redraw reload on screen change reload on file change acc: show total fix --drop show "modified account names" with --drop or --alias journal screen bs/is/cf-ish reports persistent custom reports persistent config search in page adjust other options add edit custom screens plugin screens ```