hledger-ui-1.14.2/Hledger/0000755000000000000000000000000013420632425013365 5ustar0000000000000000hledger-ui-1.14.2/Hledger/UI/0000755000000000000000000000000013444556753013721 5ustar0000000000000000hledger-ui-1.14.2/hledger-ui.hs0000644000000000000000000000013313302271455014372 0ustar0000000000000000#!/usr/bin/env runhaskell module Main (module Hledger.UI) where import Hledger.UI (main) hledger-ui-1.14.2/Hledger/UI.hs0000644000000000000000000000047313420632425014242 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.14.2/Hledger/UI/AccountsScreen.hs0000644000000000000000000004556713433431637017204 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} -- Add a date:-tomorrow to the query to exclude future txns, by default. -- XXX this necessitates special handling in multiBalanceReport, at least pfq | presentorfuture_ uopts == PFFuture = Any | otherwise = Date $ DateSpan Nothing (Just $ addDays 1 d) q = And [queryFromOpts d ropts, pfq] -- run the report (items,_total) = report ropts' q j where -- XXX in historical mode, --forecast throws off the starting balances report | balancetype_ ropts == HistoricalBalance = balanceReportFromMultiBalanceReport | otherwise = balanceReport -- still using the old balanceReport for change reports as it -- does not include every account from before the report period -- 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 amts -- like showMixedAmountOneLineWithoutPrice } where Mixed amts = normaliseMixedAmountSquashPricesForDisplay $ stripPrices bal stripPrices (Mixed as) = Mixed $ map stripprice as where stripprice a = a{aprice=NoPrice} displayitems = map displayitem items -- 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" 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") ,("-+", str "depth") ,("T", renderToggle (tree_ ropts) "flat" "tree") ,("H", renderToggle (not ishistorical) "end-bals" "changes") ,("F", renderToggle (presentorfuture_ uopts == PFFuture) "present" "future") --,("/", "filter") --,("DEL", "unfilter") --,("ESC", "cancel/top") ,("a", str "add") -- ,("g", "reload") ,("q", str "quit") ] asDraw _ = error "draw function called with wrong screen type, should not happen" asDrawItem :: (Int,Int) -> Bool -> AccountsScreenItem -> Widget Name asDrawItem (acctwidth, balwidth) selected AccountsScreenItem{..} = Widget Greedy Fixed $ do -- c <- getContext -- let showitem = intercalate "\n" . balanceReportItemAsText defreportopts fmt render $ addamts asItemRenderedAmounts $ str (T.unpack $ fitText (Just acctwidth) (Just acctwidth) True True $ T.replicate (asItemIndentLevel) " " <> asItemDisplayAccountName) <+> str " " <+> str (balspace asItemRenderedAmounts) where balspace as = replicate n ' ' where n = max 0 (balwidth - (sum (map strWidth as) + 2 * (length as - 1))) addamts :: [String] -> Widget Name -> Widget Name addamts [] w = w addamts [a] w = (<+> renderamt a) w -- foldl' :: (b -> a -> b) -> b -> t a -> b -- foldl' (Widget -> String -> Widget) -> Widget -> [String] -> Widget addamts (a:as) w = foldl' addamt (addamts [a] w) as addamt :: Widget Name -> String -> Widget Name addamt w a = ((<+> renderamt a) . (<+> str ", ")) w renderamt :: String -> Widget Name renderamt a | '-' `elem` a = withAttr (sel $ "list" <> "balance" <> "negative") $ str a | otherwise = withAttr (sel $ "list" <> "balance" <> "positive") $ str a sel | selected = (<> "selected") | otherwise = id asHandle :: UIState -> BrickEvent Name AppEvent -> EventM Name (Next UIState) asHandle ui0@UIState{ aScreen=scr@AccountsScreen{..} ,aopts=UIOpts{cliopts_=copts} ,ajournal=j ,aMode=mode } ev = do d <- liftIO getCurrentDay 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 endPos (journalFilePath j)) >> uiReloadJournalIfChanged copts d j ui VtyEvent (EvKey (KChar '0') []) -> continue $ regenerateScreens j d $ setDepth (Just 0) ui VtyEvent (EvKey (KChar '1') []) -> continue $ regenerateScreens j d $ setDepth (Just 1) ui VtyEvent (EvKey (KChar '2') []) -> continue $ regenerateScreens j d $ setDepth (Just 2) ui VtyEvent (EvKey (KChar '3') []) -> continue $ regenerateScreens j d $ setDepth (Just 3) ui VtyEvent (EvKey (KChar '4') []) -> continue $ regenerateScreens j d $ setDepth (Just 4) ui VtyEvent (EvKey (KChar '5') []) -> continue $ regenerateScreens j d $ setDepth (Just 5) ui VtyEvent (EvKey (KChar '6') []) -> continue $ regenerateScreens j d $ setDepth (Just 6) ui VtyEvent (EvKey (KChar '7') []) -> continue $ regenerateScreens j d $ setDepth (Just 7) ui VtyEvent (EvKey (KChar '8') []) -> continue $ regenerateScreens j d $ setDepth (Just 8) ui VtyEvent (EvKey (KChar '9') []) -> continue $ regenerateScreens j d $ setDepth (Just 9) ui VtyEvent (EvKey (KChar '-') []) -> continue $ regenerateScreens j d $ decDepth ui VtyEvent (EvKey (KChar '_') []) -> continue $ regenerateScreens j d $ decDepth ui VtyEvent (EvKey (KChar c) []) | c `elem` ['+','='] -> continue $ regenerateScreens j d $ incDepth ui VtyEvent (EvKey (KChar 't') []) -> continue $ regenerateScreens j d $ setReportPeriod (DayPeriod d) ui -- 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') []) -> asCenterAndContinue $ regenerateScreens j d $ toggleFuture 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" 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.14.2/Hledger/UI/Editor.hs0000644000000000000000000000720113420632425015464 0ustar0000000000000000{- | Editor integration. -} -- {-# LANGUAGE OverloadedStrings #-} module Hledger.UI.Editor where import Control.Applicative ((<|>)) import Data.List import Safe import System.Environment import System.Exit import System.FilePath import System.Process import Hledger -- | Editors we know how to create more specific command lines for. data EditorType = Emacs | EmacsClient | Vi | Other -- | A position we can move to in a text editor: a line and optional column number. -- 1 (or 0) means the first and -1 means the last (and -2 means the second last, etc. -- though this may not be well supported.) type TextPosition = (Int, Maybe Int) endPos :: Maybe TextPosition endPos = Just (-1,Nothing) -- | Run the hledger-iadd executable (an alternative to the built-in add command), -- or raise an error. runIadd :: FilePath -> IO ExitCode runIadd f = runCommand ("hledger-iadd -f " ++ f) >>= waitForProcess -- | Try running the user's preferred text editor, or a default edit command, -- on the main journal file, blocking until it exits, and returning the exit code; -- or raise an error. runEditor :: Maybe TextPosition -> FilePath -> IO ExitCode runEditor mpos f = editorOpenPositionCommand mpos f >>= runCommand >>= waitForProcess -- Get the basic shell command to start the user's preferred text editor. -- This is the value of environment variable $HLEDGER_UI_EDITOR, or $EDITOR, or -- a default (emacsclient -a '' -nw, start/connect to an emacs daemon in terminal mode). editorCommand :: IO String editorCommand = do hledger_ui_editor_env <- lookupEnv "HLEDGER_UI_EDITOR" editor_env <- lookupEnv "EDITOR" let Just cmd = hledger_ui_editor_env <|> editor_env <|> Just "emacsclient -a '' -nw" return cmd -- | Get a shell command to start the user's preferred text editor, or a default, -- and optionally jump to a given position in the file. This will be the basic -- editor command, with the appropriate options added, if we know how. -- Currently we know how to do this for emacs and vi. -- Some examples: -- $EDITOR=notepad -> "notepad FILE" -- $EDITOR=vi -> "vi +LINE FILE" -- $EDITOR=vi, line -1 -> "vi + FILE" -- $EDITOR=emacs -> "emacs +LINE:COL FILE" -- $EDITOR=emacs, line -1 -> "emacs FILE -f end-of-buffer" -- $EDITOR not set -> "emacs -nw FILE -f end-of-buffer" -- editorOpenPositionCommand :: Maybe TextPosition -> FilePath -> IO String editorOpenPositionCommand mpos f = do cmd <- editorCommand let f' = singleQuoteIfNeeded f return $ case (identifyEditor cmd, mpos) of (EmacsClient, Just (l,mc)) | l >= 0 -> cmd ++ " " ++ emacsposopt l mc ++ " " ++ f' (EmacsClient, Just (l,mc)) | l < 0 -> cmd ++ " " ++ emacsposopt 999999999 mc ++ " " ++ f' (Emacs, Just (l,mc)) | l >= 0 -> cmd ++ " " ++ emacsposopt l mc ++ " " ++ f' (Emacs, Just (l,_)) | l < 0 -> cmd ++ " " ++ f' ++ " -f end-of-buffer" (Vi, Just (l,_)) -> cmd ++ " " ++ viposopt l ++ " " ++ f' _ -> cmd ++ " " ++ f' where emacsposopt l mc = "+" ++ show l ++ maybe "" ((":"++).show) mc viposopt l = "+" ++ if l >= 0 then show l else "" -- Identify which text editor is used in the basic editor command, if possible. identifyEditor :: String -> EditorType identifyEditor cmd | "emacsclient" `isPrefixOf` exe = EmacsClient | "emacs" `isPrefixOf` exe = Emacs | exe `elem` ["vi","nvim","vim","ex","view","gvim","gview","evim","eview","rvim","rview","rgvim","rgview"] = Vi | otherwise = Other where exe = lowercase $ takeFileName $ headDef "" $ words' cmd hledger-ui-1.14.2/Hledger/UI/ErrorScreen.hs0000644000000000000000000001624113433431637016501 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" 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" 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 _ -> (endPos, journalFilePath j) e | e `elem` [VtyEvent (EvKey (KChar 'g') []), AppEvent FileChange] -> liftIO (uiReloadJournal copts d (popScreen ui)) >>= continue . uiCheckBalanceAssertions d -- (ej, _) <- liftIO $ journalReloadIfChanged copts d j -- case ej of -- Left err -> continue ui{aScreen=s{esError=err}} -- show latest parse error -- Right j' -> continue $ regenerateScreens j' d $ popScreen ui -- return to previous screen, and reload it VtyEvent (EvKey (KChar 'I') []) -> continue $ uiCheckBalanceAssertions d (popScreen $ toggleIgnoreBalanceAssertions ui) 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" -- | 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.14.2/Hledger/UI/Main.hs0000644000000000000000000002113513444556753015143 0ustar0000000000000000{-| hledger-ui - a hledger add-on providing a curses-style interface. Copyright (c) 2007-2015 Simon Michael Released under GPL version 3 or later. -} {-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE MultiParamTypeClasses #-} module Hledger.UI.Main where -- import Control.Applicative -- import Lens.Micro.Platform ((^.)) import Control.Concurrent (threadDelay) import Control.Concurrent.Async import Control.Monad -- import Control.Monad.IO.Class (liftIO) #if !MIN_VERSION_vty(5,15,0) import Data.Default (def) #endif -- import Data.Monoid -- import Data.List import Data.Maybe -- import Data.Text (Text) import qualified Data.Text as T -- import Data.Time.Calendar import Graphics.Vty (mkVty) import Safe import System.Exit import System.Directory import System.FilePath import System.FSNotify import Brick #if MIN_VERSION_brick(0,16,0) import qualified Brick.BChan as BC #else import Control.Concurrent.Chan (newChan, writeChan) #endif import Hledger import Hledger.Cli hiding (progname,prognameandversion) import Hledger.UI.UIOptions import Hledger.UI.UITypes import Hledger.UI.UIState (toggleHistorical) import Hledger.UI.Theme import Hledger.UI.AccountsScreen import Hledger.UI.RegisterScreen ---------------------------------------------------------------------- #if MIN_VERSION_brick(0,16,0) newChan :: IO (BC.BChan a) newChan = BC.newBChan 10 writeChan :: BC.BChan a -> a -> IO () writeChan = BC.writeBChan #endif main :: IO () main = do opts <- getHledgerUIOpts let copts = cliopts_ opts copts' = copts { inputopts_ = (inputopts_ copts) { auto_ = True } , reportopts_ = (reportopts_ copts) { forecast_ = True } } -- when (debug_ $ cliopts_ opts) $ printf "%s\n" prognameandversion >> printf "opts: %s\n" (show opts) run $ opts { cliopts_ = copts' } where run opts | "help" `inRawOpts` (rawopts_ $ cliopts_ opts) = putStr (showModeUsage uimode) >> exitSuccess | "version" `inRawOpts` (rawopts_ $ cliopts_ opts) = putStrLn prognameandversion >> exitSuccess | "binary-filename" `inRawOpts` (rawopts_ $ cliopts_ opts) = putStrLn (binaryfilename progname) | otherwise = withJournalDo (cliopts_ opts) (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_ =depthfromoptsandargs, period_=periodfromoptsandargs, query_ =unwords -- as in ReportOptions, with same limitations [v | (k,v) <- rawopts_ copts, k=="args", not $ any (`isPrefixOf` v) ["depth","date"]], -- always disable boring account name eliding, unlike the CLI, for a more regular tree no_elide_=True, -- 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 depthfromoptsandargs = case queryDepth q of 99999 -> Nothing d -> Just d datespanfromargs = queryDateSpan (date2_ ropts) $ fst $ parseQuery d (T.pack $ query_ ropts) periodfromoptsandargs = dateSpanAsPeriod $ spansIntersect [periodAsDateSpan $ period_ ropts, datespanfromargs] -- XXX move this stuff into Options, UIOpts theme = maybe defaultTheme (fromMaybe defaultTheme . getTheme) $ maybestringopt "theme" $ rawopts_ copts mregister = maybestringopt "register" $ rawopts_ copts (scr, prevscrs) = case mregister of Nothing -> (accountsScreen, []) -- with --register, start on the register screen, and also put -- the accounts screen on the prev screens stack so you can exit -- to that as usual. Just apat -> (rsSetAccount acct False registerScreen, [ascr']) where acct = headDef (error' $ "--register "++apat++" did not match any account") $ filter (regexMatches apat . T.unpack) $ journalAccountNames j -- Initialising the accounts screen is awkward, requiring -- another temporary UIState value.. ascr' = aScreen $ asInit d True UIState{ aopts=uopts' ,ajournal=j ,aScreen=asSetSelectedAccount acct accountsScreen ,aPrevScreens=[] ,aMode=Normal } ui = (sInit scr) d True $ (if change_ uopts' then toggleHistorical else id) -- XXX UIState{ aopts=uopts' ,ajournal=j ,aScreen=scr ,aPrevScreens=prevscrs ,aMode=Normal } brickapp :: App UIState AppEvent Name brickapp = App { appStartEvent = return , appAttrMap = const theme , appChooseCursor = showFirstCursor , appHandleEvent = \ui ev -> sHandle (aScreen ui) ui ev , appDraw = \ui -> sDraw (aScreen ui) ui } -- print (length (show ui)) >> exitSuccess -- show any debug output to this point & quit if not (watch_ uopts') then void $ defaultMain brickapp ui else do -- a channel for sending misc. events to the app eventChan <- newChan -- start a background thread reporting changes in the current date -- use async for proper child termination in GHCI let watchDate old = do threadDelay 1000000 -- 1 s new <- getCurrentDay when (new /= old) $ do let dc = DateChange old new -- dbg1IO "datechange" dc -- XXX don't uncomment until dbg*IO fixed to use traceIO, GHC may block/end thread -- traceIO $ show dc writeChan eventChan dc watchDate new withAsync (getCurrentDay >>= watchDate) $ \_ -> -- 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 = nub $ sort $ map takeDirectory files dbg1IO "files" files dbg1IO "directories to watch" directories forM_ directories $ \d -> watchDir mgr d -- predicate: ignore changes not involving our files (\fev -> case fev of #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 #if MIN_VERSION_vty(5,15,0) let mkvty = mkVty mempty #else let mkvty = mkVty def #endif #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.14.2/Hledger/UI/RegisterScreen.hs0000644000000000000000000004621013433431637017173 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 } pfq | presentorfuture_ uopts == PFFuture = Any | otherwise = Date $ DateSpan Nothing (Just $ addDays 1 d) q = And [queryFromOpts d ropts', pfq] -- reportq = filterQuery (not . queryIsDepth) q (_label,items) = accountTransactionsReport ropts' j q thisacctq items' = (if empty_ ropts' then id else filter (not . isZeroMixedAmount . fifth6)) $ -- without --empty, exclude no-change txns reverse -- most recent last items -- generate pre-rendered list items. This helps calculate column widths. displayitems = map displayitem items' where displayitem (t, _, _issplit, otheracctsstr, change, bal) = RegisterScreenItem{rsItemDate = showDate $ transactionRegisterDate q thisacctq t ,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 = showMixedAmountOneLineWithoutPrice change ,rsItemBalanceAmount = showMixedAmountOneLineWithoutPrice 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" 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") ,("T", renderToggle (tree_ ropts) "flat(-subs)" "tree(+subs)") -- rsForceInclusive may override, but use tree_ to ensure a visible toggle effect ,("H", renderToggle (not ishistorical) "historical" "period") ,("F", renderToggle (presentorfuture_ uopts == PFFuture) "present" "future") -- ,("a", "add") -- ,("g", "reload") -- ,("q", "quit") ] rsDraw _ = error "draw function called with wrong screen type, should not happen" rsDrawItem :: (Int,Int,Int,Int,Int) -> Bool -> RegisterScreenItem -> Widget Name rsDrawItem (datewidth,descwidth,acctswidth,changewidth,balwidth) selected RegisterScreenItem{..} = Widget Greedy Fixed $ do render $ str (fitString (Just datewidth) (Just datewidth) True True rsItemDate) <+> str " " <+> str (fitString (Just 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 -> (endPos, journalFilePath j) Just (_, RegisterScreenItem{ rsItemTransaction=Transaction{tsourcepos=GenericSourcePos f l c}}) -> (Just (l, Just c),f) Just (_, RegisterScreenItem{ rsItemTransaction=Transaction{tsourcepos=JournalSourcePos f (l,_)}}) -> (Just (l, Nothing),f) -- display mode/query toggles 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 $ toggleFuture 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 = fromIntegral $ maybe 0 (+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" isBlankElement mel = ((rsItemDate . snd) <$> mel) == Just "" rsCenterAndContinue ui = do scrollSelectionToMiddle $ rsList $ aScreen ui continue ui hledger-ui-1.14.2/Hledger/UI/Theme.hs0000644000000000000000000001160113420632425015277 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.14.2/Hledger/UI/TransactionScreen.hs0000644000000000000000000002057713433431637017704 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 #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{..}} = ui tsInit _ _ _ = error "init function called with wrong screen type, should not happen" tsDraw :: UIState -> [Widget Name] tsDraw UIState{aopts=UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}} ,aScreen=TransactionScreen{tsTransaction=(i,t) ,tsTransactions=nts ,tsAccount=acct } ,aMode=mode } = case mode of Help -> [helpDialog copts, maincontent] -- Minibuffer e -> [minibuffer e, maincontent] _ -> [maincontent] where maincontent = Widget Greedy Greedy $ do render $ defaultLayout toplabel bottomlabel $ str $ showTransactionUnelidedOneLineAmounts $ -- (if real_ ropts then filterTransactionPostings (Real True) else id) -- filter postings by --real t where toplabel = str "Transaction " -- <+> withAttr ("border" <> "bold") (str $ "#" ++ show (tindex t)) -- <+> str (" ("++show i++" of "++show (length nts)++" in "++acct++")") <+> (str $ "#" ++ show (tindex t)) <+> str " (" <+> withAttr ("border" <> "bold") (str $ show i) <+> str (" of "++show (length nts)) <+> togglefilters <+> borderQueryStr (query_ ropts) <+> str (" in "++T.unpack (replaceHiddenAccountsNameWith "All" acct)++")") <+> (if ignore_assertions_ $ 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" 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 d <- liftIO getCurrentDay ej <- liftIO $ journalReload copts case ej of Left err -> continue $ screenEnter d errorScreen{esError=err} ui Right j' -> do -- got to redo the register screen's transactions report, to get the latest transactions list for this screen -- XXX duplicates rsInit let ropts' = ropts {depth_=Nothing ,balancetype_=HistoricalBalance } q = filterQuery (not . queryIsDepth) $ queryFromOpts d ropts' thisacctq = Acct $ accountNameToAccountRegex acct -- includes subs items = reverse $ snd $ accountTransactionsReport ropts j' q thisacctq ts = map first6 items numberedts = zip [1..] ts -- select the best current transaction from the new list -- stay at the same index if possible, or if we are now past the end, select the last, otherwise select the first (i',t') = case lookup i numberedts of Just t'' -> (i,t'') Nothing | null numberedts -> (0,nulltransaction) | i > fst (last numberedts) -> last numberedts | otherwise -> head numberedts ui' = ui{aScreen=s{tsTransaction=(i',t') ,tsTransactions=numberedts ,tsAccount=acct}} continue $ regenerateScreens j' d ui' VtyEvent (EvKey (KChar 'I') []) -> continue $ uiCheckBalanceAssertions d (toggleIgnoreBalanceAssertions ui) -- if allowing toggling here, we should refresh the txn list from the parent register screen -- EvKey (KChar 'E') [] -> continue $ regenerateScreens j d $ stToggleEmpty ui -- EvKey (KChar 'C') [] -> continue $ regenerateScreens j d $ stToggleCleared ui -- EvKey (KChar 'R') [] -> continue $ regenerateScreens j d $ stToggleReal ui VtyEvent 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" -- | 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.14.2/Hledger/UI/UIOptions.hs0000644000000000000000000001111513433431637016134 0ustar0000000000000000{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveDataTypeable #-} {-| -} module Hledger.UI.UIOptions where import Data.Data (Data) import Data.Default import Data.Typeable (Typeable) 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 " ,flagNone ["flat","F"] (setboolopt "flat") "show accounts as a list (default)" ,flagNone ["tree","T"] (setboolopt "tree") "show accounts as a tree" -- ,flagNone ["present"] (setboolopt "present") "exclude transactions dated later than today (default)" ,flagNone ["future"] (setboolopt "future") "show transactions dated later than today (normally hidden)" -- ,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 [([Char], [Char])] uimode = (mode "hledger-ui" [("command","ui")] "browse accounts, postings and entries in a full-window curses interface" (argsFlag "[PATTERNS]") []){ modeGroupFlags = Group { groupUnnamed = uiflags ,groupHidden = [] ,groupNamed = [(generalflagsgroup1)] } ,modeHelpSuffix=[ -- "Reads your ~/.hledger.journal file, or another specified by $LEDGER_FILE or -f, and starts the full-window curses ui." ] } -- hledger-ui options, used in hledger-ui and above data UIOpts = UIOpts { watch_ :: Bool ,change_ :: Bool ,presentorfuture_ :: PresentOrFutureOpt ,cliopts_ :: CliOpts } deriving (Show) defuiopts = UIOpts def 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 ,presentorfuture_ = presentorfutureopt rawopts ,cliopts_ = cliopts } -- | Should transactions dated later than today be included ? -- Like flat/tree mode, there are three states, and the meaning of default can vary by command. data PresentOrFutureOpt = PFDefault | PFPresent | PFFuture deriving (Eq, Show, Data, Typeable) instance Default PresentOrFutureOpt where def = PFDefault presentorfutureopt :: RawOpts -> PresentOrFutureOpt presentorfutureopt rawopts = case reverse $ filter (`elem` ["present","future"]) $ map fst rawopts of ("present":_) -> PFPresent ("future":_) -> PFFuture _ -> PFDefault 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 . decodeRawOpts >>= rawOptsToUIOpts getHledgerUIOpts = do args <- getArgs >>= expandArgsAt let args' = replaceNumericFlags args let cmdargopts = either usageError id $ process uimode args' rawOptsToUIOpts $ decodeRawOpts cmdargopts hledger-ui-1.14.2/Hledger/UI/UIState.hs0000644000000000000000000003122313420632425015555 0ustar0000000000000000{-# LANGUAGE CPP #-} {- | UIState operations. -} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Hledger.UI.UIState where #if !MIN_VERSION_brick(0,19,0) import Brick #endif import Brick.Widgets.Edit import Data.List import Data.Text.Zipper (gotoEOL) import Data.Time.Calendar (Day) import Hledger import Hledger.Cli.CliOptions import Hledger.UI.UITypes import Hledger.UI.UIOptions -- | Toggle between showing only 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 = maybeintopt "status-toggles" $ rawopts_ copts showstatus Cleared = "cleared" showstatus Pending = "pending" showstatus Unmarked = "unmarked" reportOptsToggleStatusSomehow :: Status -> CliOpts -> ReportOpts -> ReportOpts reportOptsToggleStatusSomehow s copts ropts = case maybeintopt "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} -- | 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 between including and excluding transactions dated later than today. toggleFuture :: UIState -> UIState toggleFuture ui@UIState{aopts=uopts@UIOpts{presentorfuture_=pf}} = ui{aopts=uopts{presentorfuture_=pf'}} where pf' | pf == PFFuture = PFPresent | otherwise = PFFuture -- | 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}}}} -- | Apply a new filter query. setFilter :: String -> UIState -> UIState setFilter s ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{query_=s}}}} -- | Clear all filters/flags. resetFilter :: UIState -> UIState resetFilter ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{ accountlistmode_=ALFlat ,empty_=True ,statuses_=[] ,real_=False ,query_="" --,period_=PeriodAll }}}} resetDepth :: UIState -> UIState resetDepth ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{depth_=Nothing}}}} -- | Get the maximum account depth in the current journal. maxDepth :: UIState -> Int maxDepth UIState{ajournal=j} = maximum $ map accountNameLevel $ journalAccountNames j -- | Decrement the current depth limit towards 0. If there was no depth limit, -- set it to one less than the maximum account depth. decDepth :: UIState -> UIState decDepth ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts@ReportOpts{..}}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{depth_=dec depth_}}}} where dec (Just d) = Just $ max 0 (d-1) dec Nothing = Just $ maxDepth ui - 1 -- | Increment the current depth limit. If this makes it equal to the -- the maximum account depth, remove the depth limit. incDepth :: UIState -> UIState incDepth ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts@ReportOpts{..}}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{depth_=inc depth_}}}} where inc (Just d) | d < (maxDepth ui - 1) = Just $ d+1 inc _ = Nothing -- | Set the current depth limit to the specified depth, or remove the depth limit. -- Also remove the depth limit if the specified depth is greater than the current -- maximum account depth. If the specified depth is negative, reset the depth limit -- to whatever was specified at uiartup. setDepth :: Maybe Int -> UIState -> UIState setDepth mdepth ui@UIState{aopts=uopts@UIOpts{cliopts_=copts@CliOpts{reportopts_=ropts}}} = ui{aopts=uopts{cliopts_=copts{reportopts_=ropts{depth_=mdepth'}}}} where mdepth' = case mdepth of Nothing -> Nothing Just d | d < 0 -> depth_ ropts | d >= maxDepth ui -> Nothing | otherwise -> mdepth getDepth :: UIState -> Maybe Int getDepth UIState{aopts=UIOpts{cliopts_=CliOpts{reportopts_=ropts}}} = depth_ ropts -- | Open the minibuffer, setting its content to the current query with the cursor at the end. showMinibuffer :: UIState -> UIState showMinibuffer ui = setMode (Minibuffer e) ui where #if MIN_VERSION_brick(0,19,0) e = applyEdit gotoEOL $ editor MinibufferEditor (Just 1) oldq #else e = applyEdit gotoEOL $ editor MinibufferEditor (str . unlines) (Just 1) oldq #endif oldq = query_ $ reportopts_ $ cliopts_ $ aopts ui -- | Close the minibuffer, discarding any edit in progress. closeMinibuffer :: UIState -> UIState closeMinibuffer = setMode Normal setMode :: Mode -> UIState -> UIState setMode m ui = ui{aMode=m} -- | Regenerate the content for the current and previous screens, from a new journal and current date. regenerateScreens :: Journal -> Day -> UIState -> UIState regenerateScreens j d ui@UIState{aScreen=s,aPrevScreens=ss} = -- XXX clumsy due to entanglement of UIState and Screen. -- sInit operates only on an appstate's current screen, so -- remove all the screens from the appstate and then add them back -- one at a time, regenerating as we go. let first:rest = reverse $ s:ss :: [Screen] ui0 = ui{ajournal=j, aScreen=first, aPrevScreens=[]} :: UIState ui1 = (sInit first) d False ui0 :: UIState ui2 = foldl' (\ui s -> (sInit s) d False $ pushScreen s ui) ui1 rest :: UIState in ui2 pushScreen :: Screen -> UIState -> UIState pushScreen scr ui = ui{aPrevScreens=(aScreen ui:aPrevScreens ui) ,aScreen=scr } popScreen :: UIState -> UIState popScreen ui@UIState{aPrevScreens=s:ss} = ui{aScreen=s, aPrevScreens=ss} popScreen ui = ui resetScreens :: Day -> UIState -> UIState resetScreens d ui@UIState{aScreen=s,aPrevScreens=ss} = (sInit topscreen) d True $ resetDepth $ resetFilter $ closeMinibuffer ui{aScreen=topscreen, aPrevScreens=[]} where topscreen = case ss of _:_ -> last ss [] -> s -- | Enter a new screen, saving the old screen & state in the -- navigation history and initialising the new screen's state. screenEnter :: Day -> Screen -> UIState -> UIState screenEnter d scr ui = (sInit scr) d True $ pushScreen scr ui hledger-ui-1.14.2/Hledger/UI/UITypes.hs0000644000000000000000000001565013433431637015615 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 { 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.14.2/Hledger/UI/UIUtils.hs0000644000000000000000000003162613433431637015612 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 ,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 to close)") Nothing (c^.availWidthL)) $ -- (Just (0,[("ok",())])) padTop (Pad 1) $ padLeft (Pad 1) $ padRight (Pad 1) $ vBox [ hBox [ padRight (Pad 1) $ vBox [ withAttr ("help" <> "heading") $ str "Navigation" ,renderKey ("UP/DOWN/PUP/PDN/HOME/END/emacs/vi keys", "") ,str " move selection" ,renderKey ("RIGHT", "show account txns, txn detail") ,renderKey ("LEFT ", "go back") ,renderKey ("ESC ", "cancel or reset") ,str " " ,withAttr ("help" <> "heading") $ str "Report period" ,renderKey ("S-DOWN /S-UP ", "shrink/grow period") ,renderKey ("S-RIGHT/S-LEFT", "next/previous period") ,renderKey ("t ", "set period to today") ,str " " ,withAttr ("help" <> "heading") $ str "Accounts screen" ,renderKey ("-+0123456789 ", "set depth limit") ,renderKey ("T ", "toggle tree/flat mode") ,renderKey ("H ", "historical end balance/period change") ,str " " ,withAttr ("help" <> "heading") $ str "Register screen" ,renderKey ("T ", "toggle subaccount txns\n(and accounts screen tree/flat mode)") ,renderKey ("H ", "show historical total/period total") ,str " " ] ,padLeft (Pad 1) $ padRight (Pad 0) $ vBox [ withAttr ("help" <> "heading") $ str "Filtering" ,renderKey ("/ ", "set a filter query") ,renderKey ("UPC ", "show unmarked/pending/cleared") ,renderKey ("F ", "show future/present txns") ,renderKey ("R ", "show real/all postings") ,renderKey ("Z ", "show nonzero/all amounts") ,renderKey ("DEL ", "remove filters") ,str " " ,withAttr ("help" <> "heading") $ str "Help" ,renderKey ("? ", "toggle this help") ,renderKey ("pmi ", "(with this help open)\nshow manual in pager/man/info") ,str " " ,withAttr ("help" <> "heading") $ str "Other" ,renderKey ("a ", "add transaction (hledger add)") ,renderKey ("A ", "add transaction (hledger-iadd)") ,renderKey ("E ", "open editor") ,renderKey ("I ", "toggle balance assertions") ,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` (moveLeftEvents ++ [EvKey KEsc [], EvKey (KChar '?') []]) -> 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 -- | Draw the minibuffer. minibuffer :: Editor String Name -> Widget Name minibuffer ed = forceAttr ("border" <> "minibuffer") $ hBox $ #if MIN_VERSION_brick(0,19,0) [txt "filter: ", renderEditor (str . unlines) True ed] #else [txt "filter: ", renderEditor True ed] #endif 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 " " -- | Render the two states of a toggle, 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) -- 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.14.2/LICENSE0000644000000000000000000010451313302271455013025 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.14.2/Setup.hs0000644000000000000000000000005613302271455013451 0ustar0000000000000000import Distribution.Simple main = defaultMain hledger-ui-1.14.2/hledger-ui.cabal0000644000000000000000000000575113444557131015042 0ustar0000000000000000cabal-version: 1.12 -- This file has been generated from package.yaml by hpack version 0.31.1. -- -- see: https://github.com/sol/hpack -- -- hash: f9ea5523eba91a10f52f9d821483b82f77605674174f9f062dc10116047094d8 name: hledger-ui version: 1.14.2 synopsis: Curses-style user interface for the hledger accounting tool description: This is hledger's curses-style interface. It is simpler and more convenient for browsing data than the command-line interface, but lighter and faster than hledger-web. . hledger is a cross-platform program for tracking money, time, or any other commodity, using double-entry accounting and a simple, editable file format. It is inspired by and largely compatible with ledger(1). hledger provides command-line, curses and web interfaces, and aims to be a reliable, practical tool for daily use. category: Finance, Console stability: stable homepage: http://hledger.org bug-reports: http://bugs.hledger.org author: Simon Michael maintainer: Simon Michael license: GPL-3 license-file: LICENSE tested-with: GHC==7.10.3, GHC==8.0.2, GHC==8.2.2, GHC==8.4.3, GHC==8.6.3 build-type: Simple extra-source-files: CHANGES.md README 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.14.2" build-depends: ansi-terminal >=0.6.2.3 , async , base >=4.8 && <4.13 , base-compat-batteries >=0.10.1 && <0.11 , cmdargs >=0.8 , containers , data-default , directory , filepath , fsnotify >=0.2.1.2 && <0.4 , hledger >=1.14.2 && <1.15 , hledger-lib >=1.14.1 && <1.15 , megaparsec >=7.0.0 && <8 , 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 , vector if os(windows) buildable: False else build-depends: brick >=0.23 , unix , vty >=5.5 if flag(threaded) ghc-options: -threaded default-language: Haskell2010 hledger-ui-1.14.2/CHANGES.md0000644000000000000000000003052713444557412013424 0ustar0000000000000000User-visible changes in hledger-ui. See also the hledger changelog. # 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.14.2/README0000644000000000000000000000201513302271455012672 0ustar0000000000000000A curses-style text user interface for the hledger accounting tool. hledger-ui is the new name for hledger-vty. Revived in 2015, this package is intended to be installed as standard by all hledger users, except those on (native) Windows, where it is not supported. hledger-ui currently allows browsing the balance, register and print reports, with drill-down and scrolling. # HACKING ## Backlog: ``` reg: show historical running balance acc: fix -H, show historical balances switch to multibalance report ? adjust filter accounts screen register screen reg: improve other account names test showing only real postings when there are reals and virtuals journal entry view dialog blog reg: support -V redraw on ctrl-l/cmd-r reload on redraw reload on screen change reload on file change acc: show total fix --drop show "modified account names" with --drop or --alias journal screen bs/is/cf-ish reports persistent custom reports persistent config search in page adjust other options add edit custom screens plugin screens ```hledger-ui-1.14.2/hledger-ui.10000644000000000000000000004045213436345506014137 0ustar0000000000000000 .TH "hledger\-ui" "1" "March 2019" "hledger\-ui 1.14" "hledger User Manuals" .SH NAME .PP hledger\-ui \- curses\-style interface for the hledger accounting tool .SH SYNOPSIS .PP \f[C]hledger\-ui\ [OPTIONS]\ [QUERYARGS]\f[] .PD 0 .P .PD \f[C]hledger\ ui\ \-\-\ [OPTIONS]\ [QUERYARGS]\f[] .SH DESCRIPTION .PP hledger is a cross\-platform program for tracking money, time, or any other commodity, using double\-entry accounting and a simple, editable file format. hledger is inspired by and largely compatible with ledger(1). .PP hledger\-ui is hledger\[aq]s curses\-style interface, providing an efficient full\-window text UI for viewing accounts and transactions, and some limited data entry capability. It is easier than hledger\[aq]s command\-line interface, and sometimes quicker and more convenient than the web interface. .PP Note hledger\-ui has some different defaults (experimental): .IP \[bu] 2 it generates rule\-based transactions and postings by default (\-\-forecast and \-\-auto are always on). .IP \[bu] 2 it hides transactions dated in the future by default (change this with \-\-future or the F key). .PP Like hledger, it reads data from one or more files in hledger journal, timeclock, timedot, or CSV format specified with \f[C]\-f\f[], or \f[C]$LEDGER_FILE\f[], or \f[C]$HOME/.hledger.journal\f[] (on windows, perhaps \f[C]C:/Users/USER/.hledger.journal\f[]). For more about this see hledger(1), hledger_journal(5) etc. .SH OPTIONS .PP Note: if invoking hledger\-ui as a hledger subcommand, write \f[C]\-\-\f[] before options as shown above. .PP Any QUERYARGS are interpreted as a hledger search query which filters the data. .TP .B \f[C]\-\-watch\f[] watch for data and date changes and reload automatically .RS .RE .TP .B \f[C]\-\-theme=default|terminal|greenterm\f[] use this custom display theme .RS .RE .TP .B \f[C]\-\-register=ACCTREGEX\f[] start in the (first) matched account\[aq]s register screen .RS .RE .TP .B \f[C]\-\-change\f[] show period balances (changes) at startup instead of historical balances .RS .RE .TP .B \f[C]\-F\ \-\-flat\f[] show accounts as a list (default) .RS .RE .TP .B \f[C]\-T\ \-\-tree\f[] show accounts as a tree .RS .RE .TP .B \f[C]\-\-future\f[] show transactions dated later than today (normally hidden) .RS .RE .PP hledger input options: .TP .B \f[C]\-f\ FILE\ \-\-file=FILE\f[] use a different input file. For stdin, use \- (default: \f[C]$LEDGER_FILE\f[] or \f[C]$HOME/.hledger.journal\f[]) .RS .RE .TP .B \f[C]\-\-rules\-file=RULESFILE\f[] Conversion rules file to use when reading CSV (default: FILE.rules) .RS .RE .TP .B \f[C]\-\-separator=CHAR\f[] Field separator to expect when reading CSV (default: \[aq],\[aq]) .RS .RE .TP .B \f[C]\-\-alias=OLD=NEW\f[] rename accounts named OLD to NEW .RS .RE .TP .B \f[C]\-\-anon\f[] anonymize accounts and payees .RS .RE .TP .B \f[C]\-\-pivot\ FIELDNAME\f[] use some other field or tag for the account name .RS .RE .TP .B \f[C]\-I\ \-\-ignore\-assertions\f[] ignore any failing balance assertions .RS .RE .PP hledger reporting options: .TP .B \f[C]\-b\ \-\-begin=DATE\f[] include postings/txns on or after this date .RS .RE .TP .B \f[C]\-e\ \-\-end=DATE\f[] include postings/txns before this date .RS .RE .TP .B \f[C]\-D\ \-\-daily\f[] multiperiod/multicolumn report by day .RS .RE .TP .B \f[C]\-W\ \-\-weekly\f[] multiperiod/multicolumn report by week .RS .RE .TP .B \f[C]\-M\ \-\-monthly\f[] multiperiod/multicolumn report by month .RS .RE .TP .B \f[C]\-Q\ \-\-quarterly\f[] multiperiod/multicolumn report by quarter .RS .RE .TP .B \f[C]\-Y\ \-\-yearly\f[] multiperiod/multicolumn report by year .RS .RE .TP .B \f[C]\-p\ \-\-period=PERIODEXP\f[] set start date, end date, and/or reporting interval all at once using period expressions syntax (overrides the flags above) .RS .RE .TP .B \f[C]\-\-date2\f[] match the secondary date instead (see command help for other effects) .RS .RE .TP .B \f[C]\-U\ \-\-unmarked\f[] include only unmarked postings/txns (can combine with \-P or \-C) .RS .RE .TP .B \f[C]\-P\ \-\-pending\f[] include only pending postings/txns .RS .RE .TP .B \f[C]\-C\ \-\-cleared\f[] include only cleared postings/txns .RS .RE .TP .B \f[C]\-R\ \-\-real\f[] include only non\-virtual postings .RS .RE .TP .B \f[C]\-NUM\ \-\-depth=NUM\f[] hide/aggregate accounts or postings more than NUM levels deep .RS .RE .TP .B \f[C]\-E\ \-\-empty\f[] show items with zero amount, normally hidden (and vice\-versa in hledger\-ui/hledger\-web) .RS .RE .TP .B \f[C]\-B\ \-\-cost\f[] convert amounts to their cost at transaction time (using the transaction price, if any) .RS .RE .TP .B \f[C]\-V\ \-\-value\f[] convert amounts to their market value on the report end date (using the most recent applicable market price, if any) .RS .RE .TP .B \f[C]\-\-auto\f[] apply automated posting rules to modify transactions. .RS .RE .TP .B \f[C]\-\-forecast\f[] apply periodic transaction rules to generate future transactions, to 6 months from now or report end date. .RS .RE .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 .B \f[C]\-h\ \-\-help\f[] show general usage (or after COMMAND, command usage) .RS .RE .TP .B \f[C]\-\-version\f[] show version .RS .RE .TP .B \f[C]\-\-debug[=N]\f[] show debug output (levels 1\-9, default: 1) .RS .RE .PP 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 \f[C]\-\-\f[] argument before.) .SH KEYS .PP \f[C]?\f[] shows a help dialog listing all keys. (Some of these also appear in the quick help at the bottom of each screen.) Press \f[C]?\f[] again (or \f[C]ESCAPE\f[], or \f[C]LEFT\f[]) to close it. The following keys work on most screens: .PP The cursor keys navigate: \f[C]right\f[] (or \f[C]enter\f[]) goes deeper, \f[C]left\f[] returns to the previous screen, \f[C]up\f[]/\f[C]down\f[]/\f[C]page\ up\f[]/\f[C]page\ down\f[]/\f[C]home\f[]/\f[C]end\f[] move up and down through lists. Vi\-style (\f[C]h\f[]/\f[C]j\f[]/\f[C]k\f[]/\f[C]l\f[]) and Emacs\-style (\f[C]CTRL\-p\f[]/\f[C]CTRL\-n\f[]/\f[C]CTRL\-f\f[]/\f[C]CTRL\-b\f[]) movement keys are also supported. A tip: movement speed is limited by your keyboard repeat rate, to move faster you may want to adjust it. (If you\[aq]re on a mac, the Karabiner app is one way to do that.) .PP With shift pressed, the cursor keys adjust the report period, limiting the transactions to be shown (by default, all are shown). \f[C]shift\-down/up\f[] steps downward and upward through these standard report period durations: year, quarter, month, week, day. Then, \f[C]shift\-left/right\f[] moves to the previous/next period. \f[C]t\f[] sets the report period to today. With the \f[C]\-\-watch\f[] option, when viewing a "current" period (the current day, week, month, quarter, or year), the period will move automatically to track the current date. To set a non\-standard period, you can use \f[C]/\f[] and a \f[C]date:\f[] query. .PP \f[C]/\f[] lets you set a general filter query limiting the data shown, using the same query terms as in hledger and hledger\-web. While editing the query, you can use CTRL\-a/e/d/k, BS, cursor keys; press \f[C]ENTER\f[] to set it, or \f[C]ESCAPE\f[]to cancel. There are also keys for quickly adjusting some common filters like account depth and transaction status (see below). \f[C]BACKSPACE\f[] or \f[C]DELETE\f[] removes all filters, showing all transactions. .PP As mentioned above, hledger\-ui shows auto\-generated periodic transactions, and hides future transactions (auto\-generated or not) by default. \f[C]F\f[] toggles showing and hiding these future transactions. This is similar to using a query like \f[C]date:\-tomorrow\f[], but more convenient. (experimental) .PP \f[C]ESCAPE\f[] removes all filters and jumps back to the top screen. Or, it cancels a minibuffer edit or help dialog in progress. .PP \f[C]CTRL\-l\f[] 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[] reloads from the data file(s) and updates the current screen and any previous screens. (With large files, this could cause a noticeable pause.) .PP \f[C]I\f[] toggles balance assertion checking. Disabling balance assertions temporarily can be useful for troubleshooting. .PP \f[C]a\f[] runs command\-line hledger\[aq]s add command, and reloads the updated file. This allows some basic data entry. .PP \f[C]A\f[] is like \f[C]a\f[], but runs the hledger\-iadd tool, which provides a curses\-style interface. This key will be available if \f[C]hledger\-iadd\f[] is installed in $PATH. .PP \f[C]E\f[] runs $HLEDGER_UI_EDITOR, or $EDITOR, or a default (\f[C]emacsclient\ \-a\ ""\ \-nw\f[]) on the journal file. With some editors (emacs, vi), the cursor will be positioned at the current transaction when invoked from the register and transaction screens, and at the error location (if possible) when invoked from the error screen. .PP \f[C]q\f[] quits the application. .PP Additional screen\-specific keys are described below. .SH SCREENS .SS Accounts screen .PP This is normally the first screen displayed. It lists accounts and their balances, like hledger\[aq]s balance command. By default, it shows all accounts and their latest ending balances (including the balances of subaccounts). if you specify a query on the command line, it shows just the matched accounts and the balances from matched transactions. .PP Account names are shown as a flat list by default. Press \f[C]T\f[] to toggle tree mode. In flat 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[] to \f[C]9\f[], to set a depth limit. Or use \f[C]\-\f[] to decrease and \f[C]+\f[]/\f[C]=\f[] to increase the depth limit. \f[C]0\f[] 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[]. .PP \f[C]H\f[] toggles between showing historical balances or period balances. Historical balances (the default) are ending balances at the end of the report period, taking into account all transactions before that date (filtered by the filter query if any), including transactions before the start of the report period. In other words, historical balances are what you would see on a bank statement for that account (unless disturbed by a filter query). Period balances ignore transactions before the report start date, so they show the change in balance during the report period. They are more useful eg when viewing a time log. .PP \f[C]U\f[] toggles filtering by unmarked status, including or excluding unmarked postings in the balances. Similarly, \f[C]P\f[] toggles pending postings, and \f[C]C\f[] 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[] toggles real mode, in which virtual postings are ignored. .PP \f[C]Z\f[] toggles nonzero mode, in which only accounts with nonzero balances are shown (hledger\-ui shows zero items by default, unlike command\-line hledger). .PP Press \f[C]right\f[] or \f[C]enter\f[] to view an account\[aq]s transactions register. .SS Register screen .PP This screen shows the transactions affecting a particular account, like a check register. Each line represents one transaction and shows: .IP \[bu] 2 the other account(s) involved, in abbreviated form. (If there are both real and virtual postings, it shows only the accounts affected by real postings.) .IP \[bu] 2 the overall change to the current account\[aq]s balance; positive for an inflow to this account, negative for an outflow. .IP \[bu] 2 the running historical total or period total for the current account, after the transaction. This can be toggled with \f[C]H\f[]. Similar to the accounts screen, the historical total is affected by transactions (filtered by the filter query) before the report start date, while the period total is not. If the historical total is not disturbed by a filter query, it will be the running historical balance you would see on a bank register for the current account. .PP 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 flat 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. .PD 0 .P .PD Tree mode/flat mode can be toggled with \f[C]T\f[] here also. .PP \f[C]U\f[] toggles filtering by unmarked status, showing or hiding unmarked transactions. Similarly, \f[C]P\f[] toggles pending transactions, and \f[C]C\f[] 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[] toggles real mode, in which virtual postings are ignored. .PP \f[C]Z\f[] toggles nonzero mode, in which only transactions posting a nonzero change are shown (hledger\-ui shows zero items by default, unlike command\-line hledger). .PP Press \f[C]right\f[] (or \f[C]enter\f[]) to view the selected transaction in detail. .SS Transaction screen .PP This screen shows a single transaction, as a general journal entry, similar to hledger\[aq]s print command and journal format (hledger_journal(5)). .PP The transaction\[aq]s date(s) and any cleared flag, transaction code, description, comments, along with all of its account postings are shown. Simple transactions have two postings, but there can be more (or in certain cases, fewer). .PP \f[C]up\f[] and \f[C]down\f[] will step through all transactions listed in the previous account register screen. In the title bar, the numbers in parentheses show your position within that account register. They will vary depending on which account register you came from (remember most transactions appear in multiple account registers). The #N number preceding them is the transaction\[aq]s position within the complete unfiltered journal, which is a more stable id (at least until the next reload). .SS Error screen .PP This screen will appear if there is a problem, such as a parse error, when you press g to reload. Once you have fixed the problem, press g again to reload and resume normal operation. (Or, you can press escape to cancel the reload attempt.) .SH ENVIRONMENT .PP \f[B]COLUMNS\f[] The screen width to use. Default: the full terminal width. .PP \f[B]LEDGER_FILE\f[] The journal file path when not specified with \f[C]\-f\f[]. Default: \f[C]~/.hledger.journal\f[] (on windows, perhaps \f[C]C:/Users/USER/.hledger.journal\f[]). .SH FILES .PP Reads data from one or more files in hledger journal, timeclock, timedot, or CSV format specified with \f[C]\-f\f[], or \f[C]$LEDGER_FILE\f[], or \f[C]$HOME/.hledger.journal\f[] (on windows, perhaps \f[C]C:/Users/USER/.hledger.journal\f[]). .SH BUGS .PP The need to precede options with \f[C]\-\-\f[] when invoked from hledger is awkward. .PP \f[C]\-f\-\f[] doesn\[aq]t work (hledger\-ui can\[aq]t read from stdin). .PP \f[C]\-V\f[] affects only the accounts screen. .PP When you press \f[C]g\f[], the current and all previous screens are regenerated, which may cause a noticeable pause with large files. Also there is no visual indication that this is in progress. .PP \f[C]\-\-watch\f[] is not yet fully robust. It works well for normal usage, but many file changes in a short time (eg saving the file thousands of times with an editor macro) can cause problems at least on OSX. Symptoms include: unresponsive UI, periodic resetting of the cursor position, momentary display of parse errors, high CPU usage eventually subsiding, and possibly a small but persistent build\-up of CPU usage until the program is restarted. .SH "REPORTING BUGS" Report bugs at http://bugs.hledger.org (or on the #hledger IRC channel or hledger mail list) .SH AUTHORS Simon Michael and contributors .SH COPYRIGHT Copyright (C) 2007-2016 Simon Michael. .br Released under GNU GPL v3 or later. .SH SEE ALSO hledger(1), hledger\-ui(1), hledger\-web(1), hledger\-api(1), hledger_csv(5), hledger_journal(5), hledger_timeclock(5), hledger_timedot(5), ledger(1) http://hledger.org hledger-ui-1.14.2/hledger-ui.txt0000644000000000000000000004165413436345517014625 0ustar0000000000000000 hledger-ui(1) hledger User Manuals hledger-ui(1) NAME hledger-ui - curses-style interface for the hledger accounting tool SYNOPSIS hledger-ui [OPTIONS] [QUERYARGS] hledger ui -- [OPTIONS] [QUERYARGS] DESCRIPTION hledger is a cross-platform program for tracking money, time, or any other commodity, using double-entry accounting and a simple, editable file format. hledger is inspired by and largely compatible with ledger(1). hledger-ui is hledger's curses-style interface, providing an efficient full-window text UI for viewing accounts and transactions, and some limited data entry capability. It is easier than hledger's com- mand-line interface, and sometimes quicker and more convenient than the web interface. Note hledger-ui has some different defaults (experimental): o it generates rule-based transactions and postings by default (--fore- cast and --auto are always on). o it hides transactions dated in the future by default (change this with --future or the F key). Like hledger, it reads data from one or more files in hledger journal, timeclock, timedot, or CSV format specified with -f, or $LEDGER_FILE, or $HOME/.hledger.journal (on windows, perhaps C:/Users/USER/.hledger.journal). For more about this see hledger(1), hledger_journal(5) etc. OPTIONS Note: if invoking hledger-ui as a hledger subcommand, write -- before options as shown above. Any QUERYARGS are interpreted as a hledger search query which filters the data. --watch watch for data and date changes and reload automatically --theme=default|terminal|greenterm use this custom display theme --register=ACCTREGEX start in the (first) matched account's register screen --change show period balances (changes) at startup instead of historical balances -F --flat show accounts as a list (default) -T --tree show accounts as a tree --future show transactions dated later than today (normally hidden) 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 ignore any failing balance assertions hledger reporting options: -b --begin=DATE include postings/txns on or after this date -e --end=DATE include postings/txns before this date -D --daily multiperiod/multicolumn report by day -W --weekly multiperiod/multicolumn report by week -M --monthly multiperiod/multicolumn report by month -Q --quarterly multiperiod/multicolumn report by quarter -Y --yearly multiperiod/multicolumn report by year -p --period=PERIODEXP set start date, end date, and/or reporting interval all at once using period expressions syntax (overrides the flags above) --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 at transaction time (using the transaction price, if any) -V --value convert amounts to their market value on the report end date (using the most recent applicable market price, if any) --auto apply automated posting rules to modify transactions. --forecast apply periodic transaction rules to generate future transac- tions, to 6 months from now or report end date. 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) to close it. The following keys work on most screens: The cursor keys navigate: right (or enter) goes deeper, left returns to the previous screen, up/down/page up/page down/home/end move up and down through lists. Vi-style (h/j/k/l) and Emacs-style (CTRL-p/CTRL-n/CTRL-f/CTRL-b) movement keys are also supported. A tip: movement speed is limited by your keyboard repeat rate, to move faster you may want to adjust it. (If you're on a mac, the Karabiner app is one way to do that.) With shift pressed, the cursor keys adjust the report period, limiting the transactions to be shown (by default, all are shown). shift-down/up steps downward and upward through these standard report period durations: year, quarter, month, week, day. Then, shift-left/right moves to the previous/next period. t sets the report period to today. With the --watch option, when viewing a "current" period (the current day, week, month, quarter, or year), the period will move automatically to track the current date. To set a non-stan- dard period, you can use / and a date: query. / lets you set a general filter query limiting the data shown, using the same query terms as in hledger and hledger-web. While editing the query, you can use CTRL-a/e/d/k, BS, cursor keys; press ENTER to set it, or ESCAPEto cancel. There are also keys for quickly adjusting some common filters like account depth and transaction status (see below). BACKSPACE or DELETE removes all filters, showing all transactions. As mentioned above, hledger-ui shows auto-generated periodic transac- tions, and hides future transactions (auto-generated or not) by default. F toggles showing and hiding these future transactions. This is similar to using a query like date:-tomorrow, but more convenient. (experimental) ESCAPE removes all filters and jumps back to the top screen. Or, it cancels a minibuffer edit or help dialog in progress. 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 curses-style interface. This key will be available if hledger-iadd is installed in $PATH. E runs $HLEDGER_UI_EDITOR, or $EDITOR, or a default (emac- sclient -a "" -nw) on the journal file. With some editors (emacs, vi), the cursor will be positioned at the current transaction when invoked from the register and transaction screens, and at the error location (if possible) when invoked from the error screen. q quits the application. Additional screen-specific keys are described below. SCREENS Accounts screen This is normally the first screen displayed. It lists accounts and their balances, like hledger's balance command. By default, it shows all accounts and their latest ending balances (including the balances of subaccounts). if you specify a query on the command line, it shows just the matched accounts and the balances from matched transactions. Account names are shown as a flat list by default. Press T to toggle tree mode. In flat mode, account balances are exclusive of subac- counts, except where subaccounts are hidden by a depth limit (see below). In tree mode, all account balances are inclusive of subac- counts. 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. His- torical balances (the default) are ending balances at the end of the report period, taking into account all transactions before that date (filtered by the filter query if any), including transactions before the start of the report period. In other words, historical balances are what you would see on a bank statement for that account (unless disturbed by a filter query). Period balances ignore transactions before the report start date, so they show the change in balance during the report period. They are more useful eg when viewing a time log. 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. 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 flat 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/flat 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, description, comments, along with all of its account postings are shown. Simple transactions have two postings, but there can be more (or in certain cases, fewer). up and down will step through all transactions listed in the previous account register screen. In the title bar, the numbers in parentheses show your position within that account register. They will vary depending on which account register you came from (remember most trans- actions appear in multiple account registers). The #N number preceding them is the transaction's position within the complete unfiltered jour- nal, which is a more stable id (at least until the next reload). Error screen This screen will appear if there is a problem, such as a parse error, when you press g to reload. Once you have fixed the problem, press g again to reload and resume normal operation. (Or, you can press escape to cancel the reload attempt.) ENVIRONMENT COLUMNS The screen width to use. Default: the full terminal width. LEDGER_FILE The journal file path when not specified with -f. Default: ~/.hledger.journal (on windows, perhaps C:/Users/USER/.hledger.jour- nal). FILES Reads data from one or more files in hledger journal, timeclock, time- dot, or CSV format specified with -f, or $LEDGER_FILE, or $HOME/.hledger.journal (on windows, perhaps C:/Users/USER/.hledger.journal). BUGS The need to precede options with -- when invoked from hledger is awk- ward. -f- doesn't work (hledger-ui can't read from stdin). -V affects only the accounts screen. When you press g, the current and all previous screens are regenerated, which may cause a noticeable pause with large files. Also there is no visual indication that this is in progress. --watch is not yet fully robust. It works well for normal usage, but many file changes in a short time (eg saving the file thousands of times with an editor macro) can cause problems at least on OSX. Symp- toms include: unresponsive UI, periodic resetting of the cursor posi- tion, momentary display of parse errors, high CPU usage eventually sub- siding, and possibly a small but persistent build-up of CPU usage until the program is restarted. REPORTING BUGS Report bugs at http://bugs.hledger.org (or on the #hledger IRC channel or hledger mail list) AUTHORS Simon Michael and contributors COPYRIGHT Copyright (C) 2007-2016 Simon Michael. Released under GNU GPL v3 or later. SEE ALSO hledger(1), hledger-ui(1), hledger-web(1), hledger-api(1), hledger_csv(5), hledger_journal(5), hledger_timeclock(5), hledger_time- dot(5), ledger(1) http://hledger.org hledger-ui 1.14 March 2019 hledger-ui(1) hledger-ui-1.14.2/hledger-ui.info0000644000000000000000000003410313436345506014726 0ustar0000000000000000This is hledger-ui.info, produced by makeinfo version 6.5 from stdin.  File: hledger-ui.info, Node: Top, Next: OPTIONS, Up: (dir) hledger-ui(1) hledger-ui 1.14 ***************************** hledger-ui is hledger's curses-style interface, providing an efficient full-window text UI for viewing accounts and transactions, and some limited data entry capability. It is easier than hledger's command-line interface, and sometimes quicker and more convenient than the web interface. Note hledger-ui has some different defaults (experimental): * it generates rule-based transactions and postings by default (-forecast and -auto are always on). * it hides transactions dated in the future by default (change this with -future or the F key). Like hledger, it reads data from one or more files in hledger journal, timeclock, timedot, or CSV format specified with '-f', or '$LEDGER_FILE', or '$HOME/.hledger.journal' (on windows, perhaps 'C:/Users/USER/.hledger.journal'). For more about this see hledger(1), hledger_journal(5) etc. * Menu: * OPTIONS:: * KEYS:: * SCREENS::  File: hledger-ui.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 '-F --flat' show accounts as a list (default) '-T --tree' show accounts as a tree '--future' show transactions dated later than today (normally hidden) 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' ignore any failing balance assertions hledger reporting options: '-b --begin=DATE' include postings/txns on or after this date '-e --end=DATE' include postings/txns before this date '-D --daily' multiperiod/multicolumn report by day '-W --weekly' multiperiod/multicolumn report by week '-M --monthly' multiperiod/multicolumn report by month '-Q --quarterly' multiperiod/multicolumn report by quarter '-Y --yearly' multiperiod/multicolumn report by year '-p --period=PERIODEXP' set start date, end date, and/or reporting interval all at once using period expressions syntax (overrides the flags above) '--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 at transaction time (using the transaction price, if any) '-V --value' convert amounts to their market value on the report end date (using the most recent applicable market price, if any) '--auto' apply automated posting rules to modify transactions. '--forecast' apply periodic transaction rules to generate future transactions, to 6 months from now or report end date. 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') to close it. The following keys work on most screens: The cursor keys navigate: 'right' (or 'enter') goes deeper, 'left' returns to the previous screen, 'up'/'down'/'page up'/'page down'/'home'/'end' move up and down through lists. Vi-style ('h'/'j'/'k'/'l') and Emacs-style ('CTRL-p'/'CTRL-n'/'CTRL-f'/'CTRL-b') movement keys are also supported. A tip: movement speed is limited by your keyboard repeat rate, to move faster you may want to adjust it. (If you're on a mac, the Karabiner app is one way to do that.) With shift pressed, the cursor keys adjust the report period, limiting the transactions to be shown (by default, all are shown). 'shift-down/up' steps downward and upward through these standard report period durations: year, quarter, month, week, day. Then, 'shift-left/right' moves to the previous/next period. 't' sets the report period to today. With the '--watch' option, when viewing a "current" period (the current day, week, month, quarter, or year), the period will move automatically to track the current date. To set a non-standard period, you can use '/' and a 'date:' query. '/' lets you set a general filter query limiting the data shown, using the same query terms as in hledger and hledger-web. While editing the query, you can use CTRL-a/e/d/k, BS, cursor keys; press 'ENTER' to set it, or 'ESCAPE'to cancel. There are also keys for quickly adjusting some common filters like account depth and transaction status (see below). 'BACKSPACE' or 'DELETE' removes all filters, showing all transactions. As mentioned above, hledger-ui shows auto-generated periodic transactions, and hides future transactions (auto-generated or not) by default. 'F' toggles showing and hiding these future transactions. This is similar to using a query like 'date:-tomorrow', but more convenient. (experimental) 'ESCAPE' removes all filters and jumps back to the top screen. Or, it cancels a minibuffer edit or help dialog in progress. '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 curses-style 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. 'q' quits the application. Additional screen-specific keys are described below.  File: hledger-ui.info, Node: SCREENS, 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 flat 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 flat 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/flat 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.)  Tag Table: Node: Top71 Node: OPTIONS1100 Ref: #options1197 Node: KEYS4616 Ref: #keys4711 Node: SCREENS7967 Ref: #screens8052 Node: Accounts screen8142 Ref: #accounts-screen8270 Node: Register screen10486 Ref: #register-screen10641 Node: Transaction screen12637 Ref: #transaction-screen12795 Node: Error screen13665 Ref: #error-screen13787  End Tag Table