hledger-ui-1.19.1/Hledger/0000755000000000000000000000000013700077722013375 5ustar0000000000000000hledger-ui-1.19.1/Hledger/UI/0000755000000000000000000000000013723502755013716 5ustar0000000000000000hledger-ui-1.19.1/hledger-ui.hs0000644000000000000000000000013313700077722014401 0ustar0000000000000000#!/usr/bin/env runhaskell module Main (module Hledger.UI) where import Hledger.UI (main) hledger-ui-1.19.1/Hledger/UI.hs0000644000000000000000000000047313700077722014252 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 ) where import Hledger.UI.Main import Hledger.UI.UIOptions import Hledger.UI.Theme hledger-ui-1.19.1/Hledger/UI/AccountsScreen.hs0000644000000000000000000004535613723502755017206 0ustar0000000000000000-- The accounts screen, showing accounts and balances like the CLI balance command. {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE CPP #-} module Hledger.UI.AccountsScreen (accountsScreen ,asInit ,asSetSelectedAccount ) where import Brick import Brick.Widgets.List (handleListEvent, list, listElementsL, listMoveDown, listMoveTo, listNameL, listSelectedElement, listSelectedL, renderList) import Brick.Widgets.Edit import Control.Monad import Control.Monad.IO.Class (liftIO) import Data.List import Data.Maybe #if !(MIN_VERSION_base(4,11,0)) import Data.Monoid ((<>)) #endif import qualified Data.Text as T import Data.Time.Calendar (Day, addDays) import qualified Data.Vector as V import Graphics.Vty (Event(..),Key(..),Modifier(..)) import Lens.Micro.Platform import Safe import System.Console.ANSI import System.FilePath (takeFileName) import Hledger import Hledger.Cli hiding (progname,prognameandversion) 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 ++ blankitems) 1 -- decide which account is selected: -- if reset is true, the first account; -- otherwise, the previously selected account if possible; -- otherwise, the first account with the same prefix (eg first leaf account when entering flat mode); -- otherwise, the alphabetically preceding account. newitems' = listMoveTo selidx newitems where selidx = case (reset, listSelectedElement $ _asList s) of (True, _) -> 0 (_, Nothing) -> 0 (_, Just (_,AccountsScreenItem{asItemAccountName=a})) -> headDef 0 $ catMaybes [ findIndex (a ==) as ,findIndex (a `isAccountNamePrefixOf`) as ,Just $ max 0 (length (filter (< a) as) - 1) ] where as = map asItemAccountName displayitems uopts' = uopts{cliopts_=copts{reportopts_=ropts'}} ropts' = ropts{accountlistmode_=if tree_ ropts then ALTree else ALFlat} q = And [queryFromOpts d ropts, excludeforecastq (forecast_ ropts)] where -- Except in forecast mode, exclude future/forecast transactions. excludeforecastq (Just _) = Any excludeforecastq Nothing = -- not:date:tomorrow- not:tag:generated-transaction And [ Not (Date $ DateSpan (Just $ addDays 1 d) Nothing) ,Not generatedTransactionTag ] -- run the report (items,_total) = balanceReport ropts' q j -- pre-render the list items displayitem (fullacct, shortacct, indent, bal) = AccountsScreenItem{asItemIndentLevel = indent ,asItemAccountName = fullacct ,asItemDisplayAccountName = replaceHiddenAccountsNameWith "All" $ if tree_ ropts' then shortacct else fullacct ,asItemRenderedAmounts = map (showAmountWithoutPrice False) amts } where Mixed amts = normaliseMixedAmountSquashPricesForDisplay $ stripPrices bal stripPrices (Mixed as) = Mixed $ map stripprice as where stripprice a = a{aprice=Nothing} displayitems = map displayitem items -- blanks added for scrolling control, cf RegisterScreen blankitems = replicate 100 AccountsScreenItem{asItemIndentLevel = 0 ,asItemAccountName = "" ,asItemDisplayAccountName = "" ,asItemRenderedAmounts = [] } asInit _ _ _ = error "init function called with wrong screen type, should not happen" -- PARTIAL: asDraw :: UIState -> [Widget Name] asDraw UIState{aopts=_uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}} ,ajournal=j ,aScreen=s@AccountsScreen{} ,aMode=mode } = case mode of Help -> [helpDialog copts, 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 = withAttr ("border" <> "filename") files <+> toggles <+> str (" account " ++ if ishistorical then "balances" else "changes") <+> borderPeriodStr (if ishistorical then "at end of" else "in") (period_ ropts) <+> borderQueryStr querystr <+> borderDepthStr mdepth <+> str (" ("++curidx++"/"++totidx++")") <+> (if ignore_assertions_ $ inputopts_ copts then withAttr ("border" <> "query") (str " ignoring balance assertions") else str "") where files = case journalFilePaths j of [] -> str "" f:_ -> 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)") toggles = withAttr ("border" <> "query") $ str $ unwords $ concat [ [""] ,if empty_ ropts then [] else ["nonzero"] ,uiShowStatus copts $ statuses_ ropts ,if real_ ropts then ["real"] else [] ] querystr = query_ ropts mdepth = depth_ ropts curidx = case _asList s ^. listSelectedL of Nothing -> "-" Just i -> show (i + 1) totidx = show $ V.length nonblanks where nonblanks = V.takeWhile (not . T.null . asItemAccountName) $ s ^. asList . listElementsL bottomlabel = case mode of Minibuffer ed -> minibuffer ed _ -> quickhelp where quickhelp = borderKeysStr' [ ("?", str "help") -- ,("RIGHT", str "register") ,("t", renderToggle (tree_ ropts) "list" "tree") -- ,("t", str "tree") -- ,("l", str "list") ,("-+", str "depth") ,("H", renderToggle (not ishistorical) "end-bals" "changes") ,("F", renderToggle1 (isJust $ forecast_ ropts) "forecast") --,("/", "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" -- PARTIAL: 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 let nonblanks = V.takeWhile (not . T.null . asItemAccountName) $ _asList^.listElementsL lastnonblankidx = max 0 (length nonblanks - 1) -- 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 (EvKey (KChar 'l') [MCtrl]) -> redraw ui VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui 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 VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw ui VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend 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 endPosition (journalFilePath j)) >> uiReloadJournalIfChanged copts d j ui VtyEvent (EvKey (KChar 'B') []) -> continue $ regenerateScreens j d $ toggleCost ui VtyEvent (EvKey (KChar 'V') []) -> continue $ regenerateScreens j d $ toggleValue 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 -- display mode/query toggles VtyEvent (EvKey (KChar 'H') []) -> asCenterAndContinue $ regenerateScreens j d $ toggleHistorical ui VtyEvent (EvKey (KChar 't') []) -> asCenterAndContinue $ regenerateScreens j d $ toggleTree ui VtyEvent (EvKey (KChar 'Z') []) -> asCenterAndContinue $ regenerateScreens j d $ toggleEmpty ui VtyEvent (EvKey (KChar 'R') []) -> asCenterAndContinue $ regenerateScreens j d $ toggleReal ui VtyEvent (EvKey (KChar 'U') []) -> asCenterAndContinue $ regenerateScreens j d $ toggleUnmarked ui VtyEvent (EvKey (KChar 'P') []) -> asCenterAndContinue $ regenerateScreens j d $ togglePending ui VtyEvent (EvKey (KChar 'C') []) -> asCenterAndContinue $ regenerateScreens j d $ toggleCleared ui VtyEvent (EvKey (KChar 'F') []) -> continue $ regenerateScreens j d $ toggleForecast d 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 e | e `elem` moveLeftEvents -> continue $ popScreen ui VtyEvent (EvKey (KChar 'l') [MCtrl]) -> scrollSelectionToMiddle _asList >> redraw ui VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui -- enter register screen for selected account (if there is one), -- centering its selected transaction if possible VtyEvent e | e `elem` moveRightEvents , not $ isBlankElement $ listSelectedElement _asList-> -- TODO center selection after entering register screen; neither of these works till second time entering; easy strictifications didn't help rsCenterAndContinue $ -- flip rsHandle (VtyEvent (EvKey (KChar 'l') [MCtrl])) $ screenEnter d regscr ui where regscr = rsSetAccount selacct isdepthclipped registerScreen isdepthclipped = case getDepth ui of Just d -> accountNameLevel selacct >= d Nothing -> False -- prevent moving down over blank padding items; -- instead scroll down by one, until maximally scrolled - shows the end has been reached VtyEvent (EvKey (KDown) []) | isBlankElement mnextelement -> do vScrollBy (viewportScroll $ _asList^.listNameL) 1 continue ui where mnextelement = listSelectedElement $ listMoveDown _asList -- if page down or end leads to a blank padding item, stop at last non-blank VtyEvent e@(EvKey k []) | k `elem` [KPageDown, KEnd] -> do list <- handleListEvent e _asList if isBlankElement $ listSelectedElement list then do let list' = listMoveTo lastnonblankidx list scrollSelectionToMiddle list' continue ui{aScreen=scr{_asList=list'}} else continue ui{aScreen=scr{_asList=list}} -- fall through to the list's event handler (handles up/down) VtyEvent ev -> do newitems <- handleListEvent (normaliseMovementKeys ev) _asList continue $ ui{aScreen=scr & asList .~ newitems & asSelectedAccount .~ selacct } AppEvent _ -> continue ui MouseDown _ _ _ _ -> continue ui MouseUp _ _ _ -> continue ui where journalspan = journalDateSpan False j asHandle _ _ = error "event handler called with wrong screen type, should not happen" -- PARTIAL: asSetSelectedAccount a s@AccountsScreen{} = s & asSelectedAccount .~ a asSetSelectedAccount _ s = s isBlankElement mel = ((asItemAccountName . snd) <$> mel) == Just "" asCenterAndContinue ui = do scrollSelectionToMiddle $ _asList $ aScreen ui continue ui hledger-ui-1.19.1/Hledger/UI/Editor.hs0000644000000000000000000001021113700101030015443 0ustar0000000000000000{- | Editor integration. -} -- {-# LANGUAGE OverloadedStrings #-} module Hledger.UI.Editor ( -- TextPosition endPosition ,runEditor ,runIadd ) where import Control.Applicative ((<|>)) import Safe import System.Environment import System.Exit import System.FilePath import System.Process import Hledger -- | A position we can move to in a text editor: a line and optional column number. -- Line number 1 or 0 means the first line. A negative line number means the last line. type TextPosition = (Int, Maybe Int) -- | The text position meaning "last line, first column". endPosition :: Maybe TextPosition endPosition = Just (-1,Nothing) -- | Run the hledger-iadd executable on the given file, blocking until it exits, -- and return the exit code; or raise an error. -- hledger-iadd is an alternative to the built-in add command. runIadd :: FilePath -> IO ExitCode runIadd f = runCommand ("hledger-iadd -f " ++ f) >>= waitForProcess -- | Run the user's preferred text editor (or try a default editor), -- on the given file, blocking until it exits, and return the exit -- code; or raise an error. If a text position is provided, the editor -- will be focussed at that position in the file, if we know how. runEditor :: Maybe TextPosition -> FilePath -> IO ExitCode runEditor mpos f = editFileAtPositionCommand mpos f >>= runCommand >>= waitForProcess -- | Get a shell command line to open the user's preferred text editor -- (or a default editor) on the given file, and to focus it at the -- given text position if one is provided and if we know how. -- We know how to focus on position for: emacs, vi, nano. -- We know how to focus on last line for: vi. -- -- Some tests: With line and column numbers specified, -- @ -- if EDITOR is: the command should be: -- ------------- ----------------------------------- -- notepad notepad FILE -- vi vi +LINE FILE -- vi + FILE # negative LINE -- emacs emacs +LINE:COL FILE -- emacs FILE # negative LINE -- (unset) emacsclient -a '' -nw +LINE:COL FILE -- emacsclient -a '' -nw FILE # negative LINE -- @ -- -- How to open editors at the last line of a file: -- @ -- emacs: emacs FILE -f end-of-buffer -- emacsclient: can't -- vi: vi + FILE -- @ -- editFileAtPositionCommand :: Maybe TextPosition -> FilePath -> IO String editFileAtPositionCommand mpos f = do let f' = singleQuoteIfNeeded f editcmd <- getEditCommand let editor = lowercase $ takeFileName $ headDef "" $ words' editcmd let positionarg = case mpos of Just (l, mc) | editor `elem` [ "ex", "vi","vim","view","nvim","evim","eview", "gvim","gview","rvim","rview","rgvim","rgview" ] -> plusAndMaybeLine l mc Just (l, mc) | editor `elem` ["emacs", "emacsclient"] -> plusLineAndMaybeColonColumnOrEnd l mc Just (l, mc) | editor `elem` ["nano"] -> plusLineAndMaybeCommaColumn l mc _ -> "" where plusAndMaybeLine l _ = "+" ++ if l >= 0 then show l else "" plusLineAndMaybeCommaColumn l mc = "+" ++ show l ++ maybe "" ((","++).show) mc plusLineAndMaybeColonColumnOrEnd l mc | l >= 0 = "+" ++ show l ++ maybe "" ((":"++).show) mc | otherwise = "" -- otherwise = "-f end-of-buffer" -- XXX Problems with this: -- it must appear after the filename, whereas +LINE:COL must appear before -- it works only with emacs, not emacsclient return $ unwords [editcmd, positionarg, f'] -- | Get the user's preferred edit command. This is the value of the -- $HLEDGER_UI_EDITOR environment variable, or of $EDITOR, or a -- default ("emacsclient -a '' -nw", which starts/connects to an emacs -- daemon in terminal mode). getEditCommand :: IO String getEditCommand = 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 hledger-ui-1.19.1/Hledger/UI/ErrorScreen.hs0000644000000000000000000001631513722544246016511 0ustar0000000000000000-- The error screen, showing a current error condition (such as a parse error after reloading the journal) {-# LANGUAGE OverloadedStrings, FlexibleContexts, RecordWildCards #-} {-# LANGUAGE CPP #-} module Hledger.UI.ErrorScreen (errorScreen ,uiCheckBalanceAssertions ,uiReloadJournal ,uiReloadJournalIfChanged ) where import Brick -- import Brick.Widgets.Border ("border") import Control.Monad import Control.Monad.IO.Class (liftIO) #if !(MIN_VERSION_base(4,11,0)) import Data.Monoid #endif import Data.Time.Calendar (Day) import Data.Void (Void) import Graphics.Vty (Event(..),Key(..),Modifier(..)) import Text.Megaparsec import Text.Megaparsec.Char import Hledger.Cli hiding (progname,prognameandversion) 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" -- PARTIAL: esDraw :: UIState -> [Widget Name] esDraw UIState{aopts=UIOpts{cliopts_=copts@CliOpts{}} ,aScreen=ErrorScreen{..} ,aMode=mode } = case mode of Help -> [helpDialog copts, 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 ("border" <> "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" -- PARTIAL: 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 VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw ui VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend 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 _ -> (endPosition, 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) VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw ui VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui _ -> continue ui esHandle _ _ = error "event handler called with wrong screen type, should not happen" -- PARTIAL: -- | 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 -- Keep in sync with 'Hledger.Data.Transaction.showGenericSourcePos' hledgerparseerrorpositionp :: ParsecT Void String t (String, Int, Int) hledgerparseerrorpositionp = do anySingle `manyTill` char '"' f <- anySingle `manyTill` (oneOf ['"','\n']) choice [ do string " (line " l <- read <$> some digitChar string ", column " c <- read <$> some digitChar return (f, l, c), do string " (lines " l <- read <$> some digitChar char '-' some digitChar char ')' return (f, l, 1) ] -- 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_ $ inputopts_ copts = ui | otherwise = case journalCheckBalanceAssertions j of Nothing -> ui Just err -> case ui of UIState{aScreen=s@ErrorScreen{}} -> ui{aScreen=s{esError=err}} _ -> screenEnter d errorScreen{esError=err} ui hledger-ui-1.19.1/Hledger/UI/Main.hs0000644000000000000000000002116313723502755015141 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 LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# 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) -- import Data.Monoid -- import Data.List import Data.List.Extra (nubSort) 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.Directory import System.FilePath import System.FSNotify import Brick import qualified Brick.BChan as BC import Hledger import Hledger.Cli hiding (progname,prognameandversion) 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 ---------------------------------------------------------------------- newChan :: IO (BC.BChan a) newChan = BC.newBChan 10 writeChan :: BC.BChan a -> a -> IO () writeChan = BC.writeBChan main :: IO () main = do opts@UIOpts{cliopts_=copts@CliOpts{inputopts_=_iopts,reportopts_=ropts,rawopts_=rawopts}} <- getHledgerUIOpts -- when (debug_ $ cliopts_ opts) $ printf "%s\n" prognameandversion >> printf "opts: %s\n" (show opts) -- always include forecasted periodic transactions when loading data; -- they will be toggled on and off in the UI. let copts' = copts{reportopts_=ropts{forecast_=Just $ fromMaybe nulldatespan (forecast_ ropts)}} case True of _ | "help" `inRawOpts` rawopts -> putStr (showModeUsage uimode) _ | "version" `inRawOpts` rawopts -> putStrLn prognameandversion _ | "binary-filename" `inRawOpts` rawopts -> putStrLn (binaryfilename progname) _ -> withJournalDo copts' (runBrickUi opts) runBrickUi :: UIOpts -> Journal -> IO () runBrickUi uopts@UIOpts{cliopts_=copts@CliOpts{inputopts_=_iopts,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_ =queryDepth q, period_=periodfromoptsandargs, query_ =unwords -- as in ReportOptions, with same limitations $ collectopts filteredQueryArg (rawopts_ copts), -- always disable boring account name eliding, unlike the CLI, for a more regular tree no_elide_=True, -- flip the default for items with zero amounts, show them by default empty_=not $ empty_ ropts, -- show historical balances by default, unlike the CLI balancetype_=HistoricalBalance } } } where q = queryFromOpts d ropts datespanfromargs = queryDateSpan (date2_ ropts) $ fst $ either error' id $ parseQuery d (T.pack $ query_ ropts) -- PARTIAL: periodfromoptsandargs = dateSpanAsPeriod $ spansIntersect [periodAsDateSpan $ period_ ropts, datespanfromargs] filteredQueryArg = \case ("args", v) | not $ any (`isPrefixOf` v) ["depth:", "date:"] -- skip depth/date passed as query -> Just (quoteIfNeeded v) _ -> Nothing -- 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") -- PARTIAL: . filterAccts $ journalAccountNames j filterAccts = case toRegexCI apat of Right re -> filter (regexMatch re . T.unpack) Left _ -> const [] -- Initialising the accounts screen is awkward, requiring -- another temporary UIState value.. ascr' = aScreen $ asInit d True UIState{ astartupopts=uopts' ,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{ astartupopts=uopts' ,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 } -- print (length (show ui)) >> exitSuccess -- show any debug output to this point & quit if not (watch_ uopts') then void $ Brick.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) $ \_ -> -- 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 . fst) $ jfiles j let directories = nubSort $ 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 #if MIN_VERSION_fsnotify(0,3,0) Modified f _ False #else Modified f _ #endif -> 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" $ show fev writeChan eventChan FileChange ) -- and start the app. Must be inside the withManager block let mkvty = mkVty mempty #if MIN_VERSION_brick(0,47,0) vty0 <- mkvty void $ customMain vty0 mkvty (Just eventChan) brickapp ui #else void $ customMain mkvty (Just eventChan) brickapp ui #endif hledger-ui-1.19.1/Hledger/UI/RegisterScreen.hs0000644000000000000000000004720713723502755017210 0ustar0000000000000000-- The account register screen, showing transactions in an account, like hledger-web's register. {-# LANGUAGE OverloadedStrings, FlexibleContexts, RecordWildCards #-} {-# LANGUAGE CPP #-} module Hledger.UI.RegisterScreen (registerScreen ,rsHandle ,rsSetAccount ,rsCenterAndContinue ) where import Control.Monad import Control.Monad.IO.Class (liftIO) import Data.List import Data.List.Split (splitOn) #if !(MIN_VERSION_base(4,11,0)) import Data.Monoid ((<>)) #endif import Data.Maybe import qualified Data.Text as T import Data.Time.Calendar import qualified Data.Vector as V import Graphics.Vty (Event(..),Key(..),Modifier(..)) import Brick import Brick.Widgets.List (handleListEvent, list, listElementsL, listMoveDown, listMoveTo, listNameL, listSelectedElement, listSelectedL, renderList) import Brick.Widgets.Edit import Lens.Micro.Platform import Safe import System.Console.ANSI import Hledger import Hledger.Cli hiding (progname,prognameandversion) 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=_uopts@UIOpts{cliopts_=CliOpts{reportopts_=ropts}}, ajournal=j, aScreen=s@RegisterScreen{..}} = ui{aScreen=s{rsList=newitems'}} where -- gather arguments and queries -- XXX temp inclusive = tree_ ropts || rsForceInclusive thisacctq = Acct $ (if inclusive then accountNameToAccountRegex else accountNameToAccountOnlyRegex) rsAccount ropts' = ropts{ depth_=Nothing } q = And [queryFromOpts d ropts', excludeforecastq (forecast_ ropts)] where -- Except in forecast mode, exclude future/forecast transactions. excludeforecastq (Just _) = Any excludeforecastq Nothing = -- not:date:tomorrow- not:tag:generated-transaction And [ Not (Date $ DateSpan (Just $ addDays 1 d) Nothing) ,Not generatedTransactionTag ] (_label,items) = accountTransactionsReport ropts' j q thisacctq items' = (if empty_ ropts' then id else filter (not . mixedAmountLooksZero . 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 ,rsItemStatus = tstatus 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 = showMixedAmountElided False change ,rsItemBalanceAmount = showMixedAmountElided False bal ,rsItemTransaction = t } -- blank items are added to allow more control of scroll position; we won't allow movement over these blankitems = replicate 100 -- 100 ought to be enough for anyone RegisterScreenItem{rsItemDate = "" ,rsItemStatus = Unmarked ,rsItemDescription = "" ,rsItemOtherAccounts = "" ,rsItemChangeAmount = "" ,rsItemBalanceAmount = "" ,rsItemTransaction = nulltransaction } -- build the List newitems = list RegisterList (V.fromList $ displayitems ++ blankitems) 1 -- decide which transaction is selected: -- if reset is true, the last (latest) transaction; -- otherwise, the previously selected transaction if possible; -- otherwise, the transaction nearest in date to it; -- or if there's several with the same date, the nearest in journal order; -- otherwise, the last (latest) transaction. newitems' = listMoveTo newselidx newitems where newselidx = case (reset, listSelectedElement rsList) of (True, _) -> endidx (_, Nothing) -> endidx (_, Just (_, RegisterScreenItem{rsItemTransaction=Transaction{tindex=prevselidx, tdate=prevseld}})) -> headDef endidx $ catMaybes [ findIndex ((==prevselidx) . tindex . rsItemTransaction) displayitems ,findIndex ((==nearestidbydatethenid) . Just . tindex . rsItemTransaction) displayitems ] where nearestidbydatethenid = third3 <$> (headMay $ sort [(abs $ diffDays (tdate t) prevseld, abs (tindex t - prevselidx), tindex t) | t <- ts]) ts = map rsItemTransaction displayitems endidx = length displayitems - 1 rsInit _ _ _ = error "init function called with wrong screen type, should not happen" -- PARTIAL: rsDraw :: UIState -> [Widget Name] rsDraw UIState{aopts=_uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}} ,aScreen=RegisterScreen{..} ,aMode=mode } = case mode of Help -> [helpDialog copts, 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 + 1 + 2 + 2 -- date column plus at least 1 for status and 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 - 1 - 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 = tree_ ropts || rsForceInclusive toplabel = withAttr ("border" <> "bold") (str $ T.unpack $ replaceHiddenAccountsNameWith "All" rsAccount) -- <+> withAttr ("border" <> "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_ $ inputopts_ copts then withAttr ("border" <> "query") (str " ignoring balance assertions") else str "") where togglefilters = case concat [ uiShowStatus copts $ statuses_ ropts ,if real_ ropts then ["real"] else [] ,if empty_ ropts then [] else ["nonzero"] ] of [] -> str "" fs -> withAttr ("border" <> "query") (str $ " " ++ intercalate ", " fs) cur = str $ case rsList ^. listSelectedL of Nothing -> "-" Just i -> show (i + 1) total = str $ show $ length nonblanks nonblanks = V.takeWhile (not . null . rsItemDate) $ rsList^.listElementsL -- query = query_ $ reportopts_ $ cliopts_ opts bottomlabel = case mode of Minibuffer ed -> minibuffer ed _ -> quickhelp where quickhelp = borderKeysStr' [ ("?", str "help") ,("LEFT", str "back") -- ,("RIGHT", str "transaction") -- tree/list mode - rsForceInclusive may override, but use tree_ to ensure a visible toggle effect ,("t", renderToggle (tree_ ropts) "list(-subs)" "tree(+subs)") -- ,("t", str "tree(+subs)") -- ,("l", str "list(-subs)") ,("H", renderToggle (not ishistorical) "historical" "period") ,("F", renderToggle1 (isJust $ forecast_ ropts) "forecast") -- ,("a", "add") -- ,("g", "reload") -- ,("q", "quit") ] rsDraw _ = error "draw function called with wrong screen type, should not happen" -- PARTIAL: 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 1) (Just 1) True True (show rsItemStatus)) <+> 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 let journalspan = journalDateSpan False j nonblanks = V.takeWhile (not . null . rsItemDate) $ rsList^.listElementsL lastnonblankidx = max 0 (length nonblanks - 1) 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 (EvKey (KChar 'l') [MCtrl]) -> redraw ui VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui 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 VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw ui VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend 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 -> (endPosition, 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) -- display mode/query toggles VtyEvent (EvKey (KChar 'B') []) -> rsCenterAndContinue $ regenerateScreens j d $ toggleCost ui VtyEvent (EvKey (KChar 'V') []) -> rsCenterAndContinue $ regenerateScreens j d $ toggleValue ui VtyEvent (EvKey (KChar 'H') []) -> rsCenterAndContinue $ regenerateScreens j d $ toggleHistorical ui VtyEvent (EvKey (KChar 't') []) -> rsCenterAndContinue $ regenerateScreens j d $ toggleTree ui VtyEvent (EvKey (KChar 'Z') []) -> rsCenterAndContinue $ regenerateScreens j d $ toggleEmpty ui VtyEvent (EvKey (KChar 'R') []) -> rsCenterAndContinue $ regenerateScreens j d $ toggleReal ui VtyEvent (EvKey (KChar 'U') []) -> rsCenterAndContinue $ regenerateScreens j d $ toggleUnmarked ui VtyEvent (EvKey (KChar 'P') []) -> rsCenterAndContinue $ regenerateScreens j d $ togglePending ui VtyEvent (EvKey (KChar 'C') []) -> rsCenterAndContinue $ regenerateScreens j d $ toggleCleared ui VtyEvent (EvKey (KChar 'F') []) -> rsCenterAndContinue $ regenerateScreens j d $ toggleForecast d 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 e | e `elem` moveLeftEvents -> continue $ popScreen ui VtyEvent (EvKey (KChar 'l') [MCtrl]) -> scrollSelectionToMiddle rsList >> redraw ui VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui -- enter transaction screen for selected transaction VtyEvent e | e `elem` moveRightEvents -> do case listSelectedElement rsList of Just (_, RegisterScreenItem{rsItemTransaction=t}) -> let ts = map rsItemTransaction $ V.toList $ nonblanks numberedts = zip [1..] ts i = maybe 0 (toInteger . (+1)) $ elemIndex t ts -- XXX in continue $ screenEnter d transactionScreen{tsTransaction=(i,t) ,tsTransactions=numberedts ,tsAccount=rsAccount} ui Nothing -> continue ui -- prevent moving down over blank padding items; -- instead scroll down by one, until maximally scrolled - shows the end has been reached VtyEvent e | e `elem` moveDownEvents, isBlankElement mnextelement -> do vScrollBy (viewportScroll $ rsList^.listNameL) 1 continue ui where mnextelement = listSelectedElement $ listMoveDown rsList -- if page down or end leads to a blank padding item, stop at last non-blank VtyEvent e@(EvKey k []) | k `elem` [KPageDown, KEnd] -> do list <- handleListEvent e rsList if isBlankElement $ listSelectedElement list then do let list' = listMoveTo lastnonblankidx list scrollSelectionToMiddle list' continue ui{aScreen=s{rsList=list'}} else continue ui{aScreen=s{rsList=list}} -- fall through to the list's event handler (handles other [pg]up/down events) VtyEvent ev -> do let ev' = normaliseMovementKeys ev newitems <- handleListEvent ev' rsList continue ui{aScreen=s{rsList=newitems}} AppEvent _ -> continue ui MouseDown _ _ _ _ -> continue ui MouseUp _ _ _ -> continue ui rsHandle _ _ = error "event handler called with wrong screen type, should not happen" -- PARTIAL: isBlankElement mel = ((rsItemDate . snd) <$> mel) == Just "" rsCenterAndContinue ui = do scrollSelectionToMiddle $ rsList $ aScreen ui continue ui hledger-ui-1.19.1/Hledger/UI/Theme.hs0000644000000000000000000001157713700101030015277 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 CPP #-} {-# LANGUAGE OverloadedStrings #-} module Hledger.UI.Theme ( defaultTheme ,getTheme ,themes ,themeNames ) where import qualified Data.Map as M import Data.Maybe #if !(MIN_VERSION_base(4,11,0)) import Data.Monoid #endif import Graphics.Vty import Brick 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 active = fg brightWhite & bold selectbg = yellow select = black `on` selectbg themesList :: [(String, AttrMap)] themesList = [ ("default", attrMap (black `on` white) [ ("border" , white `on` black & dim) ,("border" <> "bold" , currentAttr & bold) ,("border" <> "depth" , active) ,("border" <> "filename" , currentAttr) ,("border" <> "key" , active) ,("border" <> "minibuffer" , white `on` black & bold) ,("border" <> "query" , active) ,("border" <> "selected" , active) ,("error" , fg red) ,("help" , white `on` black & dim) ,("help" <> "heading" , fg yellow) ,("help" <> "key" , active) -- ,("list" , black `on` white) -- ,("list" <> "amount" , currentAttr) ,("list" <> "amount" <> "decrease" , fg red) -- ,("list" <> "amount" <> "increase" , fg green) ,("list" <> "amount" <> "decrease" <> "selected" , red `on` selectbg & bold) -- ,("list" <> "amount" <> "increase" <> "selected" , green `on` selectbg & bold) ,("list" <> "balance" , currentAttr & bold) ,("list" <> "balance" <> "negative" , fg red) ,("list" <> "balance" <> "positive" , fg black) ,("list" <> "balance" <> "negative" <> "selected" , red `on` selectbg & bold) ,("list" <> "balance" <> "positive" <> "selected" , select & bold) ,("list" <> "selected" , select) -- ,("list" <> "accounts" , white `on` brightGreen) -- ,("list" <> "selected" , black `on` brightYellow) ]) ,("greenterm", attrMap (green `on` black) [ ("list" <> "selected" , black `on` green) ]) ,("terminal", attrMap defAttr [ ("border" , white `on` black), ("list" , defAttr), ("list" <> "selected" , defAttr & reverseVideo) ]) ] -- 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.19.1/Hledger/UI/TransactionScreen.hs0000644000000000000000000002451013722544246017701 0ustar0000000000000000-- The transaction screen, showing a single transaction's general journal entry. {-# LANGUAGE OverloadedStrings, TupleSections, RecordWildCards #-} -- , FlexibleContexts {-# LANGUAGE CPP #-} module Hledger.UI.TransactionScreen (transactionScreen ,rsSelect ) where import Control.Monad import Control.Monad.IO.Class (liftIO) import Data.List import Data.Maybe #if !(MIN_VERSION_base(4,11,0)) import Data.Monoid #endif import qualified Data.Text as T import Data.Time.Calendar (Day) import Graphics.Vty (Event(..),Key(..),Modifier(..)) import Brick import Brick.Widgets.List (listMoveTo) import Hledger import Hledger.Cli hiding (progname,prognameandversion) 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{} } = -- plog ("initialising TransactionScreen, value_ is " -- -- ++ (pshow (Just (AtDefault Nothing)::Maybe ValuationType)) -- ++(pshow (value_ _ropts)) -- XXX calling value_ here causes plog to fail with: debug.log: openFile: resource busy (file is locked) -- ++ "?" -- ++" and first commodity is") -- (acommodity$head$amounts$pamount$head$tpostings$snd$tsTransaction) -- `seq` ui tsInit _ _ _ = error "init function called with wrong screen type, should not happen" -- PARTIAL: tsDraw :: UIState -> [Widget Name] tsDraw UIState{aopts=UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}} ,ajournal=j ,aScreen=TransactionScreen{tsTransaction=(i,t) ,tsTransactions=nts ,tsAccount=acct } ,aMode=mode } = case mode of Help -> [helpDialog copts, maincontent] -- Minibuffer e -> [minibuffer e, maincontent] _ -> [maincontent] where maincontent = Widget Greedy Greedy $ do let prices = journalPriceOracle (infer_value_ ropts) j styles = journalCommodityStyles j periodlast = fromMaybe (error' "TransactionScreen: expected a non-empty journal") $ -- PARTIAL: shouldn't happen reportPeriodOrJournalLastDay ropts j mreportlast = reportPeriodLastDay ropts today = fromMaybe (error' "TransactionScreen: could not pick a valuation date, ReportOpts today_ is unset") $ today_ ropts -- PARTIAL: multiperiod = interval_ ropts /= NoInterval render $ defaultLayout toplabel bottomlabel $ str $ showTransactionOneLineAmounts $ (if valuationTypeIsCost ropts then transactionToCost (journalCommodityStyles j) else id) $ (if valuationTypeIsDefaultValue ropts then (\t -> transactionApplyValuation prices styles periodlast mreportlast today multiperiod t (AtDefault Nothing)) else id) $ -- (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_ $ inputopts_ copts then withAttr ("border" <> "query") (str " ignoring balance assertions") else str "") where togglefilters = case concat [ uiShowStatus copts $ statuses_ ropts ,if real_ ropts then ["real"] else [] ,if empty_ ropts then [] else ["nonzero"] ] of [] -> str "" fs -> withAttr ("border" <> "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" -- PARTIAL: 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 VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw ui VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend 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 -- plog (if e == AppEvent FileChange then "file change" else "manual reload") "" `seq` return () d <- liftIO getCurrentDay ej <- liftIO $ journalReload copts case ej of Left err -> continue $ screenEnter d errorScreen{esError=err} ui Right j' -> do continue $ regenerateScreens j' d $ regenerateTransactions ropts d j' s acct i $ -- added (inline) 201512 (why ?) clearCostValue $ ui VtyEvent (EvKey (KChar 'I') []) -> continue $ uiCheckBalanceAssertions d (toggleIgnoreBalanceAssertions ui) -- for toggles that may change the current/prev/next transactions, -- we must regenerate the transaction list, like the g handler above ? with regenerateTransactions ? TODO WIP -- 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 (KChar 'B') []) -> continue $ regenerateScreens j d $ -- regenerateTransactions ropts d j s acct i $ toggleCost ui VtyEvent (EvKey (KChar 'V') []) -> continue $ regenerateScreens j d $ -- regenerateTransactions ropts d j s acct i $ toggleValue ui VtyEvent e | e `elem` moveUpEvents -> continue $ regenerateScreens j d ui{aScreen=s{tsTransaction=(iprev,tprev)}} VtyEvent e | e `elem` moveDownEvents -> continue $ regenerateScreens j d ui{aScreen=s{tsTransaction=(inext,tnext)}} VtyEvent e | e `elem` moveLeftEvents -> continue ui'' where ui'@UIState{aScreen=scr} = popScreen ui ui'' = ui'{aScreen=rsSelect (fromIntegral i) scr} VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw ui VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui _ -> continue ui tsHandle _ _ = error "event handler called with wrong screen type, should not happen" -- PARTIAL: -- Got to redo the register screen's transactions report, to get the latest transactions list for this screen. -- XXX Duplicates rsInit. Why do we have to do this as well as regenerateScreens ? regenerateTransactions :: ReportOpts -> Day -> Journal -> Screen -> AccountName -> Integer -> UIState -> UIState regenerateTransactions ropts d j s acct i ui = 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 in ui{aScreen=s{tsTransaction=(i',t') ,tsTransactions=numberedts ,tsAccount=acct }} -- | 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.19.1/Hledger/UI/UIOptions.hs0000644000000000000000000000734713723502755016156 0ustar0000000000000000{-# LANGUAGE CPP #-} {-# LANGUAGE LambdaCase #-} {-| -} module Hledger.UI.UIOptions where import Data.Default import Data.List (intercalate) import System.Environment 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"] (setboolopt "rules-file") "run with no terminal output, showing console" flagNone ["watch"] (setboolopt "watch") "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"] (setboolopt "change") "show period balances (changes) at startup instead of historical balances" -- ,flagNone ["cumulative"] (setboolopt "cumulative") -- "show balance change accumulated across periods (in multicolumn reports)" -- ,flagNone ["historical","H"] (setboolopt "historical") -- "show historical ending balance in each period (includes postings before report start date)\n " ] ++ flattreeflags False -- ,flagNone ["present"] (setboolopt "present") "exclude transactions dated later than today (default)" -- ,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"] (setboolopt "no-elide") "don't compress empty parent accounts on one line" --uimode :: Mode RawOpts uimode = (mode "hledger-ui" (setopt "command" "ui" def) "browse accounts, postings and entries in a full-window curses interface" (argsFlag "[PATTERNS]") []){ modeGroupFlags = Group { groupUnnamed = uiflags ,groupHidden = hiddenflags ++ [flagNone ["future"] (setboolopt "forecast") "compatibility alias, use --forecast instead"] ,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 () -- XXX some refactoring seems due getHledgerUIOpts :: IO UIOpts --getHledgerUIOpts = processArgs uimode >>= return >>= rawOptsToUIOpts getHledgerUIOpts = do args <- getArgs >>= expandArgsAt let args' = replaceNumericFlags args let cmdargopts = either usageError id $ process uimode args' rawOptsToUIOpts cmdargopts hledger-ui-1.19.1/Hledger/UI/UIState.hs0000644000000000000000000003650113723300774015572 0ustar0000000000000000{- | UIState operations. -} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Hledger.UI.UIState where import Brick.Widgets.Edit import Data.List import Data.Text.Zipper (gotoEOL) import Data.Time.Calendar (Day) import Data.Maybe (fromMaybe) import Hledger import Hledger.Cli.CliOptions import Hledger.UI.UITypes import Hledger.UI.UIOptions -- | Toggle between showing only unmarked items or all items. toggleUnmarked :: UIState -> UIState toggleUnmarked ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=reportOptsToggleStatusSomehow Unmarked copts ropts}}} -- | 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_=reportOptsToggleStatusSomehow Pending copts ropts}}} -- | 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_=reportOptsToggleStatusSomehow Cleared copts ropts}}} -- TODO testing different status toggle styles -- | Generate zero or more indicators of the status filters currently active, -- which will be shown comma-separated as part of the indicators list. uiShowStatus :: CliOpts -> [Status] -> [String] uiShowStatus copts ss = case style of -- in style 2, instead of "Y, Z" show "not X" Just 2 | length ss == numstatuses-1 -> map (("not "++). showstatus) $ sort $ complement ss -- should be just one _ -> map showstatus $ sort ss where numstatuses = length [minBound..maxBound::Status] style = maybeposintopt "status-toggles" $ rawopts_ copts showstatus Cleared = "cleared" showstatus Pending = "pending" showstatus Unmarked = "unmarked" reportOptsToggleStatusSomehow :: Status -> CliOpts -> ReportOpts -> ReportOpts reportOptsToggleStatusSomehow s copts ropts = case maybeposintopt "status-toggles" $ rawopts_ copts of Just 2 -> reportOptsToggleStatus2 s ropts Just 3 -> reportOptsToggleStatus3 s ropts -- Just 4 -> reportOptsToggleStatus4 s ropts -- Just 5 -> reportOptsToggleStatus5 s ropts _ -> reportOptsToggleStatus1 s ropts -- 1 UPC toggles only X/all reportOptsToggleStatus1 s ropts@ReportOpts{statuses_=ss} | ss == [s] = ropts{statuses_=[]} | otherwise = ropts{statuses_=[s]} -- 2 UPC cycles X/not-X/all -- repeatedly pressing X cycles: -- [] U [u] -- [u] U [pc] -- [pc] U [] -- pressing Y after first or second step starts new cycle: -- [u] P [p] -- [pc] P [p] reportOptsToggleStatus2 s ropts@ReportOpts{statuses_=ss} | ss == [s] = ropts{statuses_=complement [s]} | ss == complement [s] = ropts{statuses_=[]} | otherwise = ropts{statuses_=[s]} -- XXX assume only three values -- 3 UPC toggles each X reportOptsToggleStatus3 s ropts@ReportOpts{statuses_=ss} | s `elem` ss = ropts{statuses_=filter (/= s) ss} | otherwise = ropts{statuses_=simplifyStatuses (s:ss)} -- 4 upc sets X, UPC sets not-X --reportOptsToggleStatus4 s ropts@ReportOpts{statuses_=ss} -- | s `elem` ss = ropts{statuses_=filter (/= s) ss} -- | otherwise = ropts{statuses_=simplifyStatuses (s:ss)} -- -- 5 upc toggles X, UPC toggles not-X --reportOptsToggleStatus5 s ropts@ReportOpts{statuses_=ss} -- | s `elem` ss = ropts{statuses_=filter (/= s) ss} -- | otherwise = ropts{statuses_=simplifyStatuses (s:ss)} -- | Given a list of unique enum values, list the other possible values of that enum. complement :: (Bounded a, Enum a, Eq a) => [a] -> [a] complement = ([minBound..maxBound] \\) -- -- | 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} -- | Show primary amounts, not cost or value. clearCostValue :: UIState -> UIState clearCostValue ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{value_ = plog "clearing value mode" Nothing}}}} -- | Toggle between showing the primary amounts or costs. toggleCost :: UIState -> UIState toggleCost ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{value_ = valuationToggleCost $ value_ ropts}}}} -- | Toggle between showing primary amounts or default valuation. toggleValue :: UIState -> UIState toggleValue ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{ value_ = plog "toggling value mode to" $ valuationToggleValue $ value_ ropts}}}} -- | Basic toggling of -B/cost, for hledger-ui. valuationToggleCost :: Maybe ValuationType -> Maybe ValuationType valuationToggleCost (Just (AtCost _)) = Nothing valuationToggleCost _ = Just $ AtCost Nothing -- | Basic toggling of -V, for hledger-ui. valuationToggleValue :: Maybe ValuationType -> Maybe ValuationType valuationToggleValue (Just (AtDefault _)) = Nothing valuationToggleValue _ = Just $ AtDefault Nothing -- | Set hierarchic account tree mode. setTree :: UIState -> UIState setTree ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{accountlistmode_=ALTree}}}} -- | Set flat account list mode. setList :: UIState -> UIState setList ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{accountlistmode_=ALFlat}}}} -- | Toggle between flat and tree mode. If current mode is unspecified/default, assume it's flat. toggleTree :: UIState -> UIState toggleTree ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=toggleTreeMode ropts}}} where toggleTreeMode ropts | accountlistmode_ ropts == ALTree = ropts{accountlistmode_=ALFlat} | otherwise = ropts{accountlistmode_=ALTree} -- | 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 hledger-ui's "forecast mode". In forecast mode, periodic -- transactions (generated by periodic rules) are enabled (as with -- hledger --forecast), and also future transactions in general -- (including non-periodic ones) are displayed. In normal mode, all -- future transactions (periodic or not) are suppressed (unlike -- command-line hledger). -- -- After toggling this, we do a full reload of the journal from disk -- to make it take effect; currently that's done in the callers (cf -- AccountsScreen, RegisterScreen) where it's easier. This is -- overkill, probably we should just hide/show the periodic -- transactions with a query for their special tag. -- toggleForecast :: Day -> UIState -> UIState toggleForecast d ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts'}} where copts' = copts{reportopts_=ropts{forecast_=forecast'}} forecast' = case forecast_ ropts of Just _ -> Nothing Nothing -> Just $ fromMaybe nulldatespan $ forecastPeriodFromRawOpts d $ rawopts_ copts -- | 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{inputopts_=iopts}}} = ui{aopts=uopts{cliopts_=copts{inputopts_=iopts{ignore_assertions_=not $ ignore_assertions_ iopts}}}} -- | 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}}}} -- | Clear any report period limits. resetReportPeriod :: UIState -> UIState resetReportPeriod = setReportPeriod PeriodAll -- | 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}}}} -- | Reset some filters & toggles. resetFilter :: UIState -> UIState resetFilter ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{ empty_=True ,statuses_=[] ,real_=False ,query_="" --,period_=PeriodAll }}}} -- | Reset all options state to exactly what it was at startup -- (preserving any command-line options/arguments). resetOpts :: UIState -> UIState resetOpts ui@UIState{astartupopts} = ui{aopts=astartupopts} 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 (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 $ resetOpts $ 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.19.1/Hledger/UI/UITypes.hs0000644000000000000000000001601413722544246015616 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 (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 { astartupopts :: UIOpts -- ^ the command-line options and query arguments specified at startup ,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 ,rsItemStatus :: Status -- ^ transaction status ,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.19.1/Hledger/UI/UIUtils.hs0000644000000000000000000003227713723300774015620 0ustar0000000000000000{- | Rendering & misc. helpers. -} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE CPP #-} module Hledger.UI.UIUtils ( borderDepthStr ,borderKeysStr ,borderKeysStr' ,borderPeriodStr ,borderQueryStr ,defaultLayout ,helpDialog ,helpHandle ,minibuffer ,moveDownEvents ,moveLeftEvents ,moveRightEvents ,moveUpEvents ,normaliseMovementKeys ,renderToggle ,renderToggle1 ,replaceHiddenAccountsNameWith ,scrollSelectionToMiddle ,suspend ,redraw ) where import Brick import Brick.Widgets.Border import Brick.Widgets.Border.Style import Brick.Widgets.Dialog import Brick.Widgets.Edit import Brick.Widgets.List (List, listSelectedL, listNameL, listItemHeightL) import Control.Monad.IO.Class import Data.List import Data.Maybe #if !(MIN_VERSION_base(4,11,0)) import Data.Monoid #endif import Graphics.Vty (Event(..),Key(..),Modifier(..),Vty(..),Color,Attr,currentAttr,refresh -- ,Output(displayBounds,mkDisplayContext),DisplayContext(..) ) import Lens.Micro.Platform import System.Environment import Hledger hiding (Color) import Hledger.Cli (CliOpts) import Hledger.Cli.DocFiles import Hledger.UI.UITypes import Hledger.UI.UIState -- | On posix platforms, send the system STOP signal to suspend the -- current program. On windows, does nothing. #ifdef mingw32_HOST_OS suspendSignal :: IO () suspendSignal = return () #else import System.Posix.Signals suspendSignal :: IO () suspendSignal = raiseSignal sigSTOP #endif -- | On posix platforms, suspend the program using the STOP signal, -- like control-z in bash, returning to the original shell prompt, -- and when resumed, continue where we left off. -- On windows, does nothing. suspend :: s -> EventM a (Next s) suspend st = suspendAndResume $ suspendSignal >> return st -- | Tell vty to redraw the whole screen, and continue. redraw :: s -> EventM a (Next s) redraw st = getVtyHandle >>= liftIO . refresh >> continue st -- | 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" -- | Draw the help dialog, called when help mode is active. helpDialog :: CliOpts -> Widget Name helpDialog _copts = Widget Fixed Fixed $ do c <- getContext render $ withDefAttr "help" $ renderDialog (dialog (Just "Help (LEFT/ESC/?/q to close help)") Nothing (c^.availWidthL)) $ -- (Just (0,[("ok",())])) padTop (Pad 0) $ padLeft (Pad 1) $ padRight (Pad 1) $ vBox [ hBox [ padRight (Pad 1) $ vBox [ withAttr ("help" <> "heading") $ str "Navigation" ,renderKey ("UP/DOWN/PUP/PDN/HOME/END/k/j/C-p/C-n", "") ,str " move selection up/down" ,renderKey ("RIGHT/l/C-f", "show txns, or txn detail") ,renderKey ("LEFT/h/C-b ", "go back") ,renderKey ("ESC ", "cancel, or reset app state") ,str " " ,withAttr ("help" <> "heading") $ str "Accounts screen" ,renderKey ("1234567890-+ ", "set/adjust depth limit") ,renderKey ("t ", "toggle accounts tree/list mode") ,renderKey ("H ", "toggle historical balance/change") ,str " " ,withAttr ("help" <> "heading") $ str "Register screen" ,renderKey ("t ", "toggle subaccount txns\n(and accounts tree/list mode)") ,renderKey ("H ", "toggle historical/period total") ,str " " ,withAttr ("help" <> "heading") $ str "Help" ,renderKey ("? ", "toggle this help") ,renderKey ("p/m/i", "while help is open:\nshow manual in pager/man/info") ,str " " ] ,padLeft (Pad 1) $ padRight (Pad 0) $ vBox [ withAttr ("help" <> "heading") $ str "Filtering" ,renderKey ("/ ", "set a filter query") ,renderKey ("F ", "show future & periodic txns") ,renderKey ("R ", "show real/all postings") ,renderKey ("Z ", "show nonzero/all amounts") ,renderKey ("U/P/C ", "show unmarked/pending/cleared") ,renderKey ("S-DOWN /S-UP ", "shrink/grow period") ,renderKey ("S-RIGHT/S-LEFT", "next/previous period") ,renderKey ("T ", "set period to today") ,renderKey ("DEL ", "reset filters") ,str " " ,withAttr ("help" <> "heading") $ str "Other" ,renderKey ("a ", "add transaction (hledger add)") ,renderKey ("A ", "add transaction (hledger-iadd)") ,renderKey ("B ", "show amounts/costs") ,renderKey ("E ", "open editor") ,renderKey ("I ", "toggle balance assertions") ,renderKey ("V ", "show amounts/market values") ,renderKey ("g ", "reload data") ,renderKey ("C-l ", "redraw & recenter") ,renderKey ("C-z ", "suspend") ,renderKey ("q ", "quit") ] ] -- ,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 ("help" <> "key") (str key) <+> str " " <+> str desc -- | Event handler used when help mode is active. -- May invoke $PAGER, less, man or info, which is likely to fail on MS Windows, TODO. helpHandle :: UIState -> BrickEvent Name AppEvent -> EventM Name (Next UIState) helpHandle ui ev = do pagerprog <- liftIO $ fromMaybe "less" <$> lookupEnv "PAGER" case ev of VtyEvent e | e `elem` closeHelpEvents -> continue $ setMode Normal ui VtyEvent (EvKey (KChar 'p') []) -> suspendAndResume $ runPagerForTopic pagerprog "hledger-ui" >> return ui' VtyEvent (EvKey (KChar 'm') []) -> suspendAndResume $ runManForTopic "hledger-ui" >> return ui' VtyEvent (EvKey (KChar 'i') []) -> suspendAndResume $ runInfoForTopic "hledger-ui" >> return ui' _ -> continue ui where ui' = setMode Normal ui closeHelpEvents = moveLeftEvents ++ [EvKey KEsc [], EvKey (KChar '?') [], EvKey (KChar 'q') []] -- | Draw the minibuffer. minibuffer :: Editor String Name -> Widget Name minibuffer ed = forceAttr ("border" <> "minibuffer") $ hBox [txt "filter: ", renderEditor (str . unlines) True ed] borderQueryStr :: String -> Widget Name borderQueryStr "" = str "" borderQueryStr qry = str " matching " <+> withAttr ("border" <> "query") (str qry) borderDepthStr :: Maybe Int -> Widget Name borderDepthStr Nothing = str "" borderDepthStr (Just d) = str " to depth " <+> withAttr ("border" <> "query") (str $ show d) borderPeriodStr :: String -> Period -> Widget Name borderPeriodStr _ PeriodAll = str "" borderPeriodStr preposition p = str (" "++preposition++" ") <+> withAttr ("border" <> "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 ("border" <> "key") (str keys) <+> str ":" <+> desc | (keys, desc) <- keydescs] where -- sep = str " | " sep = str " " -- | Show both states of a toggle ("aaa/bbb"), highlighting the active one. renderToggle :: Bool -> String -> String -> Widget Name renderToggle isright l r = let bold = withAttr ("border" <> "selected") in if isright then str (l++"/") <+> bold (str r) else bold (str l) <+> str ("/"++r) -- | Show a toggle's label, highlighted (bold) when the toggle is active. renderToggle1 :: Bool -> String -> Widget Name renderToggle1 isactive l = let bold = withAttr ("border" <> "selected") in if isactive then bold (str l) else str l -- 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 body = Widget Greedy Greedy $ do c <- getContext let (_w,h) = (c^.availWidthL, c^.availHeightL) h' = h - 2 body' = vLimit (h') body debugmsg = "" -- " debug: "++show (_w,h') render $ hBorderWithLabel (withAttr "border" $ toplabel <+> str debugmsg) <=> body' <=> hBorderWithLabel (withAttr "border" 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 [("border", attr)]) ---- | Like brick's continue, but first run some action to modify brick's state. ---- This action does not affect the app state, but might eg adjust a widget's scroll position. --continueWith :: EventM n () -> ui -> EventM n (Next ui) --continueWith brickaction ui = brickaction >> continue ui ---- | Scroll a list's viewport so that the selected item is at the top ---- of the display area. --scrollToTop :: List Name e -> EventM Name () --scrollToTop list = do -- let vpname = list^.listNameL -- setTop (viewportScroll vpname) 0 -- | Scroll a list's viewport so that the selected item is centered in the -- middle of the display area. scrollSelectionToMiddle :: List Name e -> EventM Name () scrollSelectionToMiddle list = do let mselectedrow = list^.listSelectedL vpname = list^.listNameL mvp <- lookupViewport vpname case (mselectedrow, mvp) of (Just selectedrow, Just vp) -> do let itemheight = dbg4 "itemheight" $ list^.listItemHeightL vpheight = dbg4 "vpheight" $ vp^.vpSize._2 itemsperpage = dbg4 "itemsperpage" $ vpheight `div` itemheight toprow = dbg4 "toprow" $ max 0 (selectedrow - (itemsperpage `div` 2)) -- assuming ViewportScroll's row offset is measured in list items not screen rows setTop (viewportScroll vpname) toprow _ -> return () -- arrow keys vi keys emacs keys moveUpEvents = [EvKey KUp [] , EvKey (KChar 'k') [], EvKey (KChar 'p') [MCtrl]] moveDownEvents = [EvKey KDown [] , EvKey (KChar 'j') [], EvKey (KChar 'n') [MCtrl]] moveLeftEvents = [EvKey KLeft [] , EvKey (KChar 'h') [], EvKey (KChar 'b') [MCtrl]] moveRightEvents = [EvKey KRight [], EvKey (KChar 'l') [], EvKey (KChar 'f') [MCtrl]] normaliseMovementKeys ev | ev `elem` moveUpEvents = EvKey KUp [] | ev `elem` moveDownEvents = EvKey KDown [] | ev `elem` moveLeftEvents = EvKey KLeft [] | ev `elem` moveRightEvents = EvKey KRight [] | otherwise = ev hledger-ui-1.19.1/LICENSE0000644000000000000000000010451313700077722013034 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.19.1/Setup.hs0000644000000000000000000000005613700077722013460 0ustar0000000000000000import Distribution.Simple main = defaultMain hledger-ui-1.19.1/hledger-ui.cabal0000644000000000000000000000614613725533425015047 0ustar0000000000000000cabal-version: 1.12 -- This file has been generated from package.yaml by hpack version 0.33.0. -- -- see: https://github.com/sol/hpack -- -- hash: 9f306e545c5b87e192eac6bea6e0a46c9694e9844524b6ef500d2eb59e3d2fa0 name: hledger-ui version: 1.19.1 synopsis: Curses-style terminal interface for the hledger accounting system description: A simple curses-style terminal user interface for the hledger accounting system. It can be a more convenient way to browse your accounts than the CLI. This package currently does not support Microsoft Windows, except in WSL. . hledger is a robust, cross-platform set of tools for tracking money, time, or any other commodity, using double-entry accounting and a simple, editable file format, with command-line, terminal and web interfaces. It is a Haskell rewrite of Ledger, and one of the leading implementations of Plain Text Accounting. Read more at: 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==8.0.2, GHC==8.2.2, GHC==8.4.4, GHC==8.6.5, GHC==8.8.3, GHC==8.10.0.20200123 build-type: Simple extra-source-files: CHANGES.md README.md hledger-ui.1 hledger-ui.txt hledger-ui.info source-repository head type: git location: https://github.com/simonmichael/hledger flag threaded description: Build with support for multithreaded execution manual: False default: True executable hledger-ui main-is: hledger-ui.hs 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 Paths_hledger_ui 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.19.1" build-depends: ansi-terminal >=0.9 , async , base >=4.9 && <4.15 , base-compat-batteries >=0.10.1 && <0.12 , brick >=0.23 , cmdargs >=0.8 , containers , data-default , directory , extra >=1.6.3 , filepath , fsnotify >=0.2.1.2 && <0.4 , hledger >=1.19.1 && <1.20 , hledger-lib >=1.19.1 && <1.20 , megaparsec >=7.0.0 && <9.1 , microlens >=0.4 , microlens-platform >=0.2.3.1 , pretty-show >=1.6.4 , process >=1.2 , safe >=0.2 , split >=0.1 , text >=1.2 , text-zipper >=0.4 , time >=1.5 , transformers , unix , vector , vty >=5.15 if os(windows) buildable: False else buildable: True if flag(threaded) ghc-options: -threaded default-language: Haskell2010 hledger-ui-1.19.1/CHANGES.md0000644000000000000000000003516513725533425013433 0ustar0000000000000000User-visible changes in hledger-ui. See also the hledger changelog. # 1.19.1 2020-09-07 - Allow megaparsec 9 # 1.19 2020-09-01 - The --color/--colour=WHEN command line option, support for the NO_COLOR environment variable, and smarter autodetection of colour terminals have been added (#1296) - -t and -l command line flags have been added as short forms of --tree and --flat (#1286) - Flat (AKA list) mode is now the default - t now toggles tree mode, while T sets the "today" period (#1286) - register: multicommodity amounts containing more than two commodities are now elided - register: a transaction dated outside the report period now is not shown even if it has postings dated inside the report period. - ESC now restores exactly the app's state at startup, which includes clearing any report period limit (#1286) - DEL/BS no longer changes the tree/list mode - q now exits help before exiting the app (#1286) - The help dialog's layout is improved # 1.18.1 2020-06-21 - Fix regression in 'F' (#1255) (Dmitry Astapov) # 1.18 2020-06-07 - builds with hledger 1.18 # 1.17.1.1 2020-03-19 - update bounds after some belated hledger-* version bumps # 1.17.1 2020-03-19 - fix a regression, empty register of depth-limited account (fix #1208) - require newer Decimal, math-functions libs to ensure consistent rounding behaviour, even when built with old GHCs/snapshots. hledger uses banker's rounding (rounds to nearest even number, eg 0.5 displayed with zero decimal places is "0"). # 1.17 2020-03-01 - don't enable --auto by default - don't enable --forecast by default; drop the --future flag (#1193) Previously, periodic transactions occurring today were always shown, in both "present" and "future" modes. Now, generation of periodic transactions and display of future transactions (all kinds) are combined as "forecast mode", which can be enabled with --forecast and/or the F key. The --future flag is now a hidden alias for --forecast, and deprecated. # 1.16.2 2020-01-14 - add support for megaparsec 8 (#1175) # 1.16.1 2019-12-03 - use hledger 1.16.1, fixing GHC 8.0/8.2 build # 1.16 2019-12-01 - add support for GHC 8.8, base-compat 0.11 (#1090) - drop support for GHC 7.10 - the B and V keys toggle cost or value display (like the -B and -V command line flags) # 1.15 2019-09-01 - allow brick >=0.47 - use hledger 1.15 # 1.14.2 2019-03-20 - support brick 0.47+ as well, to get into stackage nightly. # 1.14.1 2019-03-20 - require brick <0.47 to fix build (#995) - use hledger 1.14.2 # 1.14 2019-03-01 - use hledger 1.14 # 1.13.1 (2019/02/02) - fix build issues with older brick/stack resolvers; require brick 0.23+ # 1.13 (2019/02/01) - on posix systems, control-z suspends the program - control-l now works everywhere and redraws more reliably - the top status info is clearer - use hledger 1.13 # 1.12.1 (2018/12/10) - avoid build issue with brick 0.44+ (#935) # 1.12 (2018/12/02) - fix "Any" build error with GHC < 8.4 - error screen: always show error position properly (#904) (Mykola Orliuk) - accounts screen: show correct balances when there's only periodic transactions - drop the --status-toggles flag - periodic transactions and transaction modifiers are always enabled. Rule-based transactions and postings are always generated (--forecast and --auto are always on). Experimental. - escape key resets to flat mode. Flat mode is the default at startup. Probably it should reset to tree mode if --tree was used at startup. - tree mode tweaks: add --tree/-T/-F flags, make flat mode the default,\ toggle tree mode with T, ensure a visible effect on register screen - hide future txns by default, add --future flag, toggle with F. You may have transactions dated later than today, perhaps piped from print --forecast or recorded in the journal, which you don't want to see except when forecasting. By default, we now hide future transactions, showing "today's balance". This can be toggled with the F key, which is easier than setting a date query. --present and --future flags have been added to set the initial mode. (Experimental. Interactions with date queries have not been explored.) - quick help tweaks; try to show most useful info first - reorganise help dialog, fit content into 80x25 again - styling tweaks; cyan/blue -> white/yellow - less noisy styling in horizontal borders (#838) - register screen: positive amounts: green -> black The green/red scheme helped distinguish the changes column from the black/red balance column, but the default green is hard to read on the pale background in some terminals. Also the changes column is non-bold now. - use hledger 1.12 # 1.11.1 (2018/10/06) - use hledger 1.11.1 # 1.11 (2018/9/30) - use hledger 1.11 # 1.10.1 (2018/7/3) - restore support for fsnotify 0.2.1.2, as well as 0.3.x (#833) - fix a vty version bound & possibly build failures with old vty (#494) # 1.10 (2018/6/30) - the effect of --value, --forecast, and --anon flags is now preserved on reload (#753) - edit-at-transaction-position is now also supported when $EDITOR is neovim - support/require fsnotify 0.3.0.1+ - use hledger-lib 1.10 # 1.9.1 (2018/4/30) - use hledger-lib 1.9.1 # 1.9 (2018/3/31) - support ghc 8.4, latest deps - when the system text encoding is UTF-8, ignore any UTF-8 BOM prefix found when reading files - -E/--empty toggles zeroes at startup (with opposite default to cli) # 1.5 (2017/12/31) - fix help -> view manual (on posix platforms) #623 - support -V/--value, --forecast, --auto - remove upper bounds on all but hledger* and base (experimental) # 1.4 (2017/9/30) - a @FILE argument reads flags & args from FILE, one per line - enable --pivot and --anon options, like hledger CLI (#474) (Jakub Zárybnický) - accept -NUM as a shortcut for --depth NUM - deps: allow ansi-terminal 0.7 - deps: drop oldtime flag, require time 1.5+ # 1.3.1 (2017/8/25) - allow megaparsec 6 (#594, Simon Michael, Hans-Peter Deifel) - allow megaparsec-6.1 (Hans-Peter Deifel) - allow vty 5.17 (Felix Yan) - allow brick 0.24 - restore upper bounds on hledger packages # 1.3 (2017/6/30) The register screen now shows transaction status marks. The "uncleared" status, and associated UI flags and keys, have been renamed to "unmarked" to remove ambiguity and confusion. This means that we have dropped the `--uncleared` flag, and our `-U` flag now matches only unmarked things and not pending ones. See the issue and linked mail list discussion for more background. (#564) The P key toggles pending mode, consistent with U (unmarked) and C (cleared). There is also a temporary --status-toggles flag for testing other toggle styles; see `hledger-ui -h`. (#564) There is now less "warping" of selection when lists change: - When the selected account disappears, eg when toggling zero accounts, the selection moves to the alphabetically preceding item, instead of the first one. - When the selected transaction disappears, eg when toggling status filters, the selection moves to the nearest transaction by date (and if several have the same date, by journal order), instead of the last one. In the accounts and register screens, you can now scroll down further so that the last item need not always be shown at the bottom of the screen. And we now try to show the selected item centered in the following situations: - after moving to the end with Page down/End - after toggling filters (status, real, historical..) - on pressing the control-l key (should force a screen redraw, also) - on entering the register screen from the accounts screen (there's a known problem with this: it doesn't work the first time). (Items near the top can't be centered, as we don't scroll higher than the top of the list.) Emacs movement keys are now supported, as well as VI keys. hjkl and CTRL-bfnp should work wherever unmodified arrow keys work. In the transaction screen, amounts are now better aligned, eg when there are posting status marks or virtual postings. Deps: allow brick 0.19 (#575, Felix Yan, Simon Michael) # 1.2 (2017/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.19.1/README.md0000644000000000000000000000052213722544246013305 0ustar0000000000000000# hledger-ui A simple curses-style text user interface for the hledger accounting system. It can be a more convenient way to browse your accounts than the CLI. This package currently does not support Microsoft Windows, except in WSL. See also: the [project README](https://hledger.org/README.html) and [home page](https://hledger.org). hledger-ui-1.19.1/hledger-ui.10000644000000000000000000004534713725533425014153 0ustar0000000000000000 .TH "hledger-ui" "1" "September 2020" "hledger-ui 1.18.99" "hledger User Manuals" .SH NAME .PP hledger-ui - terminal interface for the hledger accounting tool .SH SYNOPSIS .PP \f[C]hledger-ui [OPTIONS] [QUERYARGS]\f[R] .PD 0 .P .PD \f[C]hledger ui -- [OPTIONS] [QUERYARGS]\f[R] .SH DESCRIPTION .PP hledger is a reliable, cross-platform set of programs 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 terminal 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[R], or \f[C]$LEDGER_FILE\f[R], or \f[C]$HOME/.hledger.journal\f[R] (on windows, perhaps \f[C]C:/Users/USER/.hledger.journal\f[R]). For more about this see hledger(1), hledger_journal(5) etc. .PP Unlike hledger, hledger-ui hides all future-dated transactions by default. They can be revealed, along with any rule-generated periodic transactions, by pressing the F key (or starting with --forecast) to enable \[dq]forecast mode\[dq]. .SH OPTIONS .PP Note: if invoking hledger-ui as a hledger subcommand, write \f[C]--\f[R] before options as shown above. .PP Any QUERYARGS are interpreted as a hledger search query which filters the data. .TP \f[B]\f[CB]--watch\f[B]\f[R] watch for data and date changes and reload automatically .TP \f[B]\f[CB]--theme=default|terminal|greenterm\f[B]\f[R] use this custom display theme .TP \f[B]\f[CB]--register=ACCTREGEX\f[B]\f[R] start in the (first) matched account\[aq]s register screen .TP \f[B]\f[CB]--change\f[B]\f[R] show period balances (changes) at startup instead of historical balances .TP \f[B]\f[CB]-l --flat\f[B]\f[R] show accounts as a flat list (default) .TP \f[B]\f[CB]-t --tree\f[B]\f[R] show accounts as a tree .PP hledger input options: .TP \f[B]\f[CB]-f FILE --file=FILE\f[B]\f[R] use a different input file. For stdin, use - (default: \f[C]$LEDGER_FILE\f[R] or \f[C]$HOME/.hledger.journal\f[R]) .TP \f[B]\f[CB]--rules-file=RULESFILE\f[B]\f[R] Conversion rules file to use when reading CSV (default: FILE.rules) .TP \f[B]\f[CB]--separator=CHAR\f[B]\f[R] Field separator to expect when reading CSV (default: \[aq],\[aq]) .TP \f[B]\f[CB]--alias=OLD=NEW\f[B]\f[R] rename accounts named OLD to NEW .TP \f[B]\f[CB]--anon\f[B]\f[R] anonymize accounts and payees .TP \f[B]\f[CB]--pivot FIELDNAME\f[B]\f[R] use some other field or tag for the account name .TP \f[B]\f[CB]-I --ignore-assertions\f[B]\f[R] disable balance assertion checks (note: does not disable balance assignments) .PP hledger reporting options: .TP \f[B]\f[CB]-b --begin=DATE\f[B]\f[R] include postings/txns on or after this date .TP \f[B]\f[CB]-e --end=DATE\f[B]\f[R] include postings/txns before this date .TP \f[B]\f[CB]-D --daily\f[B]\f[R] multiperiod/multicolumn report by day .TP \f[B]\f[CB]-W --weekly\f[B]\f[R] multiperiod/multicolumn report by week .TP \f[B]\f[CB]-M --monthly\f[B]\f[R] multiperiod/multicolumn report by month .TP \f[B]\f[CB]-Q --quarterly\f[B]\f[R] multiperiod/multicolumn report by quarter .TP \f[B]\f[CB]-Y --yearly\f[B]\f[R] multiperiod/multicolumn report by year .TP \f[B]\f[CB]-p --period=PERIODEXP\f[B]\f[R] set start date, end date, and/or reporting interval all at once using period expressions syntax .TP \f[B]\f[CB]--date2\f[B]\f[R] match the secondary date instead (see command help for other effects) .TP \f[B]\f[CB]-U --unmarked\f[B]\f[R] include only unmarked postings/txns (can combine with -P or -C) .TP \f[B]\f[CB]-P --pending\f[B]\f[R] include only pending postings/txns .TP \f[B]\f[CB]-C --cleared\f[B]\f[R] include only cleared postings/txns .TP \f[B]\f[CB]-R --real\f[B]\f[R] include only non-virtual postings .TP \f[B]\f[CB]-NUM --depth=NUM\f[B]\f[R] hide/aggregate accounts or postings more than NUM levels deep .TP \f[B]\f[CB]-E --empty\f[B]\f[R] show items with zero amount, normally hidden (and vice-versa in hledger-ui/hledger-web) .TP \f[B]\f[CB]-B --cost\f[B]\f[R] convert amounts to their cost/selling amount at transaction time .TP \f[B]\f[CB]-V --market\f[B]\f[R] convert amounts to their market value in default valuation commodities .TP \f[B]\f[CB]-X --exchange=COMM\f[B]\f[R] convert amounts to their market value in commodity COMM .TP \f[B]\f[CB]--value\f[B]\f[R] convert amounts to cost or market value, more flexibly than -B/-V/-X .TP \f[B]\f[CB]--infer-value\f[B]\f[R] with -V/-X/--value, also infer market prices from transactions .TP \f[B]\f[CB]--auto\f[B]\f[R] apply automated posting rules to modify transactions. .TP \f[B]\f[CB]--forecast\f[B]\f[R] generate future transactions from periodic transaction rules, for the next 6 months or till report end date. In hledger-ui, also make ordinary future transactions visible. .TP \f[B]\f[CB]--color=WHEN (or --colour=WHEN)\f[B]\f[R] Should color-supporting commands use ANSI color codes in text output. \[aq]auto\[aq] (default): whenever stdout seems to be a color-supporting terminal. \[aq]always\[aq] or \[aq]yes\[aq]: always, useful eg when piping output into \[aq]less -R\[aq]. \[aq]never\[aq] or \[aq]no\[aq]: never. A NO_COLOR environment variable overrides this. .PP When a reporting option appears more than once in the command line, the last one takes precedence. .PP Some reporting options can also be written as query arguments. .PP hledger help options: .TP \f[B]\f[CB]-h --help\f[B]\f[R] show general usage (or after COMMAND, command usage) .TP \f[B]\f[CB]--version\f[B]\f[R] show version .TP \f[B]\f[CB]--debug[=N]\f[B]\f[R] show debug output (levels 1-9, default: 1) .PP a \[at]file argument will be expanded to the contents of file, which should contain one command line option/argument per line. (to prevent this, insert a \f[C]--\f[R] argument before.) .SH keys .PP \f[C]?\f[R] 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[R] again (or \f[C]escape\f[R], or \f[C]left\f[R], or \f[C]q\f[R]) to close it. the following keys work on most screens: .PP the cursor keys navigate: \f[C]right\f[R] (or \f[C]enter\f[R]) goes deeper, \f[C]left\f[R] returns to the previous screen, \f[C]up\f[R]/\f[C]down\f[R]/\f[C]page up\f[R]/\f[C]page down\f[R]/\f[C]home\f[R]/\f[C]end\f[R] move up and down through lists. Emacs-style (\f[C]ctrl-p\f[R]/\f[C]ctrl-n\f[R]/\f[C]ctrl-f\f[R]/\f[C]ctrl-b\f[R]) movement keys are also supported (but not vi-style keys, since hledger-1.19, sorry!). 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[R] steps downward and upward through these standard report period durations: year, quarter, month, week, day. then, \f[C]shift-left/right\f[R] moves to the previous/next period. \f[C]T\f[R] sets the report period to today. with the \f[C]--watch\f[R] option, when viewing a \[dq]current\[dq] 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[R] and a \f[C]date:\f[R] query. .PP \f[C]/\f[R] 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[R] to set it, or \f[C]escape\f[R]to cancel. there are also keys for quickly adjusting some common filters like account depth and transaction status (see below). \f[C]backspace\f[R] or \f[C]delete\f[R] removes all filters, showing all transactions. .PP as mentioned above, by default hledger-ui hides future transactions - both ordinary transactions recorded in the journal, and periodic transactions generated by rule. \f[C]f\f[R] toggles forecast mode, in which future/forecasted transactions are shown. \f[I](experimental)\f[R] .PP \f[C]escape\f[R] resets the UI state and jumps back to the top screen, restoring the app\[aq]s initial state at startup. Or, it cancels minibuffer data entry or the help dialog. .PP \f[C]ctrl-l\f[R] redraws the screen and centers the selection if possible (selections near the top won\[aq]t be centered, since we don\[aq]t scroll above the top). .PP \f[C]g\f[R] 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[R] toggles balance assertion checking. disabling balance assertions temporarily can be useful for troubleshooting. .PP \f[C]a\f[R] runs command-line hledger\[aq]s add command, and reloads the updated file. this allows some basic data entry. .PP \f[C]a\f[R] is like \f[C]a\f[R], but runs the hledger-iadd tool, which provides a terminal interface. this key will be available if \f[C]hledger-iadd\f[R] is installed in $path. .PP \f[C]e\f[R] runs $hledger_ui_editor, or $editor, or a default (\f[C]emacsclient -a \[dq]\[dq] -nw\f[R]) 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]b\f[R] toggles cost mode, showing amounts in their transaction price\[aq]s commodity (like toggling the \f[C]-b/--cost\f[R] flag). .PP \f[C]v\f[R] toggles value mode, showing amounts\[aq] current market value in their default valuation commodity (like toggling the \f[C]-v/--market\f[R] flag). note, \[dq]current market value\[dq] means the value on the report end date if specified, otherwise today. to see the value on another date, you can temporarily set that as the report end date. eg: to see a transaction as it was valued on july 30, go to the accounts or register screen, press \f[C]/\f[R], and add \f[C]date:-7/30\f[R] to the query. .PP at most one of cost or value mode can be active at once. .PP there\[aq]s not yet any visual reminder when cost or value mode is active; for now pressing \f[C]b\f[R] \f[C]b\f[R] \f[C]v\f[R] should reliably reset to normal mode. .PP with --watch active, if you save an edit to the journal file while viewing the transaction screen in cost or value mode, the \f[C]b\f[R]/\f[C]v\f[R] keys will stop working. to work around, press g to force a manual reload, or exit the transaction screen. .PP \f[C]q\f[R] 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 shown as a flat list by default; press \f[C]t\f[R] to toggle tree mode. In list mode, account balances are exclusive of subaccounts, except where subaccounts are hidden by a depth limit (see below). In tree mode, all account balances are inclusive of subaccounts. .PP To see less detail, press a number key, \f[C]1\f[R] to \f[C]9\f[R], to set a depth limit. Or use \f[C]-\f[R] to decrease and \f[C]+\f[R]/\f[C]=\f[R] to increase the depth limit. \f[C]0\f[R] shows even less detail, collapsing all accounts to a single total. To remove the depth limit, set it higher than the maximum account depth, or press \f[C]ESCAPE\f[R]. .PP \f[C]H\f[R] 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]U\f[R] toggles filtering by unmarked status, including or excluding unmarked postings in the balances. Similarly, \f[C]P\f[R] toggles pending postings, and \f[C]C\f[R] toggles cleared postings. (By default, balances include all postings; if you activate one or two status filters, only those postings are included; and if you activate all three, the filter is removed.) .PP \f[C]R\f[R] toggles real mode, in which virtual postings are ignored. .PP \f[C]Z\f[R] 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[R] or \f[C]enter\f[R] 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[R]. 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 Transactions affecting this account\[aq]s subaccounts will be included in the register if the accounts screen is in tree mode, or if it\[aq]s in list mode but this account has subaccounts which are not shown due to a depth limit. In other words, the register always shows the transactions contributing to the balance shown on the accounts screen. Tree mode/list mode can be toggled with \f[C]t\f[R] here also. .PP \f[C]U\f[R] toggles filtering by unmarked status, showing or hiding unmarked transactions. Similarly, \f[C]P\f[R] toggles pending transactions, and \f[C]C\f[R] toggles cleared transactions. (By default, transactions with all statuses are shown; if you activate one or two status filters, only those transactions are shown; and if you activate all three, the filter is removed.) .PP \f[C]R\f[R] toggles real mode, in which virtual postings are ignored. .PP \f[C]Z\f[R] 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[R] (or \f[C]enter\f[R]) 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[R] and \f[C]down\f[R] 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[R] The screen width to use. Default: the full terminal width. .PP \f[B]LEDGER_FILE\f[R] The journal file path when not specified with \f[C]-f\f[R]. Default: \f[C]\[ti]/.hledger.journal\f[R] (on windows, perhaps \f[C]C:/Users/USER/.hledger.journal\f[R]). .PP A typical value is \f[C]\[ti]/DIR/YYYY.journal\f[R], where DIR is a version-controlled finance directory and YYYY is the current year. Or \f[C]\[ti]/DIR/current.journal\f[R], where current.journal is a symbolic link to YYYY.journal. .PP On Mac computers, you can set this and other environment variables in a more thorough way that also affects applications started from the GUI (say, an Emacs dock icon). Eg on MacOS Catalina I have a \f[C]\[ti]/.MacOSX/environment.plist\f[R] file containing .IP .nf \f[C] { \[dq]LEDGER_FILE\[dq] : \[dq]\[ti]/finance/current.journal\[dq] } \f[R] .fi .PP To see the effect you may need to \f[C]killall Dock\f[R], or reboot. .SH FILES .PP Reads data from one or more files in hledger journal, timeclock, timedot, or CSV format specified with \f[C]-f\f[R], or \f[C]$LEDGER_FILE\f[R], or \f[C]$HOME/.hledger.journal\f[R] (on windows, perhaps \f[C]C:/Users/USER/.hledger.journal\f[R]). .SH BUGS .PP The need to precede options with \f[C]--\f[R] when invoked from hledger is awkward. .PP \f[C]-f-\f[R] doesn\[aq]t work (hledger-ui can\[aq]t read from stdin). .PP \f[C]-V\f[R] affects only the accounts screen. .PP When you press \f[C]g\f[R], 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[R] 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. .PP Also, if you are viewing files mounted from another machine, \f[C]--watch\f[R] requires that both machine clocks are roughly in step. .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-2019 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.19.1/hledger-ui.txt0000644000000000000000000004664713725533425014636 0ustar0000000000000000 hledger-ui(1) hledger User Manuals hledger-ui(1) NAME hledger-ui - terminal interface for the hledger accounting tool SYNOPSIS hledger-ui [OPTIONS] [QUERYARGS] hledger ui -- [OPTIONS] [QUERYARGS] DESCRIPTION hledger is a reliable, cross-platform set of programs 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 terminal 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. Unlike hledger, hledger-ui hides all future-dated transactions by de- fault. They can be revealed, along with any rule-generated periodic transactions, by pressing the F key (or starting with --forecast) to enable "forecast mode". 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 -l --flat show accounts as a flat list (default) -t --tree show accounts as a tree 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) --separator=CHAR Field separator to expect when reading CSV (default: ',') --alias=OLD=NEW rename accounts named OLD to NEW --anon anonymize accounts and payees --pivot FIELDNAME use some other field or tag for the account name -I --ignore-assertions disable balance assertion checks (note: does not disable balance assignments) 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 using period expressions syntax --date2 match the secondary date instead (see command help for other ef- fects) -U --unmarked include only unmarked postings/txns (can combine with -P or -C) -P --pending include only pending postings/txns -C --cleared include only cleared postings/txns -R --real include only non-virtual postings -NUM --depth=NUM hide/aggregate accounts or postings more than NUM levels deep -E --empty show items with zero amount, normally hidden (and vice-versa in hledger-ui/hledger-web) -B --cost convert amounts to their cost/selling amount at transaction time -V --market convert amounts to their market value in default valuation com- modities -X --exchange=COMM convert amounts to their market value in commodity COMM --value convert amounts to cost or market value, more flexibly than -B/-V/-X --infer-value with -V/-X/--value, also infer market prices from transactions --auto apply automated posting rules to modify transactions. --forecast generate future transactions from periodic transaction rules, for the next 6 months or till report end date. In hledger-ui, also make ordinary future transactions visible. --color=WHEN (or --colour=WHEN) Should color-supporting commands use ANSI color codes in text output. 'auto' (default): whenever stdout seems to be a color- supporting terminal. 'always' or 'yes': always, useful eg when piping output into 'less -R'. 'never' or 'no': never. A NO_COLOR environment variable overrides this. When a reporting option appears more than once in the command line, the last one takes precedence. Some reporting options can also be written as query arguments. hledger help options: -h --help show general usage (or after COMMAND, command usage) --version show version --debug[=N] show debug output (levels 1-9, default: 1) a @file argument will be expanded to the contents of file, which should contain one command line option/argument per line. (to prevent this, insert a -- argument before.) 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, or q) 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. Emacs-style (ctrl-p/ctrl-n/ctrl-f/ctrl-b) movement keys are also supported (but not vi-style keys, since hledger-1.19, sorry!). 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 escapeto cancel. there are also keys for quickly adjusting some common filters like account depth and transaction status (see below). backspace or delete removes all filters, showing all transactions. as mentioned above, by default hledger-ui hides future transactions - both ordinary transactions recorded in the journal, and periodic trans- actions generated by rule. f toggles forecast mode, in which fu- ture/forecasted transactions are shown. (experimental) escape resets the UI state and jumps back to the top screen, restoring the app's initial state at startup. Or, it cancels minibuffer data en- try or the help dialog. ctrl-l redraws the screen and centers the selection if possible (selec- tions near the top won't be centered, since we don't scroll above the top). 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. a is like a, but runs the hledger-iadd tool, which provides a terminal interface. this key will be available if hledger-iadd is installed in $path. 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 possi- ble) when invoked from the error screen. b toggles cost mode, showing amounts in their transaction price's com- modity (like toggling the -b/--cost flag). v toggles value mode, showing amounts' current market value in their default valuation commodity (like toggling the -v/--market flag). note, "current market value" means the value on the report end date if specified, otherwise today. to see the value on another date, you can temporarily set that as the report end date. eg: to see a transaction as it was valued on july 30, go to the accounts or register screen, press /, and add date:-7/30 to the query. at most one of cost or value mode can be active at once. there's not yet any visual reminder when cost or value mode is active; for now pressing b b v should reliably reset to normal mode. with --watch active, if you save an edit to the journal file while viewing the transaction screen in cost or value mode, the b/v keys will stop working. to work around, press g to force a manual reload, or exit the transaction 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 shown as a flat list by default; press t to toggle tree mode. In list mode, account balances are exclusive of subac- counts, except where subaccounts are hidden by a depth limit (see be- low). In tree mode, all account balances are inclusive of subaccounts. To see less detail, press a number key, 1 to 9, to set a depth limit. Or use - to decrease and +/= to increase the depth limit. 0 shows even less detail, collapsing all accounts to a single total. To remove the depth limit, set it higher than the maximum account depth, or press ES- CAPE. 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 be- fore 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. U toggles filtering by unmarked status, including or excluding unmarked postings in the balances. Similarly, P toggles pending postings, and C toggles cleared postings. (By default, balances include all postings; if you activate one or two status filters, only those postings are in- cluded; and if you activate all three, the filter is removed.) 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. Transactions affecting this account's subaccounts will be included in the register if the accounts screen is in tree mode, or if it's in list mode but this account has subaccounts which are not shown due to a depth limit. In other words, the register always shows the transac- tions contributing to the balance shown on the accounts screen. Tree mode/list mode can be toggled with t here also. U toggles filtering by unmarked status, showing or hiding unmarked transactions. Similarly, P toggles pending transactions, and C toggles cleared transactions. (By default, transactions with all statuses are shown; if you activate one or two status filters, only those transac- tions are shown; and if you activate all three, the filter is removed.) 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, de- scription, 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 de- pending on which account register you came from (remember most transac- tions 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). A typical value is ~/DIR/YYYY.journal, where DIR is a version-con- trolled finance directory and YYYY is the current year. Or ~/DIR/cur- rent.journal, where current.journal is a symbolic link to YYYY.journal. On Mac computers, you can set this and other environment variables in a more thorough way that also affects applications started from the GUI (say, an Emacs dock icon). Eg on MacOS Catalina I have a ~/.MacOSX/en- vironment.plist file containing { "LEDGER_FILE" : "~/finance/current.journal" } To see the effect you may need to killall Dock, or reboot. 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. Also, if you are viewing files mounted from another machine, --watch requires that both machine clocks are roughly in step. 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-2019 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.18.99 September 2020 hledger-ui(1) hledger-ui-1.19.1/hledger-ui.info0000644000000000000000000004463713725533425014747 0ustar0000000000000000This is hledger-ui.info, produced by makeinfo version 6.7 from stdin.  File: hledger-ui.info, Node: Top, Next: OPTIONS, Up: (dir) hledger-ui(1) hledger-ui 1.18.99 ******************************** hledger-ui - terminal interface for the hledger accounting tool 'hledger-ui [OPTIONS] [QUERYARGS]' 'hledger ui -- [OPTIONS] [QUERYARGS]' hledger is a reliable, cross-platform set of programs 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 terminal 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. Unlike hledger, hledger-ui hides all future-dated transactions by default. They can be revealed, along with any rule-generated periodic transactions, by pressing the F key (or starting with -forecast) to enable "forecast mode". * Menu: * OPTIONS:: * keys:: * screens:: * ENVIRONMENT:: * FILES:: * BUGS::  File: hledger-ui.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 '-l --flat' show accounts as a flat list (default) '-t --tree' show accounts as a tree 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) '--separator=CHAR' Field separator to expect when reading CSV (default: ',') '--alias=OLD=NEW' rename accounts named OLD to NEW '--anon' anonymize accounts and payees '--pivot FIELDNAME' use some other field or tag for the account name '-I --ignore-assertions' disable balance assertion checks (note: does not disable balance assignments) 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 using period expressions syntax '--date2' match the secondary date instead (see command help for other effects) '-U --unmarked' include only unmarked postings/txns (can combine with -P or -C) '-P --pending' include only pending postings/txns '-C --cleared' include only cleared postings/txns '-R --real' include only non-virtual postings '-NUM --depth=NUM' hide/aggregate accounts or postings more than NUM levels deep '-E --empty' show items with zero amount, normally hidden (and vice-versa in hledger-ui/hledger-web) '-B --cost' convert amounts to their cost/selling amount at transaction time '-V --market' convert amounts to their market value in default valuation commodities '-X --exchange=COMM' convert amounts to their market value in commodity COMM '--value' convert amounts to cost or market value, more flexibly than -B/-V/-X '--infer-value' with -V/-X/-value, also infer market prices from transactions '--auto' apply automated posting rules to modify transactions. '--forecast' generate future transactions from periodic transaction rules, for the next 6 months or till report end date. In hledger-ui, also make ordinary future transactions visible. '--color=WHEN (or --colour=WHEN)' Should color-supporting commands use ANSI color codes in text output. 'auto' (default): whenever stdout seems to be a color-supporting terminal. 'always' or 'yes': always, useful eg when piping output into 'less -R'. 'never' or 'no': never. A NO_COLOR environment variable overrides this. When a reporting option appears more than once in the command line, the last one takes precedence. Some reporting options can also be written as query arguments. hledger help options: '-h --help' show general usage (or after COMMAND, command usage) '--version' show version '--debug[=N]' show debug output (levels 1-9, default: 1) a @file argument will be expanded to the contents of file, which should contain one command line option/argument per line. (to prevent this, insert a '--' argument before.)  File: hledger-ui.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', or 'q') 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. Emacs-style ('ctrl-p'/'ctrl-n'/'ctrl-f'/'ctrl-b') movement keys are also supported (but not vi-style keys, since hledger-1.19, sorry!). 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 transaction status (see below). 'backspace' or 'delete' removes all filters, showing all transactions. as mentioned above, by default hledger-ui hides future transactions - both ordinary transactions recorded in the journal, and periodic transactions generated by rule. 'f' toggles forecast mode, in which future/forecasted transactions are shown. _(experimental)_ 'escape' resets the UI state and jumps back to the top screen, restoring the app's initial state at startup. Or, it cancels minibuffer data entry or the help dialog. 'ctrl-l' redraws the screen and centers the selection if possible (selections near the top won't be centered, since we don't scroll above the top). '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. 'a' is like 'a', but runs the hledger-iadd tool, which provides a terminal interface. this key will be available if 'hledger-iadd' is installed in $path. '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. 'b' toggles cost mode, showing amounts in their transaction price's commodity (like toggling the '-b/--cost' flag). 'v' toggles value mode, showing amounts' current market value in their default valuation commodity (like toggling the '-v/--market' flag). note, "current market value" means the value on the report end date if specified, otherwise today. to see the value on another date, you can temporarily set that as the report end date. eg: to see a transaction as it was valued on july 30, go to the accounts or register screen, press '/', and add 'date:-7/30' to the query. at most one of cost or value mode can be active at once. there's not yet any visual reminder when cost or value mode is active; for now pressing 'b' 'b' 'v' should reliably reset to normal mode. with -watch active, if you save an edit to the journal file while viewing the transaction screen in cost or value mode, the 'b'/'v' keys will stop working. to work around, press g to force a manual reload, or exit the transaction screen. 'q' quits the application. additional screen-specific keys are described below.  File: hledger-ui.info, Node: screens, Next: ENVIRONMENT, Prev: keys, Up: Top 3 screens ********* * Menu: * accounts screen:: * Register screen:: * Transaction screen:: * Error screen::  File: hledger-ui.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 shown as a flat list by default; press 't' to toggle tree mode. In list mode, account balances are exclusive of subaccounts, except where subaccounts are hidden by a depth limit (see below). In tree mode, all account balances are inclusive of subaccounts. To see less detail, press a number key, '1' to '9', to set a depth limit. Or use '-' to decrease and '+'/'=' to increase the depth limit. '0' shows even less detail, collapsing all accounts to a single total. To remove the depth limit, set it higher than the maximum account depth, or press 'ESCAPE'. '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. 'U' toggles filtering by unmarked status, including or excluding unmarked postings in the balances. Similarly, 'P' toggles pending postings, and 'C' toggles cleared postings. (By default, balances include all postings; if you activate one or two status filters, only those postings are included; and if you activate all three, the filter is removed.) '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.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. Transactions affecting this account's subaccounts will be included in the register if the accounts screen is in tree mode, or if it's in list mode but this account has subaccounts which are not shown due to a depth limit. In other words, the register always shows the transactions contributing to the balance shown on the accounts screen. Tree mode/list mode can be toggled with 't' here also. 'U' toggles filtering by unmarked status, showing or hiding unmarked transactions. Similarly, 'P' toggles pending transactions, and 'C' toggles cleared transactions. (By default, transactions with all statuses are shown; if you activate one or two status filters, only those transactions are shown; and if you activate all three, the filter is removed.) '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.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.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.)  File: hledger-ui.info, Node: ENVIRONMENT, Next: FILES, Prev: screens, Up: Top 4 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.journal'). A typical value is '~/DIR/YYYY.journal', where DIR is a version-controlled finance directory and YYYY is the current year. Or '~/DIR/current.journal', where current.journal is a symbolic link to YYYY.journal. On Mac computers, you can set this and other environment variables in a more thorough way that also affects applications started from the GUI (say, an Emacs dock icon). Eg on MacOS Catalina I have a '~/.MacOSX/environment.plist' file containing { "LEDGER_FILE" : "~/finance/current.journal" } To see the effect you may need to 'killall Dock', or reboot.  File: hledger-ui.info, Node: FILES, Next: BUGS, Prev: ENVIRONMENT, Up: Top 5 FILES ******* 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').  File: hledger-ui.info, Node: BUGS, Prev: FILES, Up: Top 6 BUGS ****** The need to precede options with '--' when invoked from hledger is awkward. '-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. 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. Also, if you are viewing files mounted from another machine, '--watch' requires that both machine clocks are roughly in step.  Tag Table: Node: Top71 Node: OPTIONS1476 Ref: #options1573 Node: keys5545 Ref: #keys5640 Node: screens9972 Ref: #screens10077 Node: accounts screen10167 Ref: #accounts-screen10295 Node: Register screen12510 Ref: #register-screen12665 Node: Transaction screen14662 Ref: #transaction-screen14820 Node: Error screen15690 Ref: #error-screen15812 Node: ENVIRONMENT16056 Ref: #environment16170 Node: FILES16977 Ref: #files17076 Node: BUGS17289 Ref: #bugs17366  End Tag Table  Local Variables: coding: utf-8 End: