hledger-ui-1.50.3/Hledger/0000755000000000000000000000000015054061121013360 5ustar0000000000000000hledger-ui-1.50.3/Hledger/UI/0000755000000000000000000000000015107174442013707 5ustar0000000000000000hledger-ui-1.50.3/app/0000755000000000000000000000000015054061121012566 5ustar0000000000000000hledger-ui-1.50.3/Hledger/UI.hs0000644000000000000000000000115215054061121014230 0ustar0000000000000000{-| This is the root module of the @hledger-ui@ package, providing hledger's terminal user interface. The main function, command-line options, and terminal themes are exported. == See also: - hledger-lib:Hledger - hledger:Hledger.Cli - [The README files](https://github.com/search?q=repo%3Asimonmichael%2Fhledger+path%3A**%2FREADME*&type=code&ref=advsearch) - [The high-level developer docs](https://hledger.org/dev.html) -} module Hledger.UI ( module Hledger.UI.Main, module Hledger.UI.Theme, module Hledger.UI.UIOptions, ) where import Hledger.UI.Main import Hledger.UI.UIOptions import Hledger.UI.Theme hledger-ui-1.50.3/Hledger/UI/Main.hs0000644000000000000000000003542415107137141015132 0ustar0000000000000000{-| hledger-ui - a hledger add-on providing an efficient TUI. SPDX-License-Identifier: GPL-3.0-or-later Copyright (c) 2007-2025 (each year in this range) Simon Michael and contributors. 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 . -} {-# LANGUAGE CPP #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE MultiWayIf #-} module Hledger.UI.Main where import Control.Applicative ((<|>)) import Control.Concurrent (threadDelay) import Control.Concurrent.Async (withAsync) #if MIN_VERSION_base(4,20,0) import Control.Exception.Backtrace (setBacktraceMechanismState, BacktraceMechanism(..)) #endif import Control.Monad (forM_, void, when) import Data.Bifunctor (first) import Data.Function ((&)) import Data.List (find) import Data.List.Extra (nubSort) import Data.Maybe (fromMaybe) import Data.Text qualified as T import Graphics.Vty (Mode (Mouse), Vty (outputIface), Output (setMode)) import Graphics.Vty.CrossPlatform (mkVty) import Lens.Micro ((^.)) import System.Directory (canonicalizePath) import System.Environment (withProgName) import System.FilePath (takeDirectory) import System.FSNotify (Event(Added, Modified), watchDir, withManager, EventIsDirectory (IsFile)) import Brick hiding (bsDraw) import Brick.BChan qualified as BC import Hledger import Hledger.Cli hiding (progname,prognameandversion) import Hledger.UI.Theme import Hledger.UI.UIOptions import Hledger.UI.UITypes import Hledger.UI.UIState (uiState, getDepth) import Hledger.UI.UIUtils (dbguiEv, showScreenStack, showScreenSelection) import Hledger.UI.MenuScreen import Hledger.UI.AccountsScreen import Hledger.UI.CashScreen import Hledger.UI.BalancesheetScreen import Hledger.UI.IncomestatementScreen import Hledger.UI.RegisterScreen import Hledger.UI.TransactionScreen import Hledger.UI.ErrorScreen import Hledger.UI.UIScreens ---------------------------------------------------------------------- newChan :: IO (BC.BChan a) newChan = BC.newBChan 10 writeChan :: BC.BChan a -> a -> IO () writeChan = BC.writeBChan hledgerUiMain :: IO () hledgerUiMain = handleExit $ withGhcDebug' $ withProgName "hledger-ui.log" $ do -- force Hledger.Utils.Debug.* to log to hledger-ui.log when (ghcDebugMode == GDPauseAtStart) $ ghcDebugPause' #if MIN_VERSION_base(4,20,0) -- Control ghc 9.10+'s stack traces. -- CostCentreBacktrace - collect cost-centre stack backtraces (only available when built with profiling) -- HasCallStackBacktrace - collect HasCallStack backtraces -- ExecutionBacktrace - collect backtraces from native execution stack unwinding -- IPEBacktrace - collect backtraces from Info Table Provenance Entries #ifdef DEBUG setBacktraceMechanismState HasCallStackBacktrace True #else setBacktraceMechanismState HasCallStackBacktrace False #endif #endif dbg1MsgIO "\n\n\n\n==== hledger-ui start" dbg1IO "args" progArgs dbg1IO "debugLevel" debugLevel opts1@UIOpts{uoCliOpts=copts@CliOpts{inputopts_=iopts,rawopts_=rawopts}} <- getHledgerUIOpts -- when (debug_ $ cliopts_ opts) $ printf "%s\n" prognameandversion >> printf "opts: %s\n" (show opts) usecolor <- useColorOnStdout -- When ANSI colour/styling is available and enabled, encourage user's $PAGER to use it (for command line help). when usecolor setupPager -- And when it's not, disable colour in the TUI ? -- Theme.hs's themes currently hard code various colours and styles provided by vty, -- which probably are disabled automatically when terminal doesn't support them. -- But we'll at least force hledger-ui's theme to a monochrome one. let opts = if usecolor then opts1 else opts1{uoTheme=Just "terminal"} -- always generate forecasted periodic transactions; their visibility will be toggled by the UI. let copts' = copts{inputopts_=iopts{forecast_=forecast_ iopts <|> Just nulldatespan}} case True of _ | boolopt "help" rawopts -> runPager $ showModeUsage uimode ++ "\n" _ | boolopt "tldr" rawopts -> runTldrForPage "hledger-ui" _ | boolopt "info" rawopts -> runInfoForTopic "hledger-ui" Nothing _ | boolopt "man" rawopts -> runManForTopic "hledger-ui" Nothing _ | boolopt "version" rawopts -> putStrLn prognameandversion -- _ | boolopt "binary-filename" rawopts -> putStrLn (binaryfilename progname) _ -> withJournal copts' (runBrickUi opts) when (ghcDebugMode == GDPauseAtEnd) $ ghcDebugPause' runBrickUi :: UIOpts -> Journal -> IO () runBrickUi uopts0@UIOpts{uoCliOpts=copts@CliOpts{inputopts_=_iopts,reportspec_=rspec@ReportSpec{_rsReportOpts=ropts}}} j = do let today = copts^.rsDay -- hledger-ui's query handling is currently in flux, mixing old and new approaches. -- Related: #1340, #1383, #1387. Some notes and terminology: -- The *startup query* is the Query generated at program startup, from -- command line options, arguments, and the current date. hledger CLI -- uses this. -- hledger-ui/hledger-web allow the query to be changed at will, creating -- a new *runtime query* each time. -- The startup query or part of it can be used as a *constraint query*, -- limiting all runtime queries. hledger-web does this with the startup -- report period, never showing transactions outside those dates. -- hledger-ui does not do this. -- A query is a combination of multiple subqueries/terms, which are -- generated from command line options and arguments, ui/web app runtime -- state, and/or the current date. -- Some subqueries are generated by parsing freeform user input, which -- can fail. We don't want hledger users to see such failures except: -- 1. at program startup, in which case the program exits -- 2. after entering a new freeform query in hledger-ui/web, in which case -- the change is rejected and the program keeps running -- So we should parse those kinds of subquery only at those times. Any -- subqueries which do not require parsing can be kept separate. And -- these can be combined to make the full query when needed, eg when -- hledger-ui screens are generating their data. (TODO) -- Some parts of the query are also kept separate for UI reasons. -- hledger-ui provides special UI for controlling depth (number keys), -- the report period (shift arrow keys), realness/status filters (RUPC keys) etc. -- There is also a freeform text area for extra query terms (/ key). -- It's cleaner and less conflicting to keep the former out of the latter. uopts = uopts0{ uoCliOpts=copts{ reportspec_=rspec{ _rsQuery=filteredQuery $ _rsQuery rspec, -- query with depth/date parts removed _rsReportOpts=ropts{ depth_ = queryDepth $ _rsQuery rspec, -- query's depth part period_ = periodfromoptsandargs, -- query's date part no_elide_ = True, -- avoid squashing boring account names, for a more regular tree (unlike hledger) empty_ = not $ empty_ ropts, -- show zero items by default, hide them with -E (unlike hledger) declared_ = True -- always show declared accounts even if unused } } } } where datespanfromargs = queryDateSpan (date2_ ropts) $ _rsQuery rspec periodfromoptsandargs = dateSpanAsPeriod $ spansIntersect [periodAsDateSpan $ period_ ropts, datespanfromargs] filteredQuery q = simplifyQuery $ And [queryFromFlags ropts, filtered q] where filtered = filterQuery (\x -> not $ queryIsDepth x || queryIsDate x) -- Choose the initial screen to display. -- We also set up a stack of previous screens, as if you had navigated down to it from the top. -- Note the previous screens list is ordered nearest-first, with the top-most (menu) screen last. -- Keep all of this synced with msNew. rawopts = rawopts_ $ uoCliOpts $ uopts (prevscrs, currscr) = dbg1With (showScreenStack "initial" showScreenSelection . uncurry2 (uiState defuiopts nulljournal)) $ if -- An accounts screen is specified. Its previous screen will be the menu screen with it selected. | boolopt "cash" rawopts -> ([msSetSelectedScreen csItemIndex menuscr], csacctsscr) | boolopt "bs" rawopts -> ([msSetSelectedScreen bsItemIndex menuscr], bsacctsscr) | boolopt "is" rawopts -> ([msSetSelectedScreen isItemIndex menuscr], isacctsscr) | boolopt "all" rawopts -> ([msSetSelectedScreen asItemIndex menuscr], allacctsscr) -- A register screen is specified with --register=ACCT. The initial screen stack will be: -- -- menu screen, with ACCTSSCR selected -- ACCTSSCR (the accounts screen containing ACCT), with ACCT selected -- register screen for ACCT -- | Just apat <- uoRegister uopts -> let -- the account being requested acct = fromMaybe (error' $ "--register "++apat++" did not match any account") -- PARTIAL: . firstMatch $ journalAccountNamesDeclaredOrImplied j where firstMatch = case toRegexCI $ T.pack apat of Right re -> find (regexMatchText re) Left _ -> const Nothing -- the register screen for acct regscr = rsSetAccount acct False $ rsNew uopts today j acct forceinclusive where forceinclusive = case getDepth ui of Just de -> accountNameLevel acct >= de Nothing -> False -- The accounts screen containing acct. -- Keep these selidx values synced with the menu items in msNew. (acctsscr, selidx) = case journalAccountType j acct of Just t | isBalanceSheetAccountType t -> (bsacctsscr, 1) Just t | isIncomeStatementAccountType t -> (isacctsscr, 2) _ -> (allacctsscr,0) & first (asSetSelectedAccount acct) -- the menu screen menuscr' = msSetSelectedScreen selidx menuscr in ([acctsscr, menuscr'], regscr) -- Otherwise, start on the menu screen. | otherwise -> ([], menuscr) where menuscr = msNew allacctsscr = asNew uopts today j Nothing csacctsscr = csNew uopts today j Nothing bsacctsscr = bsNew uopts today j Nothing isacctsscr = isNew uopts today j Nothing ui = uiState uopts j prevscrs currscr app = brickApp (uoTheme uopts) -- print (length (show ui)) >> exitSuccess -- show any debug output to this point & quit let -- helper: make a Vty terminal controller with mouse support enabled makevty = do v <- mkVty mempty setMode (outputIface v) Mouse True return v if not (uoWatch uopts) then do vty <- makevty void $ customMain vty makevty Nothing app 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 -- run this small task asynchronously: (getCurrentDay >>= watchDate) -- until this main task terminates: $ \_async -> -- 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 files <- mapM (canonicalizePath . fst) $ jfiles j let directories = nubSort $ map takeDirectory files dbg1IO "files" files dbg1IO "directories to watch" directories forM_ directories $ \d -> watchDir mgr d -- predicate: ignore changes not involving our files (\case Added f _ IsFile -> f `elem` files -- for editors which write the whole file from scratch on saves Modified f _ IsFile -> f `elem` files -- for editors which modify existing files in place -- 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. (XXX makevty too ?) vty <- makevty void $ customMain vty makevty (Just eventChan) app ui brickApp :: Maybe String -> App UIState AppEvent Name brickApp mtheme = App { appStartEvent = return () , appAttrMap = const $ fromMaybe defaultTheme $ getTheme =<< mtheme , appChooseCursor = showFirstCursor , appHandleEvent = uiHandle , appDraw = uiDraw } uiHandle :: BrickEvent Name AppEvent -> EventM Name UIState () uiHandle ev = do dbguiEv $ "\n==== " ++ show ev ui <- get case aScreen ui of MS _ -> msHandle ev AS _ -> asHandle ev CS _ -> csHandle ev BS _ -> bsHandle ev IS _ -> isHandle ev RS _ -> rsHandle ev TS _ -> tsHandle ev ES _ -> esHandle ev uiDraw :: UIState -> [Widget Name] uiDraw ui = case aScreen ui of MS _ -> msDraw ui AS _ -> asDraw ui CS _ -> csDraw ui BS _ -> bsDraw ui IS _ -> isDraw ui RS _ -> rsDraw ui TS _ -> tsDraw ui ES _ -> esDraw ui hledger-ui-1.50.3/Hledger/UI/Theme.hs0000644000000000000000000001716515107137141015312 0ustar0000000000000000-- | The all-important theming engine! -- -- Cf -- https://hackage.haskell.org/package/vty/docs/Graphics-Vty-Attributes.html -- http://hackage.haskell.org/package/brick/docs/Brick-AttrMap.html -- http://hackage.haskell.org/package/brick-0.1/docs/Brick-Util.html -- http://hackage.haskell.org/package/brick-0.1/docs/Brick-Widgets-Core.html#g:5 -- http://hackage.haskell.org/package/brick-0.1/docs/Brick-Widgets-Border.html {-# LANGUAGE OverloadedStrings #-} module Hledger.UI.Theme ( defaultTheme ,getTheme ,themes ,themeNames ) where import Data.Map qualified as M import Data.Maybe import Graphics.Vty import Brick import Safe (headErr) defaultTheme :: AttrMap defaultTheme = fromMaybe (snd $ headErr themesList) $ getTheme "white" -- PARTIAL headErr succeeds because themesList is non-null -- 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) [ (attrName "border" , white `on` black & dim) ,(attrName "border" <> attrName "bold" , currentAttr & bold) ,(attrName "border" <> attrName "depth" , active) ,(attrName "border" <> attrName "filename" , currentAttr) ,(attrName "border" <> attrName "key" , active) ,(attrName "border" <> attrName "minibuffer" , white `on` black & bold) ,(attrName "border" <> attrName "query" , active) ,(attrName "border" <> attrName "selected" , active) ,(attrName "error" , fg red) ,(attrName "help" , white `on` black & dim) ,(attrName "help" <> attrName "heading" , fg yellow) ,(attrName "help" <> attrName "key" , active) -- ,(attrName "list" , black `on` white) -- ,(attrName "list" <> attrName "amount" , currentAttr) ,(attrName "list" <> attrName "amount" <> attrName "decrease" , fg red) -- ,(attrName "list" <> attrName "amount" <> attrName "increase" , fg green) ,(attrName "list" <> attrName "amount" <> attrName "decrease" <> attrName "selected" , red `on` selectbg & bold) -- ,(attrName "list" <> attrName "amount" <> attrName "increase" <> attrName "selected" , green `on` selectbg & bold) ,(attrName "list" <> attrName "balance" , currentAttr & bold) ,(attrName "list" <> attrName "balance" <> attrName "negative" , fg red) ,(attrName "list" <> attrName "balance" <> attrName "positive" , fg black) ,(attrName "list" <> attrName "balance" <> attrName "negative" <> attrName "selected" , red `on` selectbg & bold) ,(attrName "list" <> attrName "balance" <> attrName "positive" <> attrName "selected" , select & bold) ,(attrName "list" <> attrName "selected" , select) -- ,(attrName "list" <> attrName "accounts" , white `on` brightGreen) -- ,(attrName "list" <> attrName "selected" , black `on` brightYellow) ]) ,("greenterm", attrMap (green `on` black) [ (attrName "list" <> attrName "selected" , black `on` green) ]) ,("terminal", attrMap defAttr [ (attrName "border" , white `on` black), (attrName "list" , defAttr), (attrName "list" <> attrName "selected" , defAttr & reverseVideo) ]) ,("dark", attrMap (white `on` black & dim) [ (attrName "border" , white `on` black) , (attrName "border" <> attrName "bold" , currentAttr & bold) , (attrName "border" <> attrName "depth" , active) , (attrName "border" <> attrName "filename" , currentAttr) , (attrName "border" <> attrName "key" , active) , (attrName "border" <> attrName "minibuffer" , white `on` black & bold) , (attrName "border" <> attrName "query" , active) , (attrName "border" <> attrName "selected" , active) , (attrName "error" , fg red) , (attrName "help" , currentAttr & bold) , (attrName "help" <> attrName "heading" , fg blue) , (attrName "help" <> attrName "key" , active) , (attrName "list" <> attrName "amount" <> attrName "decrease" , fg red) , (attrName "list" <> attrName "amount" <> attrName "decrease" <> attrName "selected" , red `on` black & bold) , (attrName "list" <> attrName "balance" , currentAttr) , (attrName "list" <> attrName "balance" <> attrName "negative" , fg red) , (attrName "list" <> attrName "balance" <> attrName "positive" , fg white) , (attrName "list" <> attrName "balance" <> attrName "negative" <> attrName "selected" , red `on` black & bold) , (attrName "list" <> attrName "balance" <> attrName "positive" <> attrName "selected" , yellow `on` black & bold) , (attrName "list" <> attrName "selected" , yellow `on` black & bold) ]) ] -- 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.50.3/Hledger/UI/UIOptions.hs0000644000000000000000000001221315107137141016126 0ustar0000000000000000{-# LANGUAGE CPP #-} {-# LANGUAGE TemplateHaskell #-} module Hledger.UI.UIOptions where import Data.Default (def) import Data.Either (fromRight) import Data.List (intercalate) import Data.Map qualified as M import Data.Maybe (fromMaybe) import GitHash (tGitInfoCwdTry) import Lens.Micro (set) import System.Environment (getArgs) import Hledger.Cli hiding (packageversion, progname, prognameandversion) import Hledger.UI.Theme (themes, themeNames) -- cf Hledger.Cli.Version packageversion :: PackageVersionString packageversion = #ifdef VERSION VERSION #else "" #endif progname :: ProgramName progname = "hledger-ui" -- | Generate the version string for this program. -- The template haskell call is here rather than in Hledger.Cli.Version to avoid wasteful recompilation. prognameandversion :: String prognameandversion = versionStringWith $$tGitInfoCwdTry #ifdef GHCDEBUG True #else False #endif progname packageversion binaryinfo :: HledgerBinaryInfo binaryinfo = fromRight nullbinaryinfo $ parseHledgerVersion prognameandversion uiflags = [ flagNone ["watch","w"] (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++")") ,flagNone ["cash"] (setboolopt "cash") "start in: the cash accounts screen" ,flagNone ["bs"] (setboolopt "bs") "start in: the balance sheet accounts screen" ,flagNone ["is"] (setboolopt "is") "start in: the income statement accounts screen" ,flagNone ["all"] (setboolopt "all") "start in: the all accounts screen" ,flagReq ["register"] (\s opts -> Right $ setopt "register" s opts) "ACCTREGEX" "start in: the (first matched) account's register" ,flagNone ["change"] (setboolopt "change") "show period balances (changes) at startup instead of historical balances" -- ,flagNone ["cumulative"] (setboolopt "cumulative") -- "show balance change accumulated across periods (in multicolumn reports)" -- ,flagNone ["historical","H"] (setboolopt "historical") -- "show historical ending balance in each period (includes postings before report start date)\n " ] ++ flattreeflags False -- ,flagNone ["present"] (setboolopt "present") "exclude transactions dated later than today (default)" -- ,flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "with --flat, omit this many leading account name components" -- ,flagReq ["format"] (\s opts -> Right $ setopt "format" s opts) "FORMATSTR" "use this custom line format" -- ,flagNone ["no-elide"] (setboolopt "no-elide") "don't compress empty parent accounts on one line" --uimode :: Mode RawOpts uimode = (mode "hledger-ui" (setopt "command" "ui" def) "browse accounts, postings and entries in a full-window TUI" (argsFlag "[--cash|--bs|--is|--all|--register=ACCT] [QUERY]") []) {modeGroupFlags = Group { groupUnnamed = uiflags ,groupHidden = hiddenflags ++ [flagNone ["future"] (setboolopt "forecast") "old flag, use --forecast instead" ,flagNone ["menu"] (setboolopt "menu") "old flag, menu screen is now the default" ] ,groupNamed = mkgeneralflagsgroups1 helpflags } ,modeHelpSuffix=[ -- "Reads your ~/.hledger.journal file, or another specified by $LEDGER_FILE or -f, and starts the full-window TUI." ] } -- hledger-ui options, used in hledger-ui and above data UIOpts = UIOpts { uoWatch :: Bool , uoTheme :: Maybe String , uoRegister :: Maybe String , uoCliOpts :: CliOpts } deriving (Show) defuiopts = UIOpts { uoWatch = False , uoTheme = Nothing , uoRegister = Nothing , uoCliOpts = defcliopts } -- | Process a RawOpts into a UIOpts. -- An invalid --theme name will raise an error. rawOptsToUIOpts :: RawOpts -> IO UIOpts rawOptsToUIOpts rawopts = do cliopts <- set balanceaccum accum <$> rawOptsToCliOpts rawopts return defuiopts { uoWatch = boolopt "watch" rawopts ,uoTheme = checkTheme <$> maybestringopt "theme" rawopts ,uoRegister = maybestringopt "register" rawopts ,uoCliOpts = cliopts } where -- show historical balance by default (unlike hledger) accum = fromMaybe Historical $ balanceAccumulationOverride rawopts checkTheme t = if t `M.member` themes then t else usageError $ "invalid theme name: " ++ t -- XXX some refactoring seems due getHledgerUIOpts :: IO UIOpts --getHledgerUIOpts = processArgs uimode >>= return >>= rawOptsToUIOpts getHledgerUIOpts = do args <- getArgs >>= expandArgsAt let args' = ensureDebugFlagHasVal $ replaceNumericFlags args let cmdargopts = either usageError id $ process uimode args' rawOptsToUIOpts cmdargopts instance HasCliOpts UIOpts where cliOpts f uiopts = (\x -> uiopts{uoCliOpts=x}) <$> f (uoCliOpts uiopts) instance HasInputOpts UIOpts where inputOpts = cliOpts.inputOpts instance HasBalancingOpts UIOpts where balancingOpts = cliOpts.balancingOpts instance HasReportSpec UIOpts where reportSpec = cliOpts.reportSpec instance HasReportOptsNoUpdate UIOpts where reportOptsNoUpdate = cliOpts.reportOptsNoUpdate instance HasReportOpts UIOpts where reportOpts = cliOpts.reportOpts hledger-ui-1.50.3/Hledger/UI/AccountsScreen.hs0000644000000000000000000005047715107137141017172 0ustar0000000000000000-- The accounts screen, showing accounts and balances like the CLI balance command. {-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} module Hledger.UI.AccountsScreen (asNew ,asUpdate ,asDraw ,asDrawHelper ,asHandle ,handleHelpMode ,handleMinibufferMode ,asHandleNormalMode ,enterRegisterScreen ,asSetSelectedAccount ) where import Brick import Brick.Widgets.List import Brick.Widgets.Edit import Control.Monad import Control.Monad.IO.Class (liftIO) #if MIN_VERSION_base(4,19,0) import Data.List hiding (reverse, (!?)) #else import Data.List hiding (reverse) #endif import Data.Maybe import Data.Text qualified as T import Data.Time.Calendar (Day) import Data.Vector qualified as V import Data.Vector ((!?)) import Graphics.Vty (Event(..),Key(..),Modifier(..), Button (BLeft, BScrollDown, BScrollUp)) import Lens.Micro.Platform import System.Console.ANSI import System.FilePath (takeFileName) import Text.DocLayout (realLength) import Hledger import Hledger.Cli hiding (Mode, mode, progname, prognameandversion) import Hledger.UI.UIOptions import Hledger.UI.UITypes import Hledger.UI.UIState import Hledger.UI.UIUtils import Hledger.UI.UIScreens import Hledger.UI.Editor import Hledger.UI.ErrorScreen (uiReload, uiReloadIfFileChanged, uiToggleBalanceAssertions) import Hledger.UI.RegisterScreen (rsCenterSelection) import Data.Either (fromRight) import Control.Arrow ((>>>)) import Safe (headDef) asDraw :: UIState -> [Widget Name] asDraw ui = dbgui "asDraw" $ asDrawHelper ui ropts' scrname where ropts' = _rsReportOpts $ reportspec_ $ uoCliOpts $ aopts ui scrname = "account " ++ if ishistorical then "balances" else "changes" where ishistorical = balanceaccum_ ropts' == Historical -- | Help draw any accounts-like screen (all accounts, balance sheet, income statement..). -- The provided ReportOpts are used instead of the ones in the UIState. -- The other argument is the screen display name. asDrawHelper :: UIState -> ReportOpts -> String -> [Widget Name] asDrawHelper UIState{aScreen=scr, aopts=uopts, ajournal=j, aMode=mode} ropts scrname = dbgui "asDrawHelper" $ case toAccountsLikeScreen scr of Nothing -> dbgui "asDrawHelper" $ errorWrongScreenType "asDrawHelper" -- PARTIAL: Just (ALS _ ass) -> case mode of Help -> [helpDialog, maincontent] _ -> [maincontent] where UIOpts{uoCliOpts=copts} = uopts 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 = ass ^. assList . listElementsL acctwidths = V.map (\AccountsScreenItem{..} -> asItemIndentLevel + realLength asItemDisplayAccountName) displayitems balwidths = V.map (maybe 0 (wbWidth . showMixedAmountB oneLineNoCostFmt) . asItemMixedAmount) displayitems preferredacctwidth = V.maximum acctwidths totalacctwidthseen = V.sum acctwidths preferredbalwidth = V.maximum balwidths totalbalwidthseen = V.sum balwidths totalwidthseen = totalacctwidthseen + totalbalwidthseen shortfall = preferredacctwidth + preferredbalwidth + 2 - availwidth acctwidthproportion = fromIntegral totalacctwidthseen / fromIntegral totalwidthseen adjustedacctwidth = min preferredacctwidth . max 15 . round $ acctwidthproportion * fromIntegral (availwidth - 2) -- leave 2 whitespace for padding adjustedbalwidth = availwidth - 2 - adjustedacctwidth -- XXX how to minimise the balance column's jumping around as you change the depth limit ? colwidths | shortfall <= 0 = (preferredacctwidth, preferredbalwidth) | otherwise = (adjustedacctwidth, adjustedbalwidth) render $ defaultLayout toplabel bottomlabel $ renderList (asDrawItem colwidths) True (ass ^. assList) where ishistorical = balanceaccum_ ropts == Historical toplabel = withAttr (attrName "border" <> attrName "filename") files <+> toggles <+> str (" " ++ scrname) <+> borderPeriodStr (if ishistorical then "at end of" else "in") (period_ ropts) <+> borderQueryStr (T.unpack . T.unwords . map textQuoteIfNeeded $ querystring_ ropts) <+> borderDepthStr mdepth <+> str (" ("++curidx++"/"++totidx++")") <+> (if ignore_assertions_ . balancingopts_ $ inputopts_ copts then withAttr (attrName "border" <> attrName "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 (attrName "border" <> attrName "query") $ str $ unwords $ concat [ [""] ,if empty_ ropts then [] else ["nonzero"] ,uiShowStatus copts $ statuses_ ropts ,if real_ ropts then ["real"] else [] ] mdepth = dsFlatDepth $ depth_ ropts curidx = case ass ^. assList . listSelectedL of Nothing -> "-" Just i -> show (i + 1) totidx = show $ V.length nonblanks where nonblanks = V.takeWhile (not . T.null . asItemAccountName) $ ass ^. assList . listElementsL bottomlabel = case mode of Minibuffer label ed -> minibuffer label ed _ -> quickhelp where quickhelp = borderKeysStr' [ ("LEFT", str "back") -- ,("RIGHT", str "register") ,("t", renderToggle (tree_ ropts) "list" "tree") -- ,("t", str "tree") -- ,("l", str "list") ,("-+", str "depth") ,case scr of BS _ -> ("", str "") IS _ -> ("", str "") _ -> ("H", renderToggle (not ishistorical) "end-bals" "changes") ,("F", renderToggle1 (isJust . forecast_ $ inputopts_ copts) "forecast") --,("/", "filter") --,("DEL", "unfilter") --,("ESC", "cancel/top") -- ,("a", str "add") -- ,("g", "reload") ,("?", str "help") -- ,("q", str "quit") ] 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 $ txt (fitText (Just acctwidth) (Just acctwidth) True True $ T.replicate (asItemIndentLevel) " " <> asItemDisplayAccountName) <+> txt balspace <+> splitAmounts balBuilder where balBuilder = maybe mempty showamt asItemMixedAmount showamt = showMixedAmountB oneLineNoCostFmt{displayMinWidth=Just balwidth, displayMaxWidth=Just balwidth} balspace = T.replicate (2 + balwidth - wbWidth balBuilder) " " splitAmounts = foldr1 (<+>) . intersperse (str ", ") . map renderamt . T.splitOn ", " . wbToText renderamt :: T.Text -> Widget Name renderamt a | T.any (=='-') a = withAttr (sel $ attrName "list" <> attrName "balance" <> attrName "negative") $ txt a | otherwise = withAttr (sel $ attrName "list" <> attrName "balance" <> attrName "positive") $ txt a sel | selected = (<> attrName "selected") | otherwise = id -- | Handle events on any accounts-like screen (all accounts, balance sheet, income statement..). asHandle :: BrickEvent Name AppEvent -> EventM Name UIState () asHandle ev = do dbguiEv "asHandle" ui0@UIState{aScreen=scr, aMode=mode} <- get' case toAccountsLikeScreen scr of Nothing -> dbgui "asHandle" $ errorWrongScreenType "asHandle" -- PARTIAL: Just als@(ALS scons ass) -> do -- save the currently selected account, in case we leave this screen and lose the selection put' ui0{aScreen=scons ass{_assSelectedAccount=asSelectedAccount ass}} case mode of Normal -> asHandleNormalMode als ev Minibuffer _ ed -> handleMinibufferMode ed ev Help -> handleHelpMode ev -- | Handle events when in normal mode on any accounts-like screen. -- The provided AccountsLikeScreen should correspond to the ui state's current screen. asHandleNormalMode :: AccountsLikeScreen -> BrickEvent Name AppEvent -> EventM Name UIState () asHandleNormalMode (ALS scons ass) ev = do dbguiEv "asHandleNormalMode" ui@UIState{aopts=UIOpts{uoCliOpts=copts}, ajournal=j} <- get' d <- liftIO getCurrentDay let l = _assList ass selacct = asSelectedAccount ass centerSelection = scrollSelectionToMiddle l clickedAcctAt y = case asItemAccountName <$> listElements l !? y of Just t | not $ T.null t -> Just t _ -> Nothing nonblanks = V.takeWhile (not . T.null . asItemAccountName) $ listElements l lastnonblankidx = max 0 (length nonblanks - 1) journalspan = journalDateSpan False j case ev of VtyEvent (EvKey (KChar 'q') []) -> halt -- q: quit VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui -- C-z: suspend VtyEvent (EvKey (KChar 'l') [MCtrl]) -> centerSelection >> redraw -- C-l: redraw VtyEvent (EvKey KEsc []) -> modify' (resetScreens d) -- ESC: reset VtyEvent (EvKey (KChar c) []) | c == '?' -> modify' (setMode Help) -- ?: enter help mode -- AppEvents come from the system, in --watch mode. -- XXX currently they are handled only in Normal mode -- XXX be sure we don't leave unconsumed app events piling up -- A data file has changed (or the user has pressed g): reload. e | e `elem` [AppEvent FileChange, VtyEvent (EvKey (KChar 'g') [])] -> uiReload copts d ui >>= put' -- The date has changed (and we are viewing a standard period which contained the old date): -- adjust the viewed period and regenerate, just in case needed. -- (Eg: when watching data for "today" and the time has just passed midnight.) AppEvent (DateChange old _) | isStandardPeriod p && p `periodContainsDate` old -> modify' (setReportPeriod (DayPeriod d) >>> regenerateScreens j d) where p = reportPeriod ui -- set or reset a filter: VtyEvent (EvKey (KChar '/') []) -> modify' (showMinibuffer "filter" Nothing >>> regenerateScreens j d) VtyEvent (EvKey k []) | k `elem` [KBS, KDel] -> modify' (resetFilter >>> regenerateScreens j d) -- run external programs: VtyEvent (EvKey (KChar 'a') []) -> suspendAndResume $ clearScreen >> setCursorPosition 0 0 >> add (cliOptsDropArgs copts) j >> uiReloadIfFileChanged copts d j ui VtyEvent (EvKey (KChar 'A') []) -> suspendAndResume $ void (runIadd (journalFilePath j)) >> uiReloadIfFileChanged copts d j ui VtyEvent (EvKey (KChar 'E') []) -> suspendAndResume $ void (runEditor endPosition (journalFilePath j)) >> uiReloadIfFileChanged copts d j ui -- adjust the period displayed: VtyEvent (EvKey (KChar 'T') []) -> modify' (setReportPeriod (DayPeriod d) >>> regenerateScreens j d) VtyEvent (EvKey (KDown) [MShift]) -> modify' (shrinkReportPeriod d >>> regenerateScreens j d) VtyEvent (EvKey (KUp) [MShift]) -> modify' (growReportPeriod d >>> regenerateScreens j d) VtyEvent (EvKey (KRight) [MShift]) -> modify' (nextReportPeriod journalspan >>> regenerateScreens j d) VtyEvent (EvKey (KLeft) [MShift]) -> modify' (previousReportPeriod journalspan >>> regenerateScreens j d) -- various toggles and settings: VtyEvent (EvKey (KChar 'I') []) -> get' >>= uiToggleBalanceAssertions d VtyEvent (EvKey (KChar 'F') []) -> modify' (toggleForecast d >>> regenerateScreens j d) VtyEvent (EvKey (KChar 'B') []) -> modify' (toggleConversionOp >>> regenerateScreens j d) VtyEvent (EvKey (KChar 'V') []) -> modify' (toggleValue >>> regenerateScreens j d) VtyEvent (EvKey (KChar '0') []) -> modify' (setDepth (Just 0) >>> regenerateScreens j d) VtyEvent (EvKey (KChar '1') []) -> modify' (setDepth (Just 1) >>> regenerateScreens j d) VtyEvent (EvKey (KChar '2') []) -> modify' (setDepth (Just 2) >>> regenerateScreens j d) VtyEvent (EvKey (KChar '3') []) -> modify' (setDepth (Just 3) >>> regenerateScreens j d) VtyEvent (EvKey (KChar '4') []) -> modify' (setDepth (Just 4) >>> regenerateScreens j d) VtyEvent (EvKey (KChar '5') []) -> modify' (setDepth (Just 5) >>> regenerateScreens j d) VtyEvent (EvKey (KChar '6') []) -> modify' (setDepth (Just 6) >>> regenerateScreens j d) VtyEvent (EvKey (KChar '7') []) -> modify' (setDepth (Just 7) >>> regenerateScreens j d) VtyEvent (EvKey (KChar '8') []) -> modify' (setDepth (Just 8) >>> regenerateScreens j d) VtyEvent (EvKey (KChar '9') []) -> modify' (setDepth (Just 9) >>> regenerateScreens j d) VtyEvent (EvKey (KChar c) []) | c `elem` ['-','_'] -> modify' (decDepth >>> regenerateScreens j d) VtyEvent (EvKey (KChar c) []) | c `elem` ['+','='] -> modify' (incDepth >>> regenerateScreens j d) -- toggles after which the selection should be recentered: VtyEvent (EvKey (KChar 'H') []) -> modify' (toggleHistorical >>> regenerateScreens j d) >> centerSelection -- harmless on BS/IS screens VtyEvent (EvKey (KChar 't') []) -> modify' (toggleTree >>> regenerateScreens j d) >> centerSelection VtyEvent (EvKey (KChar 'R') []) -> modify' (toggleReal >>> regenerateScreens j d) >> centerSelection VtyEvent (EvKey (KChar 'U') []) -> modify' (toggleUnmarked >>> regenerateScreens j d) >> centerSelection VtyEvent (EvKey (KChar 'P') []) -> modify' (togglePending >>> regenerateScreens j d) >> centerSelection VtyEvent (EvKey (KChar 'C') []) -> modify' (toggleCleared >>> regenerateScreens j d) >> centerSelection VtyEvent (EvKey (KChar c) []) | c `elem` ['z','Z'] -> modify' (toggleEmpty >>> regenerateScreens j d) >> centerSelection -- back compat: accept Z as well as z -- LEFT key or a click in the app's left margin: exit to the parent screen. VtyEvent e | e `elem` moveLeftEvents -> modify' popScreen VtyEvent (EvMouseUp 0 _ (Just BLeft)) -> modify' popScreen -- this mouse click is a VtyEvent since not in a clickable widget -- RIGHT key or MouseUp on an account: enter the register screen for the selected account VtyEvent e | e `elem` moveRightEvents, not $ isBlankItem $ listSelectedElement l -> enterRegisterScreen d selacct ui MouseUp _n (Just BLeft) Location{loc=(_,y)} | Just clkacct <- clickedAcctAt y -> enterRegisterScreen d clkacct ui -- MouseDown: this is not debounced and can repeat (https://github.com/jtdaugherty/brick/issues/347) -- so we only let it do something harmless: move the selection. MouseDown _n BLeft _mods Location{loc=(_,y)} | not $ isBlankItem clickeditem -> put' ui{aScreen=scons ass'} where clickeditem = (0,) <$> listElements l !? y ass' = ass{_assList=listMoveTo y l} -- Mouse scroll wheel: scroll up or down to the maximum extent, pushing the selection when necessary. MouseDown name btn _mods _loc | btn `elem` [BScrollUp, BScrollDown] -> do let scrollamt = if btn==BScrollUp then -1 else 1 l' <- nestEventM' l $ listScrollPushingSelection name (asListSize l) scrollamt put' ui{aScreen=scons ass{_assList=l'}} -- PGDOWN/END keys: handle with List's default handler, but restrict the selection to stop -- (and center) at the last non-blank item. VtyEvent e@(EvKey k []) | k `elem` [KPageDown, KEnd] -> do l1 <- nestEventM' l $ handleListEvent e if isBlankItem $ listSelectedElement l1 then do let l2 = listMoveTo lastnonblankidx l1 scrollSelectionToMiddle l2 put' ui{aScreen=scons ass{_assList=l2}} else put' ui{aScreen=scons ass{_assList=l1}} -- DOWN key when selection is at the last item: scroll instead of moving, until maximally scrolled VtyEvent e | e `elem` moveDownEvents, isBlankItem mnextelement -> vScrollBy (viewportScroll $ l^.listNameL) 1 where mnextelement = listSelectedElement $ listMoveDown l -- Any other vty event (UP, DOWN, PGUP etc): handle with List's default handler. VtyEvent e -> do l' <- nestEventM' l $ handleListEvent (normaliseMovementKeys e) put' ui{aScreen=scons $ ass & assList .~ l' & assSelectedAccount .~ selacct} -- Any other mouse/app event: ignore MouseDown{} -> return () MouseUp{} -> return () AppEvent _ -> return () -- | Handle events when in minibuffer mode on any screen. handleMinibufferMode ed ev = do ui@UIState{ajournal=j} <- get' d <- liftIO getCurrentDay case ev of VtyEvent (EvKey KEsc []) -> put' $ closeMinibuffer ui VtyEvent (EvKey KEnter []) -> put' $ regenerateScreens j d ui' where ui' = setFilter s (closeMinibuffer ui) & fromRight (showMinibuffer "Cannot compile regular expression" (Just s) ui) where s = chomp $ unlines $ map strip $ getEditContents ed VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui VtyEvent e -> do ed' <- nestEventM' ed $ handleEditorEvent (VtyEvent e) put' ui{aMode=Minibuffer "filter" ed'} AppEvent _ -> return () MouseDown{} -> return () MouseUp{} -> return () -- | Handle events when in help mode on any screen. handleHelpMode ev = do ui <- get' case ev of -- VtyEvent (EvKey (KChar 'q') []) -> halt VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui _ -> helpHandle ev enterRegisterScreen :: Day -> AccountName -> UIState -> EventM Name UIState () enterRegisterScreen d acct ui@UIState{ajournal=j, aopts=uopts} = do dbguiEv "enterRegisterScreen" let regscr = rsNew uopts d j acct isdepthclipped where isdepthclipped = case getDepth ui of Just de -> accountNameLevel acct >= de Nothing -> False ui1 = pushScreen regscr ui rsCenterSelection ui1 >>= put' -- | From any accounts screen's state, get the account name from the -- currently selected list item, or otherwise the last known selected account name. asSelectedAccount :: AccountsScreenState -> AccountName asSelectedAccount ass = case listSelectedElement $ _assList ass of Just (_, AccountsScreenItem{..}) -> asItemAccountName Nothing -> ass ^. assSelectedAccount -- | Set the selected account on any of the accounts screens. Has no effect on other screens. -- Sets the high-level property _assSelectedAccount and also selects the corresponding or -- best alternative item in the list widget (_assList). asSetSelectedAccount :: AccountName -> Screen -> Screen asSetSelectedAccount acct scr = case scr of (AS ass) -> AS $ assSetSelectedAccount acct ass (BS ass) -> BS $ assSetSelectedAccount acct ass (IS ass) -> IS $ assSetSelectedAccount acct ass _ -> scr where assSetSelectedAccount a ass@ASS{_assList=l} = ass{_assSelectedAccount=a, _assList=listMoveTo selidx l} where -- which list item should be selected ? selidx = headDef 0 $ catMaybes [ elemIndex a as -- the specified account, if it can be found ,findIndex (a `isAccountNamePrefixOf`) as -- or the first account found with the same prefix ,Just $ max 0 (length (filter (< a) as) - 1) -- otherwise, the alphabetically preceding account. ] where as = map asItemAccountName $ V.toList $ listElements l isBlankItem mitem = ((asItemAccountName . snd) <$> mitem) == Just "" asListSize = V.length . V.takeWhile ((/="").asItemAccountName) . listElements hledger-ui-1.50.3/Hledger/UI/BalancesheetScreen.hs0000644000000000000000000000143415054060534017760 0ustar0000000000000000-- The balance sheet screen, like the accounts screen but restricted to balance sheet accounts. module Hledger.UI.BalancesheetScreen (bsNew ,bsUpdate ,bsDraw ,bsHandle ) where import Brick hiding (bsDraw) import Hledger import Hledger.Cli hiding (mode, progname, prognameandversion) import Hledger.UI.UIOptions import Hledger.UI.UITypes import Hledger.UI.UIUtils import Hledger.UI.UIScreens import Hledger.UI.AccountsScreen (asHandle, asDrawHelper) bsDraw :: UIState -> [Widget Name] bsDraw ui = dbgui "bsDraw" $ asDrawHelper ui ropts' scrname where scrname = "balance sheet balances" ropts' = (_rsReportOpts $ reportspec_ $ uoCliOpts $ aopts ui){balanceaccum_=Historical} bsHandle :: BrickEvent Name AppEvent -> EventM Name UIState () bsHandle = asHandle . dbgui "bsHandle" hledger-ui-1.50.3/Hledger/UI/CashScreen.hs0000644000000000000000000000136215054060534016260 0ustar0000000000000000-- The cash accounts screen, like the accounts screen but restricted to cash accounts. module Hledger.UI.CashScreen (csNew ,csUpdate ,csDraw ,csHandle ) where import Brick import Hledger import Hledger.Cli hiding (mode, progname, prognameandversion) import Hledger.UI.UIOptions import Hledger.UI.UITypes import Hledger.UI.UIUtils import Hledger.UI.UIScreens import Hledger.UI.AccountsScreen (asHandle, asDrawHelper) csDraw :: UIState -> [Widget Name] csDraw ui = dbgui "csDraw" $ asDrawHelper ui ropts' scrname where scrname = "cash balances" ropts' = (_rsReportOpts $ reportspec_ $ uoCliOpts $ aopts ui){balanceaccum_=Historical} csHandle :: BrickEvent Name AppEvent -> EventM Name UIState () csHandle = asHandle . dbgui "csHandle" hledger-ui-1.50.3/Hledger/UI/Editor.hs0000644000000000000000000001372315106732206015474 0ustar0000000000000000{- | Editor integration. -} module Hledger.UI.Editor ( -- TextPosition endPosition ,runEditor ,runIadd ) where import Control.Applicative ((<|>)) import Data.List (intercalate) import Data.Maybe (catMaybes) import Data.Bifunctor (bimap) import Safe import System.Environment import System.Exit import System.FilePath import System.Info (os) import System.Process import Hledger -- | A position we can move to in a text editor: a line and optional column number. -- Line number 1 or 0 means the first line. A negative line number means the last line. type TextPosition = (Int, Maybe Int) -- | The text position meaning "last line, first column". endPosition :: Maybe TextPosition endPosition = Just (-1, Nothing) -- | Run the hledger-iadd executable on the given file, blocking until it exits, -- and return the exit code; or raise an error. -- hledger-iadd is an alternative to the built-in add command. runIadd :: FilePath -> IO ExitCode runIadd f = runCommand ("hledger-iadd -f " ++ f) >>= waitForProcess -- | Run the user's preferred text editor (or try a default editor), -- on the given file, blocking until it exits, and return the exit -- code; or raise an error. If a text position is provided, the editor -- will be focussed at that position in the file, if we know how. runEditor :: Maybe TextPosition -> FilePath -> IO ExitCode runEditor mpos f = editFileAtPositionCommand mpos f >>= runCommand >>= waitForProcess -- | Get a shell command line to open the user's preferred text editor -- (or a default editor) on the given file, and to focus it at the -- given text position if one is provided and if we know how. -- -- Just ('-' : _, _) is any text position with a negative line number. -- A text position with a negative line number means the last line. -- -- Some tests: -- @ -- EDITOR program: Maybe TextPosition Command should be: -- --------------- --------------------- ------------------------------------ -- emacs Just (line, Just col) emacs +LINE:COL FILE -- Just (line, Nothing) emacs +LINE FILE -- Just ('-' : _, _) emacs FILE -f end-of-buffer -- Nothing emacs FILE -- -- emacsclient Just (line, Just col) emacsclient +LINE:COL FILE -- Just (line, Nothing) emacsclient +LINE FILE -- Just ('-' : _, _) emacsclient FILE -- Nothing emacsclient FILE -- -- nano Just (line, Just col) nano +LINE:COL FILE -- Just (line, Nothing) nano +LINE FILE -- Just ('-' : _, _) nano FILE -- Nothing nano FILE -- -- vscode Just (line, Just col) vscode --goto FILE:LINE:COL -- Just (line, Nothing) vscode --goto FILE:LINE -- Just ('-' : _, _) vscode FILE -- Nothing vscode FILE -- -- kak Just (line, Just col) kak +LINE:COL FILE -- Just (line, Nothing) kak +LINE FILE -- Just ('-' : _, _) kak +: FILE -- Nothing kak FILE -- -- vi & variants Just (line, _) vi +LINE FILE -- Just ('-' : _, _) vi + FILE -- Nothing vi FILE -- -- (other PROG) _ PROG FILE -- -- (not set) Just (line, Just col) emacsclient -a '' -nw +LINE:COL FILE -- Just (line, Nothing) emacsclient -a '' -nw +LINE FILE -- Just ('-' : _, _) emacsclient -a '' -nw FILE -- Nothing emacsclient -a '' -nw FILE -- @ -- editFileAtPositionCommand :: Maybe TextPosition -> FilePath -> IO String editFileAtPositionCommand mpos f = do cmd <- getEditCommand let editor = lowercase $ takeBaseName $ headDef "" $ words' cmd f' = singleQuoteIfNeeded f mpos' = Just . bimap show (fmap show) =<< mpos join sep = intercalate sep . catMaybes args = case editor of "emacs" -> case mpos' of Nothing -> [f'] Just ('-' : _, _) -> [f', "-f", "end-of-buffer"] Just (l, mc) -> ['+' : join ":" [Just l, mc], f'] e | e `elem` ["emacsclient", "nano"] -> case mpos' of Nothing -> [f'] Just ('-' : _, _) -> [f'] Just (l, mc) -> ['+' : join ":" [Just l, mc], f'] "vscode" -> case mpos' of Nothing -> [f'] Just ('-' : _, _) -> [f'] Just (l, mc) -> ["--goto", join ":" [Just f', Just l, mc]] "kak" -> case mpos' of Nothing -> [f'] Just ('-' : _, _) -> ["+:", f'] Just (l, mc) -> ['+' : join ":" [Just l, mc], f'] e | e `elem` ["vi", "vim", "view", "nvim", "evim", "eview", "gvim", "gview", "rvim", "rview", "rgvim", "rgview", "ex"] -> case mpos' of Nothing -> [f'] Just ('-' : _, _) -> ["+", f'] Just (l, _) -> ['+' : l, f'] -- arch linux creates a symlink to /usr/lib/helix/hx at /usr/bin/helix e | e `elem` ["hx", "helix"] -> case mpos' of Nothing -> [f'] Just ('-' : _, _) -> [f'] Just (l, _) -> ['+' : l, f'] _ -> [f'] return $ unwords $ cmd:args -- | Get the user's preferred edit command. This is the value of the -- $HLEDGER_UI_EDITOR environment variable, or of $EDITOR, or an OS-specific default. -- -- For non-windows machines that would be "emacsclient -a '' -nw", -- which starts/connects to an emacs daemon in terminal mode. -- -- For windows the default is a plain "notepad.exe" getEditCommand :: IO String getEditCommand = do hledger_ui_editor_env <- lookupEnv "HLEDGER_UI_EDITOR" editor_env <- lookupEnv "EDITOR" let defaultEditor = Just $ if os == "mingw32" then "notepad.exe" else "emacsclient -a '' -nw" let Just cmd = hledger_ui_editor_env <|> editor_env <|> defaultEditor return cmd hledger-ui-1.50.3/Hledger/UI/ErrorScreen.hs0000644000000000000000000002434315107174442016502 0ustar0000000000000000-- The error screen, showing a current error condition (such as a parse error after reloading the journal) {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -Wno-incomplete-record-updates #-} module Hledger.UI.ErrorScreen (esNew ,esUpdate ,esDraw ,esHandle ,uiCheckBalanceAssertions ,uiReload ,uiReloadIfFileChanged ,uiReloadJournal ,uiReloadJournalIfChanged ,uiToggleBalanceAssertions ) where import Brick -- import Brick.Widgets.Border ("border") import Control.Monad.IO.Class (liftIO) import Data.Time.Calendar (Day) import Data.Void (Void) import Graphics.Vty (Event(..),Key(..),Modifier(..)) import Lens.Micro ((^.)) import Safe (headMay) import Text.Megaparsec import Text.Megaparsec.Char import Hledger.Cli hiding (mode, progname,prognameandversion) import Hledger.UI.UIOptions import Hledger.UI.UITypes import Hledger.UI.UIState import Hledger.UI.UIUtils import Hledger.UI.UIScreens import Hledger.UI.Editor -- legacy aliases uiReloadJournal = uiReload uiReloadJournalIfChanged = uiReloadIfFileChanged esDraw :: UIState -> [Widget Name] esDraw UIState{aScreen=ES ESS{..} ,aMode=mode } = case mode of Help -> [helpDialog, maincontent] _ -> [maincontent] where maincontent = Widget Greedy Greedy $ do render $ defaultLayout toplabel bottomlabel $ withAttr (attrName "error") $ str $ _essError where toplabel = withAttr (attrName "border" <> attrName "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 = quickhelp -- case mode of -- Minibuffer ed -> minibuffer ed -- _ -> quickhelp where quickhelp = borderKeysStr [ ("h", "help") ,("ESC", "cancel/top") ,("E", "editor") ,("g", "reload") ,("q", "quit") ] esDraw _ = error' "draw function called with wrong screen type, should not happen" -- PARTIAL: esHandle :: BrickEvent Name AppEvent -> EventM Name UIState () esHandle ev = do ui0 <- get' case ui0 of ui@UIState{aScreen=ES ESS{..} ,aopts=UIOpts{uoCliOpts=copts} ,ajournal=j ,aMode=mode } -> case mode of Help -> case ev of VtyEvent (EvKey (KChar 'q') []) -> halt VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui _ -> helpHandle ev _ -> do d <- liftIO getCurrentDay case ev of VtyEvent (EvKey (KChar 'q') []) -> halt VtyEvent (EvKey KEsc []) -> put' $ uiCheckBalanceAssertions d $ resetScreens d ui VtyEvent (EvKey (KChar c) []) | c `elem` ['h','?'] -> put' $ setMode Help ui -- g or file change: reload the journal and rebuild app state. e | e `elem` [VtyEvent (EvKey (KChar 'g') []), AppEvent FileChange] -> esReload copts d ui -- E: run editor, reload the journal. VtyEvent (EvKey (KChar 'E') []) -> do suspendAndResume' $ do let (pos,f) = case parsewithString hledgerparseerrorpositionp _essError of Right (f',l,c) -> (Just (l, Just c),f') Left _ -> (endPosition, journalFilePath j) runEditor pos f esReloadIfFileChanged copts d j ui VtyEvent (EvKey (KChar 'I') []) -> uiToggleBalanceAssertions d (popScreen ui) VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui _ -> return () _ -> errorWrongScreenType "esHandle" where -- Reload and fully regenerate the error screen. -- XXX On an error screen below the transaction screen, this is tricky because of a current limitation of regenerateScreens. -- For now we try to work around by re-entering the transaction screen. -- This can show flicker in the UI and it's hard to handle all situations robustly. esReload copts d ui = uiReload copts d ui >>= maybeReloadErrorScreen copts d esReloadIfFileChanged copts d j ui = liftIO (uiReloadIfFileChanged copts d j ui) >>= maybeReloadErrorScreen copts d maybeReloadErrorScreen copts d ui = case headMay $ aPrevScreens ui of Just (TS _) -> do -- check balance assertions, exit to register screen, enter transaction screen, reload once more put' $ popScreen $ popScreen $ uiCheckBalanceAssertions d ui sendVtyEvents [EvKey KEnter [], EvKey (KChar 'g') []] -- XXX Might be disrupted if other events are queued ? _ -> uiReload copts d (popScreen ui) >>= put' . uiCheckBalanceAssertions d -- | 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) ] -- Defined here so it can reference the error screen: -- | Modify some input options for hledger-ui (enable --forecast). uiAdjustOpts :: UIOpts -> CliOpts -> CliOpts uiAdjustOpts uopts = enableForecast uopts -- | Reload the journal from its input files, then update the ui app state accordingly. -- This means regenerate the entire screen stack from top level down to the current screen, using the provided today-date. -- As a convenience (usually), if journal reloading fails, this enters the error screen, or if already there, updates its message. -- -- The provided cli options can influence reloading; then if reloading succeeds they are saved in the ui state, -- otherwise the UIState keeps its old options. (XXX needed for.. ?) -- -- Like at hledger-ui startup, --forecast is always enabled. -- A forecast period specified in the provided opts, or at startup, is preserved. -- uiReload :: CliOpts -> Day -> UIState -> EventM Name UIState UIState uiReload copts d ui = liftIO $ do ej <- let copts1 = uiAdjustOpts (astartupopts ui) copts in runExceptT $ journalTransform copts1 <$> journalReload copts1 -- dbg1IO "uiReload before reload" (map tdescription $ jtxns $ ajournal ui) return $ case ej of Right j -> -- dbg1 "uiReload after reload" (map tdescription $ jtxns j) $ regenerateScreens j d ui Left err -> case ui of UIState{aScreen=ES _} -> ui{aScreen=esNew err} _ -> pushScreen (esNew err) ui -- XXX GHC 9.2 warning: -- hledger-ui/Hledger/UI/ErrorScreen.hs:164:59: warning: [-Wincomplete-record-updates] -- Pattern match(es) are non-exhaustive -- In a record-update construct: -- Patterns of type ‘Screen’ not matched: -- AccountsScreen _ _ _ _ _ -- RegisterScreen _ _ _ _ _ _ -- TransactionScreen _ _ _ _ _ _ -- | Like uiReload, except it skips re-reading the journal if its file(s) have not changed -- since it was last loaded. The up app state is always updated, since the options or today-date may have changed. -- Also, this one runs in IO, suitable for suspendAndResume. uiReloadIfFileChanged :: CliOpts -> Day -> Journal -> UIState -> IO UIState uiReloadIfFileChanged copts d j ui = do ej <- let copts1 = uiAdjustOpts (astartupopts ui) copts in runExceptT $ journalReloadIfChanged copts1 d j return $ case ej of Right (j', _) -> regenerateScreens j' d ui Left err -> case aScreen ui of ES _ -> ui{aScreen=esNew err} _ -> pushScreen (esNew 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 or pivot is active, do nothing. -- (When pivot is active, assertions have already been checked on the pre-pivot journal, -- and the current post-pivot journal's account names don't match the original assertions.) uiCheckBalanceAssertions :: Day -> UIState -> UIState uiCheckBalanceAssertions _d ui@UIState{ajournal=j, aopts=UIOpts{uoCliOpts=CliOpts{inputopts_=InputOpts{pivot_=pval}}}} | ui^.ignore_assertions = ui -- user disabled checks | not (null pval) = ui -- post-pivot journal, assertions already checked pre-pivot | otherwise = case journalCheckBalanceAssertions j of Right () -> ui Left err -> case ui of UIState{aScreen=ES sst} -> ui{aScreen=ES sst{_essError=err}} _ -> pushScreen (esNew err) ui -- | Toggle ignoring balance assertions (when user presses I), and if no longer ignoring, recheck them. -- Normally the recheck is done quickly on the in-memory journal. -- But if --pivot is active, a full journal reload is done instead -- (because we can't check balance assertions after pivoting has occurred). -- In that case, this operation could be slower and could reveal other data changes (not just balance assertion failures). uiToggleBalanceAssertions :: Day -> UIState -> EventM Name UIState () uiToggleBalanceAssertions d ui@UIState{aopts=UIOpts{uoCliOpts=copts@CliOpts{inputopts_=InputOpts{pivot_=pivotval}}}} = let ui' = toggleIgnoreBalanceAssertions ui in case (ui'^.ignore_assertions, null pivotval) of (True, _) -> put' ui' -- ignoring enabled, no check needed (False, True) -> put' $ uiCheckBalanceAssertions d ui' -- unpivoted journal, can check in memory (False, False) -> uiReload copts d ui' >>= put' -- pivoted journal, must reload to check it hledger-ui-1.50.3/Hledger/UI/IncomestatementScreen.hs0000644000000000000000000000143715054060534020544 0ustar0000000000000000-- The income statement accounts screen, like the accounts screen but restricted to income statement accounts. module Hledger.UI.IncomestatementScreen (isNew ,isUpdate ,isDraw ,isHandle ) where import Brick import Hledger import Hledger.Cli hiding (mode, progname, prognameandversion) import Hledger.UI.UIOptions import Hledger.UI.UITypes import Hledger.UI.UIUtils import Hledger.UI.UIScreens import Hledger.UI.AccountsScreen (asHandle, asDrawHelper) isDraw :: UIState -> [Widget Name] isDraw ui = dbgui "isDraw" $ asDrawHelper ui ropts' scrname where scrname = "income statement changes" ropts' = (_rsReportOpts $ reportspec_ $ uoCliOpts $ aopts ui){balanceaccum_=PerPeriod} isHandle :: BrickEvent Name AppEvent -> EventM Name UIState () isHandle = asHandle . dbgui "isHandle" hledger-ui-1.50.3/Hledger/UI/MenuScreen.hs0000644000000000000000000003417015107137141016307 0ustar0000000000000000-- The menu screen, showing other screens available in hledger-ui. {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Hledger.UI.MenuScreen (msNew ,msUpdate ,msDraw ,msHandle ,msSetSelectedScreen ) where import Brick import Brick.Widgets.List import Control.Monad import Control.Monad.IO.Class (liftIO) import Data.Maybe import Data.Text qualified as T import Data.Time.Calendar (Day) import Data.Vector qualified as V import Data.Vector ((!?)) import Graphics.Vty (Event(..),Key(..),Modifier(..), Button (BLeft, BScrollDown, BScrollUp)) import Lens.Micro.Platform import System.Console.ANSI import System.FilePath (takeFileName) import Hledger import Hledger.Cli hiding (mode, progname, prognameandversion) import Hledger.UI.UIOptions import Hledger.UI.UITypes import Hledger.UI.UIState import Hledger.UI.UIUtils import Hledger.UI.UIScreens import Hledger.UI.ErrorScreen (uiReload, uiReloadIfFileChanged, uiToggleBalanceAssertions) import Hledger.UI.Editor (runIadd, runEditor, endPosition) import Brick.Widgets.Edit (getEditContents, handleEditorEvent) import Control.Arrow ((>>>)) msDraw :: UIState -> [Widget Name] msDraw UIState{aopts=_uopts@UIOpts{uoCliOpts=copts@CliOpts{reportspec_=_rspec@ReportSpec{_rsReportOpts=ropts}}} ,ajournal=j ,aScreen=MS sst ,aMode=mode } = dbgui "msDraw" $ case mode of Help -> [helpDialog, maincontent] _ -> [maincontent] where maincontent = Widget Greedy Greedy $ do render $ defaultLayout toplabel bottomlabel $ renderList msDrawItem True (sst ^. mssList) where toplabel = withAttr (attrName "border" <> attrName "filename") files <+> borderPeriodStr "" (period_ ropts) <+> (if ignore_assertions_ . balancingopts_ $ inputopts_ copts then withAttr (attrName "border" <> attrName "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)") bottomlabel = case mode of Minibuffer label ed -> minibuffer label ed _ -> quickhelp where quickhelp = borderKeysStr' [ ("DOWN/UP", str "select") ,("RIGHT", str "enter screen") -- ,("t", renderToggle (tree_ ropts) "list" "tree") -- ,("t", str "tree") -- ,("l", str "list") -- ,("-+", str "depth") -- ,("H", renderToggle (not ishistorical) "end-bals" "changes") -- ,("F", renderToggle1 (isJust . forecast_ $ inputopts_ copts) "forecast") --,("/", "filter") --,("DEL", "unfilter") --,("ESC", "cancel/top") ,("a", str "add txn") -- ,("g", "reload") ,("?", str "help") ,("q", str "quit") ] msDraw _ = dbgui "msDraw" $ errorWrongScreenType "msDraw" -- PARTIAL: -- msDrawItem :: (Int,Int) -> Bool -> MenuScreenItem -> Widget Name -- msDrawItem (_acctwidth, _balwidth) _selected MenuScreenItem{..} = msDrawItem :: Bool -> MenuScreenItem -> Widget Name msDrawItem _selected MenuScreenItem{..} = Widget Greedy Fixed $ do render $ txt msItemScreenName -- XXX clean up like asHandle msHandle :: BrickEvent Name AppEvent -> EventM Name UIState () msHandle ev = do ui0 <- get' dbguiEv "msHandle" case ui0 of ui@UIState{ aopts=UIOpts{uoCliOpts=copts} ,ajournal=j ,aMode=mode ,aScreen=MS sst } -> do let -- save the currently selected account, in case we leave this screen and lose the selection mselscr = case listSelectedElement $ _mssList sst of Just (_, MenuScreenItem{..}) -> Just msItemScreen Nothing -> Nothing nonblanks = V.takeWhile (not . T.null . msItemScreenName) $ listElements $ _mssList sst lastnonblankidx = max 0 (length nonblanks - 1) journalspan = journalDateSpan False j d <- liftIO getCurrentDay case mode of Minibuffer _ ed -> case ev of VtyEvent (EvKey KEsc []) -> put' $ closeMinibuffer ui VtyEvent (EvKey KEnter []) -> put' $ regenerateScreens j d $ case setFilter s $ closeMinibuffer ui of Left bad -> showMinibuffer "Cannot compile regular expression" (Just bad) ui Right ui' -> ui' where s = chomp $ unlines $ map strip $ getEditContents ed VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui VtyEvent e -> do ed' <- nestEventM' ed $ handleEditorEvent (VtyEvent e) put' ui{aMode=Minibuffer "filter" ed'} AppEvent _ -> return () MouseDown{} -> return () MouseUp{} -> return () Help -> case ev of -- VtyEvent (EvKey (KChar 'q') []) -> halt VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui _ -> helpHandle ev Normal -> case ev of VtyEvent (EvKey (KChar 'q') []) -> halt -- EvKey (KChar 'l') [MCtrl] -> do VtyEvent (EvKey KEsc []) -> put' $ resetScreens d ui VtyEvent (EvKey (KChar c) []) | c == '?' -> put' $ 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 -> put' $ regenerateScreens j d $ setReportPeriod (DayPeriod d) ui where p = reportPeriod ui e | e `elem` [VtyEvent (EvKey (KChar 'g') []), AppEvent FileChange] -> uiReload copts d ui >>= put' VtyEvent (EvKey (KChar 'I') []) -> uiToggleBalanceAssertions d ui VtyEvent (EvKey (KChar 'a') []) -> suspendAndResume $ clearScreen >> setCursorPosition 0 0 >> add (cliOptsDropArgs copts) j >> uiReloadIfFileChanged copts d j ui VtyEvent (EvKey (KChar 'A') []) -> suspendAndResume $ void (runIadd (journalFilePath j)) >> uiReloadIfFileChanged copts d j ui VtyEvent (EvKey (KChar 'E') []) -> suspendAndResume $ void (runEditor endPosition (journalFilePath j)) >> uiReloadIfFileChanged copts d j ui -- VtyEvent (EvKey (KChar 'B') []) -> put' $ regenerateScreens j d $ toggleConversionOp ui -- VtyEvent (EvKey (KChar 'V') []) -> put' $ regenerateScreens j d $ toggleValue ui -- VtyEvent (EvKey (KChar '0') []) -> put' $ regenerateScreens j d $ setDepth (Just 0) ui -- VtyEvent (EvKey (KChar '1') []) -> put' $ regenerateScreens j d $ setDepth (Just 1) ui -- VtyEvent (EvKey (KChar '2') []) -> put' $ regenerateScreens j d $ setDepth (Just 2) ui -- VtyEvent (EvKey (KChar '3') []) -> put' $ regenerateScreens j d $ setDepth (Just 3) ui -- VtyEvent (EvKey (KChar '4') []) -> put' $ regenerateScreens j d $ setDepth (Just 4) ui -- VtyEvent (EvKey (KChar '5') []) -> put' $ regenerateScreens j d $ setDepth (Just 5) ui -- VtyEvent (EvKey (KChar '6') []) -> put' $ regenerateScreens j d $ setDepth (Just 6) ui -- VtyEvent (EvKey (KChar '7') []) -> put' $ regenerateScreens j d $ setDepth (Just 7) ui -- VtyEvent (EvKey (KChar '8') []) -> put' $ regenerateScreens j d $ setDepth (Just 8) ui -- VtyEvent (EvKey (KChar '9') []) -> put' $ regenerateScreens j d $ setDepth (Just 9) ui -- VtyEvent (EvKey (KChar '-') []) -> put' $ regenerateScreens j d $ decDepth ui -- VtyEvent (EvKey (KChar '_') []) -> put' $ regenerateScreens j d $ decDepth ui -- VtyEvent (EvKey (KChar c) []) | c `elem` ['+','='] -> put' $ regenerateScreens j d $ incDepth ui -- VtyEvent (EvKey (KChar 'T') []) -> put' $ regenerateScreens j d $ setReportPeriod (DayPeriod d) ui -- -- display mode/query toggles -- VtyEvent (EvKey (KChar 't') []) -> modify' (regenerateScreens j d . toggleTree) >> msCenterAndContinue -- VtyEvent (EvKey (KChar c) []) | c `elem` ['z','Z'] -> modify' (regenerateScreens j d . toggleEmpty) >> msCenterAndContinue -- VtyEvent (EvKey (KChar 'R') []) -> modify' (regenerateScreens j d . toggleReal) >> msCenterAndContinue -- VtyEvent (EvKey (KChar 'U') []) -> modify' (regenerateScreens j d . toggleUnmarked) >> msCenterAndContinue -- VtyEvent (EvKey (KChar 'P') []) -> modify' (regenerateScreens j d . togglePending) >> msCenterAndContinue -- VtyEvent (EvKey (KChar 'C') []) -> modify' (regenerateScreens j d . toggleCleared) >> msCenterAndContinue -- VtyEvent (EvKey (KChar 'F') []) -> modify' (regenerateScreens j d . toggleForecast d) -- VtyEvent (EvKey (KChar 'H') []) -> modify' (toggleHistorical >>> regenerateScreens j d) -- narrow/widen/move the period as on other screens, for consistency VtyEvent (EvKey (KDown) [MShift]) -> modify' (shrinkReportPeriod d >>> regenerateScreens j d) VtyEvent (EvKey (KUp) [MShift]) -> modify' (growReportPeriod d >>> regenerateScreens j d) VtyEvent (EvKey (KRight) [MShift]) -> modify' (nextReportPeriod journalspan >>> regenerateScreens j d) VtyEvent (EvKey (KLeft) [MShift]) -> modify' (previousReportPeriod journalspan >>> regenerateScreens j d) VtyEvent (EvKey (KChar 'T') []) -> modify' (setReportPeriod (DayPeriod d) >>> regenerateScreens j d) VtyEvent (EvKey (KChar '/') []) -> put' $ regenerateScreens j d $ showMinibuffer "filter" Nothing ui VtyEvent (EvKey k []) | k `elem` [KBS, KDel] -> (put' $ regenerateScreens j d $ resetFilter ui) VtyEvent (EvKey (KChar 'l') [MCtrl]) -> scrollSelectionToMiddle (_mssList sst) >> redraw VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui -- RIGHT enters selected screen if there is one VtyEvent e | e `elem` moveRightEvents , not $ isBlankElement $ listSelectedElement (_mssList sst) -> msEnterScreen d (fromMaybe Accounts mselscr) ui -- MouseDown is sometimes duplicated, https://github.com/jtdaugherty/brick/issues/347 -- just use it to move the selection MouseDown _n BLeft _mods Location{loc=(_x,y)} | not $ (=="") clickedname -> do put' ui{aScreen=MS sst} -- XXX does this do anything ? where item = listElements (_mssList sst) !? y clickedname = maybe "" msItemScreenName item -- mclickedscr = msItemScreen <$> item -- and on MouseUp, enter the subscreen MouseUp _n (Just BLeft) Location{loc=(_x,y)} -> -- | not $ (=="") clickedname -> case mclickedscr of Just scr -> msEnterScreen d scr ui Nothing -> return () where item = listElements (_mssList sst) !? y -- clickedname = maybe "" msItemScreenName item mclickedscr = msItemScreen <$> item -- when selection is at the last item, DOWN scrolls instead of moving, until maximally scrolled VtyEvent e | e `elem` moveDownEvents, isBlankElement mnextelement -> do vScrollBy (viewportScroll $ (_mssList sst)^.listNameL) 1 where mnextelement = listSelectedElement $ listMoveDown (_mssList sst) -- mouse scroll wheel scrolls the viewport up or down to its maximum extent, -- pushing the selection when necessary. MouseDown name btn _mods _loc | btn `elem` [BScrollUp, BScrollDown] -> do let scrollamt = if btn==BScrollUp then -1 else 1 list' <- nestEventM' (_mssList sst) $ listScrollPushingSelection name (msListSize (_mssList sst)) scrollamt put' ui{aScreen=MS sst{_mssList=list'}} -- 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 l <- nestEventM' (_mssList sst) $ handleListEvent e if isBlankElement $ listSelectedElement l then do let l' = listMoveTo lastnonblankidx l scrollSelectionToMiddle l' put' ui{aScreen=MS sst{_mssList=l'}} else put' ui{aScreen=MS sst{_mssList=l}} -- fall through to the list's event handler (handles up/down) VtyEvent e -> do list' <- nestEventM' (_mssList sst) $ handleListEvent (normaliseMovementKeys e) put' ui{aScreen=MS $ sst & mssList .~ list'} MouseDown{} -> return () MouseUp{} -> return () AppEvent _ -> return () _ -> dbguiEv "msHandle" >> errorWrongScreenType "msHandle" msEnterScreen :: Day -> ScreenName -> UIState -> EventM Name UIState () msEnterScreen d scrname ui@UIState{ajournal=j, aopts=uopts} = do dbguiEv "msEnterScreen" let scr = case scrname of Accounts -> asNew uopts d j Nothing CashScreen -> csNew uopts d j Nothing Balancesheet -> bsNew uopts d j Nothing Incomestatement -> isNew uopts d j Nothing put' $ pushScreen scr ui -- | Set the selected list item on the menu screen. Has no effect on other screens. msSetSelectedScreen :: Int -> Screen -> Screen msSetSelectedScreen selidx (MS mss@MSS{_mssList=l}) = MS mss{_mssList=listMoveTo selidx l} msSetSelectedScreen _ s = s isBlankElement mel = ((msItemScreenName . snd) <$> mel) == Just "" msListSize = V.length . V.takeWhile ((/="").msItemScreenName) . listElements hledger-ui-1.50.3/Hledger/UI/RegisterScreen.hs0000644000000000000000000004405215107137141017167 0ustar0000000000000000-- The account register screen, showing transactions in an account, like hledger-web's register. {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# OPTIONS_GHC -Wno-incomplete-record-updates #-} module Hledger.UI.RegisterScreen (rsNew ,rsUpdate ,rsDraw ,rsHandle ,rsSetAccount ,rsCenterSelection ) where import Control.Monad import Control.Monad.IO.Class (liftIO) import Data.Bifunctor (bimap, Bifunctor (second)) #if MIN_VERSION_base(4,19,0) import Data.List hiding ((!?)) #else import Data.List #endif import Data.Maybe import Data.Text qualified as T import Data.Vector qualified as V import Data.Vector ((!?)) import Graphics.Vty (Event(..),Key(..),Modifier(..), Button (BLeft, BScrollDown, BScrollUp)) import Brick import Brick.Widgets.List hiding (reverse) import Brick.Widgets.Edit import Lens.Micro.Platform import System.Console.ANSI import Hledger import Hledger.Cli hiding (mode, progname,prognameandversion) import Hledger.UI.UIOptions import Hledger.UI.UITypes import Hledger.UI.UIState import Hledger.UI.UIUtils import Hledger.UI.UIScreens import Hledger.UI.Editor import Hledger.UI.ErrorScreen (uiReload, uiReloadIfFileChanged, uiToggleBalanceAssertions) rsDraw :: UIState -> [Widget Name] rsDraw UIState{aopts=_uopts@UIOpts{uoCliOpts=copts@CliOpts{reportspec_=rspec}} ,aScreen=RS RSS{..} ,aMode=mode } = dbgui "rsDraw" $ case mode of Help -> [helpDialog, maincontent] _ -> [maincontent] where displayitems = V.toList $ listElements $ _rssList 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 (wbWidth . rsItemChangeAmount) displayitems maxbalwidthseen = maximum' $ map (wbWidth . 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 _rssList where ropts = _rsReportOpts rspec ishistorical = balanceaccum_ ropts == Historical -- inclusive = tree_ ropts || rsForceInclusive toplabel = withAttr (attrName "border" <> attrName "bold") (str $ T.unpack $ replaceHiddenAccountsNameWith "All" _rssAccount) -- <+> withAttr ("border" <> "query") (str $ if inclusive then "" else " exclusive") <+> togglefilters <+> str " transactions" -- <+> str (if ishistorical then " historical total" else " period total") <+> borderQueryStr (T.unpack . T.unwords . map textQuoteIfNeeded $ querystring_ ropts) -- <+> str " and subs" <+> borderPeriodStr "in" (period_ ropts) <+> str " (" <+> cur <+> str "/" <+> total <+> str ")" <+> (if ignore_assertions_ . balancingopts_ $ inputopts_ copts then withAttr (attrName "border" <> attrName "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 (attrName "border" <> attrName "query") (str $ " " ++ intercalate ", " fs) cur = str $ case listSelected _rssList of Nothing -> "-" Just i -> show (i + 1) total = str $ show $ length nonblanks nonblanks = V.takeWhile (not . T.null . rsItemDate) $ listElements $ _rssList -- query = query_ $ reportopts_ $ cliopts_ opts bottomlabel = case mode of Minibuffer label ed -> minibuffer label ed _ -> quickhelp where quickhelp = borderKeysStr' [ ("LEFT", str "back") -- ,("RIGHT", str "transaction") -- tree/list mode - rsForceInclusive may override, but use tree_ to ensure a visible toggle effect ,("t", renderToggle (tree_ ropts) "list(-subs)" "tree(+subs)") -- ,("t", str "tree(+subs)") -- ,("l", str "list(-subs)") ,("H", renderToggle (not ishistorical) "historical" "period") ,("F", renderToggle1 (isJust . forecast_ . inputopts_ $ copts) "forecast") -- ,("a", "add") -- ,("g", "reload") ,("?", str "help") -- ,("q", "quit") ] rsDraw _ = dbgui "rsDraw" $ errorWrongScreenType "rsDraw" -- PARTIAL: rsDrawItem :: (Int,Int,Int,Int,Int) -> Bool -> RegisterScreenItem -> Widget Name rsDrawItem (datewidth,descwidth,acctswidth,changewidth,balwidth) selected RegisterScreenItem{..} = Widget Greedy Fixed $ do render $ txt (fitText (Just datewidth) (Just datewidth) True True rsItemDate) <+> txt " " <+> txt (fitText (Just 1) (Just 1) True True (T.pack $ show rsItemStatus)) <+> txt " " <+> txt (fitText (Just descwidth) (Just descwidth) True True rsItemDescription) <+> txt " " <+> txt (fitText (Just acctswidth) (Just acctswidth) True True rsItemOtherAccounts) <+> txt " " <+> withAttr changeattr (txt $ fitText (Just changewidth) (Just changewidth) True False changeAmt) <+> txt " " <+> withAttr balattr (txt $ fitText (Just balwidth) (Just balwidth) True False balanceAmt) where changeAmt = wbToText rsItemChangeAmount balanceAmt = wbToText rsItemBalanceAmount changeattr | T.any (=='-') changeAmt = sel $ attrName "list" <> attrName "amount" <> attrName "decrease" | otherwise = sel $ attrName "list" <> attrName "amount" <> attrName "increase" balattr | T.any (=='-') balanceAmt = sel $ attrName "list" <> attrName "balance" <> attrName "negative" | otherwise = sel $ attrName "list" <> attrName "balance" <> attrName "positive" sel | selected = (<> attrName "selected") | otherwise = id -- XXX clean up like asHandle rsHandle :: BrickEvent Name AppEvent -> EventM Name UIState () rsHandle ev = do ui0 <- get' dbguiEv "rsHandle" case ui0 of ui@UIState{ aScreen=RS sst@RSS{..} ,aopts=UIOpts{uoCliOpts=copts} ,ajournal=j ,aMode=mode } -> do d <- liftIO getCurrentDay let journalspan = journalDateSpan False j nonblanks = V.takeWhile (not . T.null . rsItemDate) $ listElements $ _rssList lastnonblankidx = max 0 (length nonblanks - 1) numberedtxns = zipWith (curry (second rsItemTransaction)) [(1::Integer)..] (V.toList nonblanks) -- the transactions being shown and the currently selected or last transaction, if any: mtxns :: Maybe ([NumberedTransaction], NumberedTransaction) mtxns = case numberedtxns of [] -> Nothing nts@(_:_) -> Just (nts, maybe (last nts) (bimap ((+1).fromIntegral) rsItemTransaction) $ listSelectedElement _rssList) -- PARTIAL: last won't fail case mode of Minibuffer _ ed -> case ev of VtyEvent (EvKey KEsc []) -> modify' closeMinibuffer VtyEvent (EvKey KEnter []) -> put' $ regenerateScreens j d $ case setFilter s $ closeMinibuffer ui of Left bad -> showMinibuffer "Cannot compile regular expression" (Just bad) ui Right ui' -> ui' where s = chomp . unlines . map strip $ getEditContents ed -- VtyEvent (EvKey (KChar '/') []) -> put' $ regenerateScreens j d $ showMinibuffer ui VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui VtyEvent e -> do ed' <- nestEventM' ed $ handleEditorEvent (VtyEvent e) put' ui{aMode=Minibuffer "filter" ed'} AppEvent _ -> return () MouseDown{} -> return () MouseUp{} -> return () Help -> case ev of -- VtyEvent (EvKey (KChar 'q') []) -> halt VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui _ -> helpHandle ev Normal -> case ev of VtyEvent (EvKey (KChar 'q') []) -> halt VtyEvent (EvKey KEsc []) -> put' $ resetScreens d ui VtyEvent (EvKey (KChar c) []) | c == '?' -> put' $ setMode Help ui -- AppEvents arrive in --watch mode, see AccountsScreen AppEvent (DateChange old _) | isStandardPeriod p && p `periodContainsDate` old -> put' $ regenerateScreens j d $ setReportPeriod (DayPeriod d) ui where p = reportPeriod ui e | e `elem` [AppEvent FileChange, VtyEvent (EvKey (KChar 'g') [])] -> uiReload copts d ui >>= put' VtyEvent (EvKey (KChar 'I') []) -> uiToggleBalanceAssertions d ui VtyEvent (EvKey (KChar 'a') []) -> suspendAndResume $ clearScreen >> setCursorPosition 0 0 >> add (cliOptsDropArgs copts) j >> uiReloadIfFileChanged copts d j ui VtyEvent (EvKey (KChar 'A') []) -> suspendAndResume $ void (runIadd (journalFilePath j)) >> uiReloadIfFileChanged copts d j ui VtyEvent (EvKey (KChar 'T') []) -> put' $ regenerateScreens j d $ setReportPeriod (DayPeriod d) ui VtyEvent (EvKey (KChar 'E') []) -> suspendAndResume $ void (runEditor pos f) >> uiReloadIfFileChanged copts d j ui where (pos,f) = case listSelectedElement _rssList of Nothing -> (endPosition, journalFilePath j) Just (_, RegisterScreenItem{ rsItemTransaction=Transaction{tsourcepos=(SourcePos f' l c,_)}}) -> (Just (unPos l, Just $ unPos c),f') -- display mode/query toggles VtyEvent (EvKey (KChar 'B') []) -> rsCenterSelection (regenerateScreens j d $ toggleConversionOp ui) >>= put' VtyEvent (EvKey (KChar 'V') []) -> rsCenterSelection (regenerateScreens j d $ toggleValue ui) >>= put' VtyEvent (EvKey (KChar 'H') []) -> rsCenterSelection (regenerateScreens j d $ toggleHistorical ui) >>= put' VtyEvent (EvKey (KChar 't') []) -> rsCenterSelection (regenerateScreens j d $ toggleTree ui) >>= put' VtyEvent (EvKey (KChar c) []) | c `elem` ['z','Z'] -> rsCenterSelection (regenerateScreens j d $ toggleEmpty ui) >>= put' VtyEvent (EvKey (KChar 'R') []) -> rsCenterSelection (regenerateScreens j d $ toggleReal ui) >>= put' VtyEvent (EvKey (KChar 'U') []) -> rsCenterSelection (regenerateScreens j d $ toggleUnmarked ui) >>= put' VtyEvent (EvKey (KChar 'P') []) -> rsCenterSelection (regenerateScreens j d $ togglePending ui) >>= put' VtyEvent (EvKey (KChar 'C') []) -> rsCenterSelection (regenerateScreens j d $ toggleCleared ui) >>= put' VtyEvent (EvKey (KChar 'F') []) -> rsCenterSelection (regenerateScreens j d $ toggleForecast d ui) >>= put' VtyEvent (EvKey (KChar '/') []) -> put' $ regenerateScreens j d $ showMinibuffer "filter" Nothing ui VtyEvent (EvKey (KDown) [MShift]) -> put' $ regenerateScreens j d $ shrinkReportPeriod d ui VtyEvent (EvKey (KUp) [MShift]) -> put' $ regenerateScreens j d $ growReportPeriod d ui VtyEvent (EvKey (KRight) [MShift]) -> put' $ regenerateScreens j d $ nextReportPeriod journalspan ui VtyEvent (EvKey (KLeft) [MShift]) -> put' $ regenerateScreens j d $ previousReportPeriod journalspan ui VtyEvent (EvKey k []) | k `elem` [KBS, KDel] -> (put' $ regenerateScreens j d $ resetFilter ui) VtyEvent (EvKey (KChar 'l') [MCtrl]) -> scrollSelectionToMiddle _rssList >> redraw VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui -- exit screen on LEFT VtyEvent e | e `elem` moveLeftEvents -> put' $ popScreen ui -- or on a click in the app's left margin. This is a VtyEvent since not in a clickable widget. VtyEvent (EvMouseUp x _y (Just BLeft)) | x==0 -> put' $ popScreen ui -- enter transaction screen on RIGHT VtyEvent e | e `elem` moveRightEvents -> case mtxns of Nothing -> return (); Just (nts, nt) -> rsEnterTransactionScreen _rssAccount nts nt ui -- or on transaction click -- MouseDown is sometimes duplicated, https://github.com/jtdaugherty/brick/issues/347 -- just use it to move the selection MouseDown _n BLeft _mods Location{loc=(_x,y)} | not $ (=="") clickeddate -> do put' $ ui{aScreen=RS sst{_rssList=listMoveTo y _rssList}} where clickeddate = maybe "" rsItemDate $ listElements _rssList !? y -- and on MouseUp, enter the subscreen MouseUp _n (Just BLeft) Location{loc=(_x,y)} | not $ (=="") clickeddate -> do case mtxns of Nothing -> return (); Just (nts, nt) -> rsEnterTransactionScreen _rssAccount nts nt ui where clickeddate = maybe "" rsItemDate $ listElements _rssList !? y -- when selection is at the last item, DOWN scrolls instead of moving, until maximally scrolled VtyEvent e | e `elem` moveDownEvents, isBlankElement mnextelement -> do vScrollBy (viewportScroll $ listName $ _rssList) 1 where mnextelement = listSelectedElement $ listMoveDown _rssList -- mouse scroll wheel scrolls the viewport up or down to its maximum extent, -- pushing the selection when necessary. MouseDown name btn _mods _loc | btn `elem` [BScrollUp, BScrollDown] -> do let scrollamt = if btn==BScrollUp then -1 else 1 list' <- nestEventM' _rssList $ listScrollPushingSelection name (rsListSize _rssList) scrollamt put' ui{aScreen=RS sst{_rssList=list'}} -- 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 l <- nestEventM' _rssList $ handleListEvent e if isBlankElement $ listSelectedElement l then do let l' = listMoveTo lastnonblankidx l scrollSelectionToMiddle l' put' ui{aScreen=RS sst{_rssList=l'}} else put' ui{aScreen=RS sst{_rssList=l}} -- fall through to the list's event handler (handles other [pg]up/down events) VtyEvent e -> do let e' = normaliseMovementKeys e newitems <- nestEventM' _rssList $ handleListEvent e' put' ui{aScreen=RS sst{_rssList=newitems}} MouseDown{} -> return () MouseUp{} -> return () AppEvent _ -> return () _ -> errorWrongScreenType "rsHandle" isBlankElement mel = ((rsItemDate . snd) <$> mel) == Just "" rsListSize = V.length . V.takeWhile ((/="").rsItemDate) . listElements rsSetAccount :: AccountName -> Bool -> Screen -> Screen rsSetAccount a forceinclusive (RS st@RSS{}) = RS st{_rssAccount=replaceHiddenAccountsNameWith "*" a, _rssForceInclusive=forceinclusive} rsSetAccount _ _ st = st -- | Scroll the selected item to the middle of the screen, when on the register screen. -- No effect on other screens. rsCenterSelection :: UIState -> EventM Name UIState UIState rsCenterSelection ui@UIState{aScreen=RS sst} = do scrollSelectionToMiddle $ _rssList sst return ui -- ui is unchanged, but this makes the function more chainable rsCenterSelection ui = return ui rsEnterTransactionScreen :: AccountName -> [NumberedTransaction] -> NumberedTransaction -> UIState -> EventM Name UIState () rsEnterTransactionScreen acct nts nt ui = do dbguiEv "rsEnterTransactionScreen" put' $ pushScreen (tsNew acct nts nt) ui hledger-ui-1.50.3/Hledger/UI/TransactionScreen.hs0000644000000000000000000002601015107137141017662 0ustar0000000000000000-- The transaction screen, showing a single transaction's general journal entry. {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TupleSections #-} {-# OPTIONS_GHC -Wno-incomplete-record-updates #-} module Hledger.UI.TransactionScreen (tsNew ,tsUpdate ,tsDraw ,tsHandle ) where import Brick import Brick.Widgets.Edit (editorText, renderEditor) import Brick.Widgets.List (listMoveTo) import Control.Monad.IO.Class (liftIO) import Data.List import Data.Maybe import Data.Text qualified as T import Graphics.Vty (Event(..),Key(..),Modifier(..), Button (BLeft)) import System.Exit (ExitCode (..)) import Hledger import Hledger.Cli hiding (mode, prices, progname,prognameandversion) import Hledger.UI.UIOptions import Hledger.UI.UITypes import Hledger.UI.UIState import Hledger.UI.UIUtils import Hledger.UI.UIScreens import Hledger.UI.Editor import Hledger.UI.ErrorScreen (uiCheckBalanceAssertions, uiReload, uiReloadIfFileChanged, uiToggleBalanceAssertions) import Hledger.UI.RegisterScreen (rsHandle) tsDraw :: UIState -> [Widget Name] tsDraw UIState{aopts=UIOpts{uoCliOpts=copts@CliOpts{reportspec_=rspec@ReportSpec{_rsReportOpts=ropts}}} ,ajournal=j ,aScreen=TS TSS{_tssTransaction=(i,t') ,_tssTransactions=nts ,_tssAccount=acct } ,aMode=mode } = case mode of Help -> [helpDialog, maincontent] _ -> [maincontent] where maincontent = Widget Greedy Greedy $ render $ defaultLayout toplabel bottomlabel txneditor where -- as with print, show amounts with all of their decimal places t = transactionMapPostingAmounts mixedAmountSetFullPrecision t' -- XXX would like to shrink the editor to the size of the entry, -- so handler can more easily detect clicks below it txneditor = renderEditor (vBox . map txt) False $ editorText TransactionEditor Nothing $ showTxn ropts rspec j t 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 (attrName "border" <> attrName "bold") (str $ show i) <+> str (" of "++show (length nts)) <+> togglefilters <+> borderQueryStr (unwords . map (quoteIfNeeded . T.unpack) $ querystring_ ropts) <+> str (" in "++T.unpack (replaceHiddenAccountsNameWith "All" acct)++")") <+> (if ignore_assertions_ . balancingopts_ $ inputopts_ copts then withAttr (attrName "border" <> attrName "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 (attrName "border" <> attrName "query") (str $ " " ++ intercalate ", " fs) bottomlabel = quickhelp -- case mode of -- Minibuffer ed -> minibuffer ed -- _ -> quickhelp where quickhelp = borderKeysStr [ ("LEFT", "back") ,("UP/DOWN", "prev/next txn") --,("ESC", "cancel/top") -- ,("a", "add") ,("E", "edit") ,("g", "reload") ,("?", "help") -- ,("q", "quit") ] tsDraw _ = errorWrongScreenType "tsDraw" -- PARTIAL: -- Render a transaction suitably for the transaction screen. showTxn :: ReportOpts -> ReportSpec -> Journal -> Transaction -> T.Text showTxn ropts rspec j t = showTransactionOneLineAmounts $ maybe id (transactionApplyValuation prices styles periodlast (_rsDay rspec)) (value_ ropts) $ maybe id transactionToCost (conversionop_ ropts) t -- (if real_ ropts then filterTransactionPostings (Real True) else id) -- filter postings by --real where prices = journalPriceOracle (infer_prices_ ropts) j styles = journalCommodityStyles j periodlast = fromMaybe (error' "TransactionScreen: expected a non-empty journal") $ -- PARTIAL: shouldn't happen reportPeriodOrJournalLastDay rspec j tsHandle :: BrickEvent Name AppEvent -> EventM Name UIState () tsHandle ev = do ui0 <- get' case ui0 of ui@UIState{aScreen=TS TSS{_tssTransaction=(i,t), _tssTransactions=nts} ,aopts=UIOpts{uoCliOpts=copts} ,ajournal=j ,aMode=mode } -> case mode of Help -> case ev of -- VtyEvent (EvKey (KChar 'q') []) -> halt VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui _ -> helpHandle 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 VtyEvent (EvKey KEsc []) -> put' $ resetScreens d ui VtyEvent (EvKey (KChar c) []) | c == '?' -> put' $ setMode Help ui -- g or file change: reload the journal and rebuild app state. e | e `elem` [VtyEvent (EvKey (KChar 'g') []), AppEvent FileChange] -> tsReload copts d ui -- for debugging; leaving these here because they were hard to find -- \u -> dbguiEv (pshow u) >> put' u -- doesn't log -- \UIState{aScreen=TS tss} -> error' $ pshow $ _tssTransaction tss -- E: run editor, reload the journal. VtyEvent (EvKey (KChar 'E') []) -> do suspendAndResume' $ do let (pos,f) = case tsourcepos t of (SourcePos f' l1 c1,_) -> (Just (unPos l1, Just $ unPos c1),f') exitcode <- runEditor pos f case exitcode of ExitSuccess -> return () ExitFailure c -> error' $ "running the text editor failed with exit code " ++ show c tsReloadIfFileChanged copts d j ui AppEvent (DateChange old _) | isStandardPeriod p && p `periodContainsDate` old -> put' $ regenerateScreens j d $ setReportPeriod (DayPeriod d) ui where p = reportPeriod ui VtyEvent (EvKey (KChar 'I') []) -> uiToggleBalanceAssertions d ui -- for toggles that may change the current/prev/next transactions, -- we must regenerate the transaction list, like the g handler above ? with regenerateTransactions ? TODO WIP -- EvKey (KChar 'E') [] -> put' $ regenerateScreens j d $ stToggleEmpty ui -- EvKey (KChar 'C') [] -> put' $ regenerateScreens j d $ stToggleCleared ui -- EvKey (KChar 'R') [] -> put' $ regenerateScreens j d $ stToggleReal ui VtyEvent (EvKey (KChar 'B') []) -> put' . regenerateScreens j d $ toggleConversionOp ui VtyEvent (EvKey (KChar 'V') []) -> put' . regenerateScreens j d $ toggleValue ui VtyEvent e | e `elem` moveUpEvents -> put' $ tsSelect iprev tprev ui VtyEvent e | e `elem` moveDownEvents -> put' $ tsSelect inext tnext ui -- exit screen on LEFT VtyEvent e | e `elem` moveLeftEvents -> put' . popScreen $ tsSelect i t ui -- Probably not necessary to tsSelect here, but it's safe. -- or on a click in the app's left margin. VtyEvent (EvMouseUp x _y (Just BLeft)) | x==0 -> put' . popScreen $ tsSelect i t ui VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui _ -> return () _ -> errorWrongScreenType "tsHandle" where -- Reload and fully regenerate the transaction screen. -- XXX On transaction screen or below, this is tricky because of a current limitation of regenerateScreens. -- For now we try to work around by re-entering the screen(s). -- This can show flicker in the UI and it's hard to handle all situations robustly. tsReload copts d ui = uiReload copts d ui >>= reEnterTransactionScreen copts d tsReloadIfFileChanged copts d j ui = liftIO (uiReloadIfFileChanged copts d j ui) >>= reEnterTransactionScreen copts d reEnterTransactionScreen _copts d ui = do -- 1. If uiReload (or checking balance assertions) moved us to the error screen, save that, and return to the transaction screen. let (merrscr, uiTxn) = case aScreen $ uiCheckBalanceAssertions d ui of s@(ES _) -> (Just s, popScreen ui) _ -> (Nothing, ui) -- 2. Exit to register screen let uiReg = popScreen uiTxn put' uiReg -- 3. Re-enter the transaction screen rsHandle (VtyEvent (EvKey KEnter [])) -- PARTIAL assumes we are on the register screen. -- 4. Return to the error screen (below the transaction screen) if there was one. -- Next events will be handled by esHandle. Error repair will return to the transaction screen. maybe (return ()) (put' . flip pushScreen uiTxn) merrscr -- doesn't uiTxn have old state from before step 3 ? seems to work -- XXX some problem: -- 4. Reload once more, possibly re-entering the error screen, by sending a g event. -- sendVtyEvents [EvKey (KChar 'g') []] -- XXX Might be disrupted if other events are queued -- XXX doesn't update on non-error change: -- 4. Reload once more, possibly re-entering the error screen. -- uiTxnOrErr <- uiReload copts d uiTxn -- uiReloadIfChanged ? -- uiCheckBalanceAssertions ? seems unneeded -- put' uiTxnOrErr -- XXX not working right: -- -- 1. If uiReload (or checking balance assertions) moved us to the error screen, exit to the transaction screen. -- let -- uiTxn = case aScreen $ uiCheckBalanceAssertions d ui of -- ES _ -> popScreen ui -- _ -> ui -- -- 2. Exit to register screen -- put' $ popScreen uiTxn -- -- 3. Re-enter the transaction screen, and reload once more. -- sendVtyEvents [EvKey KEnter [], EvKey (KChar 'g') []] -- XXX Might be disrupted if other events are queued -- | Select a new transaction and update the previous register screen tsSelect :: Integer -> Transaction -> UIState -> UIState tsSelect i t ui@UIState{aScreen=TS sst} = case aPrevScreens ui of x:xs -> ui'{aPrevScreens=rsSelect i x : xs} [] -> ui' where ui' = ui{aScreen=TS sst{_tssTransaction=(i,t)}} tsSelect _ _ ui = ui -- | Select the nth item on the register screen. rsSelect :: Integer -> Screen -> Screen rsSelect i (RS sst@RSS{..}) = RS sst{_rssList=listMoveTo (fromInteger $ i-1) _rssList} rsSelect _ scr = scr hledger-ui-1.50.3/Hledger/UI/UIScreens.hs0000644000000000000000000003733215107137141016106 0ustar0000000000000000-- | Constructors and updaters for all hledger-ui screens. -- -- Constructors (*New) create and initialise a new screen with valid state, -- based on the provided options, reporting date, journal, and screen-specific parameters. -- -- Updaters (*Update) recalculate an existing screen's state, -- based on new options, reporting date, journal, and the old screen state. -- -- These are gathered in this low-level module so that any screen's handler -- can create or regenerate all other screens. -- Drawing and event-handling code is elsewhere, in per-screen modules. {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NamedFieldPuns #-} module Hledger.UI.UIScreens (screenUpdate ,esNew ,esUpdate ,msNew ,msUpdate ,asNew ,asUpdate ,asItemIndex ,csNew ,csUpdate ,csItemIndex ,bsNew ,bsUpdate ,bsItemIndex ,isNew ,isUpdate ,isItemIndex ,rsNew ,rsUpdate ,tsNew ,tsUpdate ) where import Brick.Widgets.List (listMoveTo, listSelectedElement, list) import Data.List import Data.Maybe import Data.Text qualified as T import Data.Time.Calendar (Day, diffDays) import Safe import Data.Vector qualified as V import Hledger.Cli hiding (mode, progname,prognameandversion) import Hledger.UI.UIOptions import Hledger.UI.UITypes import Hledger.UI.UIUtils import Data.Function ((&)) -- | Regenerate the content of any screen from new options, reporting date and journal. screenUpdate :: UIOpts -> Day -> Journal -> Screen -> Screen screenUpdate opts d j = \case MS sst -> MS $ msUpdate sst -- opts d j ass AS sst -> AS $ asUpdate opts d j sst CS sst -> CS $ csUpdate opts d j sst BS sst -> BS $ bsUpdate opts d j sst IS sst -> IS $ isUpdate opts d j sst RS sst -> RS $ rsUpdate opts d j sst TS sst -> TS $ tsUpdate sst ES sst -> ES $ esUpdate sst -- | Construct an error screen. -- Screen-specific arguments: the error message to show. esNew :: String -> Screen esNew msg = dbgui "esNew" $ ES ESS { _essError = msg ,_essUnused = () } -- | Update an error screen. Currently a no-op since error screen -- depends only on its screen-specific state. esUpdate :: ErrorScreenState -> ErrorScreenState esUpdate = dbgui "esUpdate`" -- | Construct a menu screen, with the first item selected. -- Screen-specific arguments: none. msNew :: Screen msNew = dbgui "msNew" $ MS MSS { _mssList = list MenuList (V.fromList items ) 1, _mssUnused = () } where -- keep synced with: indexes below, initial screen stack setup in UI.Main items = [ MenuScreenItem "Cash accounts" CashScreen ,MenuScreenItem "Balance sheet accounts" Balancesheet ,MenuScreenItem "Income statement accounts" Incomestatement ,MenuScreenItem "All accounts" Accounts ] -- keep synced with items above. -- | Positions of menu screen items, so we can move selection to them. [ csItemIndex, bsItemIndex, isItemIndex, asItemIndex ] = [0..3] :: [Int] -- | Update a menu screen. Currently a no-op since menu screen -- has unchanging content. msUpdate :: MenuScreenState -> MenuScreenState msUpdate = dbgui "msUpdate" nullass macct = ASS { _assSelectedAccount = fromMaybe "" macct ,_assList = list AccountsList (V.fromList []) 1 } -- | Construct an accounts screen listing the appropriate set of accounts, -- with the appropriate one selected. -- Screen-specific arguments: the account to select if any. asNew :: UIOpts -> Day -> Journal -> Maybe AccountName -> Screen asNew uopts d j macct = dbgui "asNew" $ AS $ asUpdate uopts d j $ nullass macct -- | Update an accounts screen's state from these options, reporting date, and journal. asUpdate :: UIOpts -> Day -> Journal -> AccountsScreenState -> AccountsScreenState asUpdate uopts d = dbgui "asUpdate" . asUpdateHelper rspec d copts roptsmod extraquery where UIOpts{uoCliOpts=copts@CliOpts{reportspec_=rspec}} = uopts roptsmod = id extraquery = Any -- | Update an accounts-like screen's state from this report spec, reporting date, -- cli options, report options modifier, extra query, and journal. asUpdateHelper :: ReportSpec -> Day -> CliOpts -> (ReportOpts -> ReportOpts) -> Query -> Journal -> AccountsScreenState -> AccountsScreenState asUpdateHelper rspec0 d copts roptsModify extraquery j ass = dbgui "asUpdateHelper" ass{_assList=l} where ropts = roptsModify $ _rsReportOpts rspec0 rspec = updateReportSpec ropts rspec0{_rsDay=d} -- update to the current date, might have changed since program start & either (error' "asUpdateHelper: adjusting the query, should not have failed") id -- PARTIAL: & reportSpecSetFutureAndForecast (forecast_ $ inputopts_ copts) -- include/exclude future & forecast transactions & reportSpecAddQuery extraquery -- add any extra restrictions l = listMoveTo selidx $ list AccountsList (V.fromList $ displayitems ++ blankitems) 1 where -- which account should be selected ? selidx = headDef 0 $ catMaybes [ elemIndex a as -- the one previously selected, if it can be found ,findIndex (a `isAccountNamePrefixOf`) as -- or the first account found with the same prefix ,Just $ max 0 (length (filter (< a) as) - 1) -- otherwise, the alphabetically preceding account. ] where a = _assSelectedAccount ass as = map asItemAccountName displayitems displayitems = map displayitem items where -- run the report (items, _) = styleAmounts styles $ balanceReport rspec j where styles = journalCommodityStylesWith HardRounding j -- pre-render a list item displayitem (fullacct, shortacct, indent, bal) = AccountsScreenItem{asItemIndentLevel = indent ,asItemAccountName = fullacct ,asItemDisplayAccountName = replaceHiddenAccountsNameWith "All" $ if tree_ ropts then shortacct else fullacct ,asItemMixedAmount = Just bal } -- blanks added for scrolling control, cf RegisterScreen. blankitems = replicate uiNumBlankItems -- XXX ugly hard-coded value. When debugging, changing to 0 reduces noise. AccountsScreenItem{asItemIndentLevel = 0 ,asItemAccountName = "" ,asItemDisplayAccountName = "" ,asItemMixedAmount = Nothing } -- | Construct a balance sheet screen listing the appropriate set of accounts, -- with the appropriate one selected. -- Screen-specific arguments: the account to select if any. bsNew :: UIOpts -> Day -> Journal -> Maybe AccountName -> Screen bsNew uopts d j macct = dbgui "bsNew" $ BS $ bsUpdate uopts d j $ nullass macct -- | Update a balance sheet screen's state from these options, reporting date, and journal. bsUpdate :: UIOpts -> Day -> Journal -> AccountsScreenState -> AccountsScreenState bsUpdate uopts d = dbgui "bsUpdate" . asUpdateHelper rspec d copts roptsmod extraquery where UIOpts{uoCliOpts=copts@CliOpts{reportspec_=rspec}} = uopts roptsmod ropts = ropts{balanceaccum_=Historical} -- always show historical end balances extraquery = Type [Asset,Liability,Equity] -- restrict to balance sheet accounts -- | Construct a cash accounts screen listing the appropriate set of accounts, -- with the appropriate one selected. -- Screen-specific arguments: the account to select if any. csNew :: UIOpts -> Day -> Journal -> Maybe AccountName -> Screen csNew uopts d j macct = dbgui "csNew" $ CS $ csUpdate uopts d j $ nullass macct -- | Update a balance sheet screen's state from these options, reporting date, and journal. csUpdate :: UIOpts -> Day -> Journal -> AccountsScreenState -> AccountsScreenState csUpdate uopts d = dbgui "csUpdate" . asUpdateHelper rspec d copts roptsmod extraquery where UIOpts{uoCliOpts=copts@CliOpts{reportspec_=rspec}} = uopts roptsmod ropts = ropts{balanceaccum_=Historical} -- always show historical end balances extraquery = Type [Cash] -- restrict to cash accounts -- | Construct an income statement screen listing the appropriate set of accounts, -- with the appropriate one selected. -- Screen-specific arguments: the account to select if any. isNew :: UIOpts -> Day -> Journal -> Maybe AccountName -> Screen isNew uopts d j macct = dbgui "isNew" $ IS $ isUpdate uopts d j $ nullass macct -- | Update an income statement screen's state from these options, reporting date, and journal. isUpdate :: UIOpts -> Day -> Journal -> AccountsScreenState -> AccountsScreenState isUpdate uopts d = dbgui "isUpdate" . asUpdateHelper rspec d copts roptsmod extraquery where UIOpts{uoCliOpts=copts@CliOpts{reportspec_=rspec}} = uopts roptsmod ropts = ropts{balanceaccum_=PerPeriod} -- always show historical end balances extraquery = Type [Revenue, Expense] -- restrict to income statement accounts -- | Construct a register screen listing the appropriate set of transactions, -- with the appropriate one selected. -- Screen-specific arguments: the account whose register this is, -- whether to force inclusive balances. rsNew :: UIOpts -> Day -> Journal -> AccountName -> Bool -> Screen rsNew uopts d j acct forceinclusive = -- XXX forcedefaultselection - whether to force selecting the last transaction. dbgui "rsNew" $ RS $ rsUpdate uopts d j $ RSS { _rssAccount = replaceHiddenAccountsNameWith "*" acct ,_rssForceInclusive = forceinclusive ,_rssList = list RegisterList (V.fromList []) 1 } -- | Update a register screen from these options, reporting date, and journal. rsUpdate :: UIOpts -> Day -> Journal -> RegisterScreenState -> RegisterScreenState rsUpdate uopts d j rss@RSS{_rssAccount, _rssForceInclusive, _rssList=oldlist} = dbgui "rsUpdate" rss{_rssList=l'} where UIOpts{uoCliOpts=copts@CliOpts{reportspec_=rspec@ReportSpec{_rsReportOpts=ropts}}} = uopts -- gather arguments and queries -- XXX temp inclusive = tree_ ropts || _rssForceInclusive thisacctq = Acct $ mkregex _rssAccount where mkregex = if inclusive then accountNameToAccountRegex else accountNameToAccountOnlyRegex -- adjust the report options and report spec, carefully as usual to avoid screwups (#1523) ropts' = ropts { -- ignore any depth limit, as in postingsReport; allows register's total to match accounts screen depth_=mempty -- do not strip prices so we can toggle costs within the ui , show_costs_=True -- XXX aregister also has this, needed ? -- always show historical balance -- , balanceaccum_= Historical } rspec' = updateReportSpec ropts' rspec{_rsDay=d} & either (error' "rsUpdate: adjusting the query for register, should not have failed") id -- PARTIAL: & reportSpecSetFutureAndForecast (forecast_ $ inputopts_ copts) -- gather transactions to display items = styleAmounts styles $ accountTransactionsReport rspec' j thisacctq where styles = journalCommodityStylesWith HardRounding j items' = (if empty_ ropts then id else filter (not . mixedAmountLooksZero . fifth6)) $ -- without --empty, exclude no-change txns reverse -- most recent last items -- pre-render the list items, helps calculate column widths displayitems = map displayitem items' where displayitem (t, _, _issplit, otheraccts, change, bal) = RegisterScreenItem{rsItemDate = showDate $ transactionRegisterDate wd (_rsQuery rspec') thisacctq t ,rsItemStatus = tstatus t ,rsItemDescription = tdescription t ,rsItemOtherAccounts = T.intercalate ", " . map accountSummarisedName $ nub otheraccts -- _ -> "" -- should do this if accounts field width < 30 ,rsItemChangeAmount = showamt change ,rsItemBalanceAmount = showamt bal ,rsItemTransaction = t } where showamt = showMixedAmountB oneLineNoCostFmt{displayMaxWidth=Just 3} wd = whichDate ropts' -- blank items are added to allow more control of scroll position; we won't allow movement over these. -- XXX Ugly. Changing to 0 helps when debugging. blankitems = replicate uiNumBlankItems RegisterScreenItem{rsItemDate = "" ,rsItemStatus = Unmarked ,rsItemDescription = "" ,rsItemOtherAccounts = "" ,rsItemChangeAmount = mempty ,rsItemBalanceAmount = mempty ,rsItemTransaction = nulltransaction } -- build the new list widget l = list RegisterList (V.fromList $ displayitems ++ blankitems) 1 -- ensure the appropriate list item is selected: -- if forcedefaultselection is true, the last (latest) transaction; XXX still needed ? -- 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. l' = listMoveTo newselidx l where endidx = max 0 $ length displayitems - 1 newselidx = -- case (forcedefaultselection, listSelectedElement _rssList) 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 case listSelectedElement oldlist of 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 -- | Construct a transaction screen showing one of a given list of transactions, -- with the ability to step back and forth through the list. -- Screen-specific arguments: the account whose transactions are being shown, -- the list of showable transactions, the currently shown transaction. tsNew :: AccountName -> [NumberedTransaction] -> NumberedTransaction -> Screen tsNew acct nts nt = dbgui "tsNew" $ TS TSS{ _tssAccount = acct ,_tssTransactions = nts ,_tssTransaction = nt } -- | Update a transaction screen. -- This currently does nothing because the initialisation in rsHandle is not so easy to extract. -- To see the updated transaction, one must exit and re-enter the transaction screen. -- See also tsHandle. tsUpdate :: TransactionScreenState -> TransactionScreenState tsUpdate = dbgui "tsUpdate" hledger-ui-1.50.3/Hledger/UI/UIState.hs0000644000000000000000000003372015107137141015561 0ustar0000000000000000{- | UIState operations. -} module Hledger.UI.UIState (uiState ,uiShowStatus ,setFilter ,setMode ,setReportPeriod ,showMinibuffer ,closeMinibuffer ,toggleCleared ,toggleConversionOp ,toggleIgnoreBalanceAssertions ,toggleEmpty ,toggleForecast ,toggleHistorical ,togglePending ,toggleUnmarked ,toggleReal ,toggleTree ,setTree ,setList ,toggleValue ,reportPeriod ,shrinkReportPeriod ,growReportPeriod ,nextReportPeriod ,previousReportPeriod ,resetReportPeriod ,moveReportPeriodToDate ,getDepth ,setDepth ,decDepth ,incDepth ,resetDepth ,popScreen ,pushScreen ,enableForecast ,resetFilter ,resetScreens ,regenerateScreens ) where import Brick.Widgets.Edit import Data.Bifunctor (first) import Data.Foldable (asum) import Data.Either (fromRight) import Data.List ((\\), sort) import Data.Maybe (fromMaybe) import Data.Semigroup (Max(..)) import Data.Text qualified as T import Data.Text.Zipper (gotoEOL) import Data.Time.Calendar (Day) import Lens.Micro ((^.), over, set) import Safe import Hledger import Hledger.Cli.CliOptions import Hledger.UI.UITypes import Hledger.UI.UIOptions (UIOpts(uoCliOpts)) import Hledger.UI.UIScreens (screenUpdate) import Hledger.UI.UIUtils (showScreenId, showScreenStack) -- | Make an initial UI state with the given options, journal, -- parent screen stack if any, and starting screen. uiState :: UIOpts -> Journal -> [Screen] -> Screen -> UIState uiState uopts j prevscrs scr = UIState { astartupopts = uopts ,aopts = uopts ,ajournal = j ,aMode = Normal ,aScreen = scr ,aPrevScreens = prevscrs } -- | Toggle between showing only unmarked items or all items. toggleUnmarked :: UIState -> UIState toggleUnmarked = over statuses (toggleStatus1 Unmarked) -- | Toggle between showing only pending items or all items. togglePending :: UIState -> UIState togglePending = over statuses (toggleStatus1 Pending) -- | Toggle between showing only cleared items or all items. toggleCleared :: UIState -> UIState toggleCleared = over statuses (toggleStatus1 Cleared) -- TODO testing different status toggle styles -- | Generate zero or more indicators of the status filters currently active, -- which will be shown comma-separated as part of the indicators list. uiShowStatus :: CliOpts -> [Status] -> [String] uiShowStatus copts ss = case style of -- in style 2, instead of "Y, Z" show "not X" Just 2 | length ss == numstatuses-1 -> map (("not "++). showstatus) $ sort $ complement ss -- should be just one _ -> map showstatus $ sort ss where numstatuses = length [minBound..maxBound::Status] style = maybeposintopt "status-toggles" $ rawopts_ copts showstatus Cleared = "cleared" showstatus Pending = "pending" showstatus Unmarked = "unmarked" -- various toggle behaviours: -- 1 UPC toggles only X/all toggleStatus1 :: Status -> [Status] -> [Status] toggleStatus1 s ss = if ss == [s] then [] else [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] -- toggleStatus s ss -- | ss == [s] = complement [s] -- | ss == complement [s] = [] -- | otherwise = [s] -- XXX assume only three values -- 3 UPC toggles each X -- toggleStatus3 s ss -- | s `elem` ss = filter (/= s) ss -- | otherwise = simplifyStatuses (s:ss) -- 4 upc sets X, UPC sets not-X -- toggleStatus4 s ss -- | s `elem` ss = filter (/= s) ss -- | otherwise = simplifyStatuses (s:ss) -- 5 upc toggles X, UPC toggles not-X -- toggleStatus5 s ss -- | s `elem` ss = filter (/= s) ss -- | otherwise = 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 = over empty__ not -- | Toggle between showing the primary amounts or costs. toggleConversionOp :: UIState -> UIState toggleConversionOp ui = (over value valOff) (over conversionop toggleCostMode ui) where toggleCostMode Nothing = Just ToCost toggleCostMode (Just NoConversionOp) = Just ToCost toggleCostMode (Just ToCost) = Just NoConversionOp valOff _ = Nothing -- | Toggle between showing primary amounts or values (using valuation specified at startup, or a default). toggleValue :: UIState -> UIState toggleValue ui = (over conversionop costOff) (over value (valuationToggleValue mstartupvaluation0) ui) where mstartupvaluation0 = value_ $ _rsReportOpts $ reportspec_ $ uoCliOpts $ astartupopts ui mdefvaluation = Just (AtEnd Nothing) -- valuationToggleValue (maybe startupvaluation) (maybe currentvaluation) = ... valuationToggleValue Nothing Nothing = mdefvaluation valuationToggleValue Nothing (Just _) = Nothing valuationToggleValue mstartupvaluation Nothing = mstartupvaluation valuationToggleValue _ (Just _) = Nothing costOff _ = Just NoConversionOp -- | Set hierarchic account tree mode. setTree :: UIState -> UIState setTree = set accountlistmode ALTree -- | Set flat account list mode. setList :: UIState -> UIState setList = set accountlistmode ALFlat -- | Toggle between flat and tree mode. If current mode is unspecified/default, assume it's flat. toggleTree :: UIState -> UIState toggleTree = over accountlistmode toggleTreeMode where toggleTreeMode ALTree = ALFlat toggleTreeMode ALFlat = ALTree -- | Toggle between historical balances and period balances. toggleHistorical :: UIState -> UIState toggleHistorical = over balanceaccum toggleBalanceAccum where toggleBalanceAccum Historical = PerPeriod toggleBalanceAccum _ = Historical -- | Toggle hledger-ui's "forecast/future mode". When this mode is enabled, -- hledger-shows regular transactions which have future dates, and -- "forecast" transactions generated by periodic transaction rules -- (which are usually but not necessarily future-dated). -- In normal mode, both of these are hidden. toggleForecast :: Day -> UIState -> UIState toggleForecast _d ui = set forecast newForecast ui where newForecast = case ui^.forecast of Just _ -> Nothing Nothing -> enableForecast (astartupopts ui) (ui^.cliOpts) ^. forecast -- | Enable forecasting in this CliOpts. -- If it previously specified a forecast period, or else if the given ui startup options did, -- preserve that as the forecast period. enableForecast :: UIOpts -> CliOpts -> CliOpts enableForecast startopts currentopts = set forecast mforecast currentopts where mforecast = asum [mcurrentforecastperiod, mstartupforecastperiod, mdefaultforecastperiod] where mcurrentforecastperiod = currentopts ^. forecast mstartupforecastperiod = startopts ^. forecast mdefaultforecastperiod = Just nulldatespan -- | Toggle between showing all and showing only real (non-virtual) items. toggleReal :: UIState -> UIState toggleReal = fromRight err . overEither real not -- PARTIAL: where err = error' "toggleReal: updating Real should not result in an error" -- | Toggle the ignoring of balance assertions. toggleIgnoreBalanceAssertions :: UIState -> UIState toggleIgnoreBalanceAssertions = over ignore_assertions not -- | Step through larger report periods, up to all. growReportPeriod :: Day -> UIState -> UIState growReportPeriod _d = updateReportPeriod periodGrow -- | Step through smaller report periods, down to a day. shrinkReportPeriod :: Day -> UIState -> UIState shrinkReportPeriod d = updateReportPeriod (periodShrink d) -- | 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 = updateReportPeriod (periodNextIn enclosingspan) -- | 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 = updateReportPeriod (periodPreviousIn enclosingspan) -- | 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 = updateReportPeriod (periodMoveTo d) -- | Clear any report period limits. resetReportPeriod :: UIState -> UIState resetReportPeriod = setReportPeriod PeriodAll -- | Get the report period. reportPeriod :: UIState -> Period reportPeriod = (^.period) -- | Set the report period. setReportPeriod :: Period -> UIState -> UIState setReportPeriod p = updateReportPeriod (const p) -- | Update report period by a applying a function. updateReportPeriod :: (Period -> Period) -> UIState -> UIState updateReportPeriod updatePeriod = fromRight err . overEither period updatePeriod -- PARTIAL: where err = error' "updateReportPeriod: updating period should not result in an error" -- | Apply a new filter query, or return the failing query. setFilter :: String -> UIState -> Either String UIState setFilter s = first (const s) . setEither querystring (words'' queryprefixes $ T.pack s) -- | Reset some filters & toggles. resetFilter :: UIState -> UIState resetFilter = set querystringNoUpdate [] . set realNoUpdate False . set statusesNoUpdate [] . set empty__ True -- set period PeriodAll . set rsQuery Any . set rsQueryOpts [] -- -- | Reset all options state to exactly what it was at startup -- -- (preserving any command-line options/arguments). -- resetOpts :: UIState -> UIState -- resetOpts ui@UIState{astartupopts} = ui{aopts=astartupopts} resetDepth :: UIState -> UIState resetDepth = updateReportDepth (const mempty) -- | Get the maximum account depth in the current journal. maxDepth :: UIState -> Int maxDepth UIState{ajournal=j} = getMax . foldMap (Max . accountNameLevel) $ journalAccountNamesDeclaredOrImplied 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 = updateReportDepth dec ui where dec (DepthSpec (Just d) _) = DepthSpec (Just $ max 0 (d-1)) [] dec (DepthSpec Nothing _) = DepthSpec (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 = updateReportDepth inc where inc (DepthSpec Nothing _) = DepthSpec Nothing [] inc (DepthSpec (Just d) _) = DepthSpec (Just $ d + 1) [] -- | 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 = updateReportDepth (const $ DepthSpec mdepth []) getDepth :: UIState -> Maybe Int getDepth = dsFlatDepth . (^.depth) -- | Update report depth by a applying a function. If asked to set a depth less -- than zero, it will leave it unchanged. updateReportDepth :: (DepthSpec -> DepthSpec) -> UIState -> UIState updateReportDepth updateDepth ui = over reportSpec update ui where update = fromRight (error' "updateReportDepth: updating depth should not result in an error") -- PARTIAL: . updateReportSpecWith (\ropts -> ropts{depth_=clipDepth ropts $ updateDepth (depth_ ropts)}) clipDepth _ (DepthSpec Nothing _) = mempty clipDepth ropts ds@(DepthSpec (Just d) _) | d < 0 = depth_ ropts | d >= maxDepth ui = mempty | otherwise = ds -- | Open the minibuffer, setting its content to the current query with the cursor at the end. showMinibuffer :: T.Text -> Maybe String -> UIState -> UIState showMinibuffer label moldq ui = setMode (Minibuffer label e) ui where e = applyEdit gotoEOL $ editor MinibufferEditor (Just 1) oldq oldq = fromMaybe (T.unpack . T.unwords . map textQuoteIfNeeded $ ui^.querystring) moldq -- | Close the minibuffer, discarding any edit in progress. closeMinibuffer :: UIState -> UIState closeMinibuffer = setMode Normal setMode :: Mode -> UIState -> UIState setMode m ui = ui{aMode=m} pushScreen :: Screen -> UIState -> UIState pushScreen scr ui = dbg1Msg ("pushing screen " <> showScreenId scr <> ". " <> showScreenStack "" showScreenId ui1) ui1 where ui1 = ui{aPrevScreens=aScreen ui:aPrevScreens ui, aScreen=scr } popScreen :: UIState -> UIState popScreen ui@UIState{aPrevScreens = s : ss} = dbg1Msg ("popping screen " <> showScreenId (aScreen ui) <> ". " <> showScreenStack "" showScreenId ui1) ui1 where ui1 = ui{aPrevScreens = ss ,aScreen = s } popScreen ui = ui -- | Reset options to their startup values, discard screen navigation history, -- and return to the top screen, regenerating it with the startup options -- and the provided reporting date. resetScreens :: Day -> UIState -> UIState resetScreens d ui@UIState{astartupopts=origopts, ajournal=j, aScreen=s,aPrevScreens=ss} = ui{aopts=origopts, aPrevScreens=[], aScreen=topscreen', aMode=Normal} where topscreen' = screenUpdate origopts d j $ lastDef s ss -- | Given a new journal and reporting date, save the new journal in the ui state, -- then regenerate the content of all screens in the stack -- (using the ui state's current options), preserving the screen navigation history. -- Note, does not save the reporting date. -- -- XXX Currently this does not properly regenerate the transaction screen or error screen, -- which depend on state from their parent(s); those screens' handlers must do additional work, which is fragile. regenerateScreens :: Journal -> Day -> UIState -> UIState regenerateScreens j d ui@UIState{aopts=opts, aScreen=s,aPrevScreens=ss} = ui{ajournal=j, aScreen=screenUpdate opts d j s, aPrevScreens=map (screenUpdate opts d j) ss} hledger-ui-1.50.3/Hledger/UI/UITypes.hs0000644000000000000000000003325715060570701015613 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 FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE EmptyDataDeriving #-} module Hledger.UI.UITypes where -- import Control.Concurrent (threadDelay) -- import GHC.IO (unsafePerformIO) import Data.Text (Text) import Data.Time.Calendar (Day) import Brick.Widgets.List (List) import Brick.Widgets.Edit (Editor) import Lens.Micro.Platform (makeLenses) import Text.Show.Functions () -- import the Show instance for functions. Warning, this also re-exports it import Hledger import Hledger.Cli (HasCliOpts(..)) import Hledger.UI.UIOptions 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'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 { -- unchanging: astartupopts :: UIOpts -- ^ the command-line options and query arguments specified at program start -- can change while program runs: ,aopts :: UIOpts -- ^ the command-line options and query arguments currently in effect ,ajournal :: Journal -- ^ the journal being viewed (can change with --watch) ,aPrevScreens :: [Screen] -- ^ previously visited screens, most recent first (XXX silly, reverse these) ,aScreen :: Screen -- ^ the currently active screen ,aMode :: Mode -- ^ the currently active mode on the current screen } deriving (Show) -- | Any screen can be in one of several modes, which modifies -- its rendering and event handling. -- The mode resets to Normal when entering a new screen. data Mode = Normal | Help | Minibuffer Text (Editor String Name) deriving (Show,Eq) -- Ignore the editor when comparing Modes. instance Eq (Editor l n) where _ == _ = True -- Unique names required for brick widgets, viewports, cursor locations etc. data Name = HelpDialog | MinibufferEditor | MenuList | AccountsViewport | AccountsList | RegisterViewport | RegisterList | TransactionEditor deriving (Ord, Show, Eq) -- Unique names for screens the user can navigate to from the menu. data ScreenName = Accounts | CashScreen | Balancesheet | Incomestatement deriving (Ord, Show, Eq) ---------------------------------------------------------------------------------------------------- -- | hledger-ui screen types, v1, "one screen = one module" -- These types aimed for maximum decoupling of modules and ease of adding more screens. -- A new screen requires -- 1. a new constructor in the Screen type, -- 2. a new module implementing init/draw/handle functions, -- 3. a call from any other screen which enters it. -- 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 :: BrickEvent Name AppEvent -> EventM Name 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 :: BrickEvent Name AppEvent -> EventM Name 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 :: BrickEvent Name AppEvent -> EventM Name 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 :: BrickEvent Name AppEvent -> EventM Name UIState () -- -- -- ,esError :: String -- ^ error message to show -- } -- deriving (Show) ---------------------------------------------------------------------------------------------------- -- | hledger-ui screen types, v2, "more parts, but simpler parts" -- These types aim to be more restrictive, allowing fewer invalid states, and easier to inspect -- and debug. The screen types store only state, not behaviour (functions), and there is no longer -- a circular dependency between UIState and Screen. -- A new screen requires -- 1. a new constructor in the Screen type -- 2. a new screen state type if needed -- 3. a new case in toAccountsLikeScreen if needed -- 4. new cases in the uiDraw and uiHandle functions -- 5. new constructor and updater functions in UIScreens, and a new case in screenUpdate -- 6. a new module implementing draw and event-handling functions -- 7. a call from any other screen which enters it (eg the menu screen, a new case in msEnterScreen) -- 8. if it appears on the main menu: a new menu item in msNew -- cf https://github.com/jtdaugherty/brick/issues/379#issuecomment-1192000374 -- | The various screens which a user can navigate to in hledger-ui, -- along with any screen-specific parameters or data influencing what they display. -- (The separate state types add code noise but seem to reduce partial code/invalid data a bit.) data Screen = MS MenuScreenState | AS AccountsScreenState | CS AccountsScreenState | BS AccountsScreenState | IS AccountsScreenState | RS RegisterScreenState | TS TransactionScreenState | ES ErrorScreenState deriving (Show) -- | A subset of the screens which reuse the account screen's state and logic. -- Such Screens can be converted to and from this more restrictive type -- for cleaner code. data AccountsLikeScreen = ALS (AccountsScreenState -> Screen) AccountsScreenState deriving (Show) toAccountsLikeScreen :: Screen -> Maybe AccountsLikeScreen toAccountsLikeScreen scr = case scr of AS ass -> Just $ ALS AS ass CS ass -> Just $ ALS CS ass BS ass -> Just $ ALS BS ass IS ass -> Just $ ALS IS ass _ -> Nothing fromAccountsLikeScreen :: AccountsLikeScreen -> Screen fromAccountsLikeScreen (ALS scons ass) = scons ass data MenuScreenState = MSS { -- view data: _mssList :: List Name MenuScreenItem -- ^ list widget showing screen names ,_mssUnused :: () -- ^ dummy field to silence warning } deriving (Show) -- Used for the accounts screen and similar screens. data AccountsScreenState = ASS { -- screen parameters: _assSelectedAccount :: AccountName -- ^ a copy of the account name from the list's selected item (or "") -- view data derived from options, reporting date, journal, and screen parameters: ,_assList :: List Name AccountsScreenItem -- ^ list widget showing account names & balances } deriving (Show) data RegisterScreenState = RSS { -- screen parameters: _rssAccount :: AccountName -- ^ the account this register is for ,_rssForceInclusive :: Bool -- ^ should this register always include subaccount transactions, -- even when in flat mode ? (ie because entered from a -- depth-clipped accounts screen item) -- view data derived from options, reporting date, journal, and screen parameters: ,_rssList :: List Name RegisterScreenItem -- ^ list widget showing transactions affecting this account } deriving (Show) data TransactionScreenState = TSS { -- screen parameters: _tssAccount :: AccountName -- ^ the account whose register we entered this screen from ,_tssTransactions :: [NumberedTransaction] -- ^ the transactions in that register, which we can step through ,_tssTransaction :: NumberedTransaction -- ^ the currently displayed transaction, and its position in the list } deriving (Show) data ErrorScreenState = ESS { -- screen parameters: _essError :: String -- ^ error message to show ,_essUnused :: () -- ^ dummy field to silence warning } deriving (Show) -- | An item in the menu screen's list of screens. data MenuScreenItem = MenuScreenItem { msItemScreenName :: Text -- ^ screen display name ,msItemScreen :: ScreenName -- ^ an internal name we can use to find the corresponding screen } 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 ,asItemMixedAmount :: Maybe MixedAmount -- ^ mixed amount to display } deriving (Show) -- | An item in the register screen's list of transactions in the current account. data RegisterScreenItem = RegisterScreenItem { rsItemDate :: Text -- ^ date ,rsItemStatus :: Status -- ^ transaction status ,rsItemDescription :: Text -- ^ description ,rsItemOtherAccounts :: Text -- ^ other accounts ,rsItemChangeAmount :: WideBuilder -- ^ the change to the current account from this transaction ,rsItemBalanceAmount :: WideBuilder -- ^ the balance or running total after this transaction ,rsItemTransaction :: Transaction -- ^ the full transaction } deriving (Show) type NumberedTransaction = (Integer, Transaction) -- These TH calls must come after most of the types above. -- Fields named _foo produce lenses named foo. -- XXX foo fields producing fooL lenses would be preferable makeLenses ''MenuScreenState makeLenses ''AccountsScreenState makeLenses ''RegisterScreenState makeLenses ''TransactionScreenState makeLenses ''ErrorScreenState ---------------------------------------------------------------------------------------------------- -- | Error message to use in case statements adapting to the different Screen shapes. errorWrongScreenType :: String -> a errorWrongScreenType lbl = -- unsafePerformIO $ threadDelay 2000000 >> -- delay to allow console output to be seen error' (unwords [lbl, "called with wrong screen type, should not happen"]) -- 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 l = l1 & listElementsL .~ (l1^.listElementsL <> l^.listElementsL) uioptslens f ui = (\x -> ui{aopts=x}) <$> f (aopts ui) instance HasCliOpts UIState where cliOpts = uioptslens.cliOpts instance HasInputOpts UIState where inputOpts = uioptslens.inputOpts instance HasBalancingOpts UIState where balancingOpts = uioptslens.balancingOpts instance HasReportSpec UIState where reportSpec = uioptslens.reportSpec instance HasReportOptsNoUpdate UIState where reportOptsNoUpdate = uioptslens.reportOptsNoUpdate instance HasReportOpts UIState where reportOpts = uioptslens.reportOpts hledger-ui-1.50.3/Hledger/UI/UIUtils.hs0000644000000000000000000005336415107137141015607 0ustar0000000000000000{- | Rendering & misc. helpers. -} {-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE LambdaCase #-} module Hledger.UI.UIUtils ( borderDepthStr ,borderKeysStr ,borderKeysStr' ,borderPeriodStr ,borderQueryStr ,defaultLayout ,helpDialog ,helpHandle ,minibuffer ,moveDownEvents ,moveLeftEvents ,moveRightEvents ,moveUpEvents ,normaliseMovementKeys ,renderToggle ,renderToggle1 ,replaceHiddenAccountsNameWith ,scrollSelectionToMiddle ,get' ,put' ,modify' ,suspend ,redraw ,reportSpecAddQuery ,reportSpecSetFutureAndForecast ,listScrollPushingSelection ,dbgui ,dbguiIO ,dbguiEv ,dbguiScreensEv ,showScreenId ,showScreenRegisterDescriptions ,showScreenSelection ,mapScreens ,uiNumBlankItems ,showScreenStack ,sendVtyEvents ) 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, listSelected, listMoveDown, listMoveUp, GenericList, listElements) import Control.Concurrent.STM (atomically, writeTChan) -- GHC only import Control.Monad.IO.Class import Data.Bifunctor (second) import Data.List import Data.Text qualified as T import Data.Time (addDays) import Graphics.Vty (Event(..),Key(..),Modifier(..),Vty(..),Color,Attr,currentAttr,refresh, displayBounds -- ,Output(displayBounds,mkDisplayContext),DisplayContext(..) ,Vty (inputIface), InternalEvent (InputEvent), Input (eventChannel) ) import Lens.Micro.Platform import Hledger -- import Hledger.Cli.CliOptions (CliOpts(reportspec_)) import Hledger.Cli.DocFiles -- import Hledger.UI.UIOptions (UIOpts(uoCliOpts)) import Hledger.UI.UITypes import Data.Vector (Vector) import Data.Vector qualified as V -- | On posix platforms, send the system STOP signal to suspend the -- current program. On windows, does nothing. -- (Though, currently hledger-ui is not built on windows.) #ifdef mingw32_HOST_OS suspendSignal :: IO () suspendSignal = return () #else import System.Posix.Signals suspendSignal :: IO () suspendSignal = raiseSignal sigSTOP #endif -- Debug logging for UI state changes. -- A good place to log things of interest while debugging, see commented examples below. get' = do ui <- get dbguiEv $ "getting state: " ++ showScreenStack "" showScreenSelection ui -- (head $ lines $ pshow $ aScreen x) -- ++ " " ++ (show $ map tdescription $ jtxns $ ajournal x) -- dbguiEv $ ("query: "++) $ pshow' $ x & aopts & uoCliOpts & reportspec_ & _rsQuery -- dbguiScreensEv "getting" showScreenId x -- dbguiScreensEv "getting, with register descriptions" showScreenRegisterDescriptions x return ui put' ui = do dbguiEv $ "putting state: " ++ showScreenStack "" showScreenSelection ui -- (head $ lines $ pshow $ aScreen x) -- ++ " " ++ (show $ map tdescription $ jtxns $ ajournal x) -- dbguiEv $ ("query: "++) $ pshow' $ x & aopts & uoCliOpts & reportspec_ & _rsQuery -- dbguiScreensEv "putting" showScreenId x -- dbguiScreensEv "putting, with register descriptions" showScreenRegisterDescriptions x put ui modify' f = do ui <- get let ui' = f ui dbguiEv $ "getting state: " ++ (showScreenStack "" showScreenSelection ui) dbguiEv $ "putting state: " ++ (showScreenStack "" showScreenSelection ui') -- (head $ lines $ pshow $ aScreen x') -- ++ " " ++ (show $ map tdescription $ jtxns $ ajournal x') -- dbguiEv $ ("from: "++) $ pshow' $ x & aopts & uoCliOpts & reportspec_ & _rsQuery -- dbguiEv $ ("to: "++) $ pshow' $ x' & aopts & uoCliOpts & reportspec_ & _rsQuery -- dbguiScreensEv "getting" showScreenId x -- dbguiScreensEv "putting" showScreenId x' -- dbguiScreensEv "getting, with register descriptions" showScreenRegisterDescriptions x -- dbguiScreensEv "putting, with register descriptions" showScreenRegisterDescriptions x' modify f -- | 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 :: Ord a => s -> EventM a s () suspend st = suspendAndResume $ suspendSignal >> return st -- | Tell vty to redraw the whole screen. redraw :: EventM a s () redraw = getVtyHandle >>= liftIO . refresh -- | 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 -- topBottomBorderWithLabel 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 :: Widget Name helpDialog = Widget Fixed Fixed $ do c <- getContext render $ withDefAttr (attrName "help") $ renderDialog (dialog (Just $ str "Help (LEFT/ESC/?/q to close help)") Nothing (c^.availWidthL)) $ -- (Just (0,[("ok",())])) padTop (Pad 0) $ padLeft (Pad 1) $ padRight (Pad 1) $ vBox [ hBox [ padRight (Pad 1) $ vBox [ withAttr (attrName "help" <> attrName "heading") $ str "Navigation" ,renderKey ("UP/DOWN/PUP/PDN/HOME/END/k/j/C-p/C-n", "") ,str " move selection up/down" ,renderKey ("RIGHT/l/C-f", "show txns, or txn detail") ,renderKey ("LEFT/h/C-b ", "go back/see other screens") ,renderKey ("ESC ", "cancel, or reset app state") ,str " " ,withAttr (attrName "help" <> attrName "heading") $ str "Accounts screens" ,renderKey ("1234567890-+ ", "set/adjust depth limit") ,renderKey ("t ", "toggle accounts tree/list mode") ,renderKey ("H ", "toggle historical balance/change") ,str " " ,withAttr (attrName "help" <> attrName "heading") $ str "Register screens" ,renderKey ("t ", "toggle subaccount txns\n(and accounts tree/list mode)") ,renderKey ("H ", "toggle historical/period total") ,str " " ,withAttr (attrName "help" <> attrName "heading") $ str "Help" ,renderKey ("? ", "toggle this help") ,renderKey ("p/m/i", "while help is open:\nshow manual in pager/man/info") ,str " " ] ,padLeft (Pad 1) $ padRight (Pad 0) $ vBox [ withAttr (attrName "help" <> attrName "heading") $ str "Filtering" ,renderKey ("/ ", "set a filter query") ,renderKey ("F ", "show future & forecast txns") ,renderKey ("R ", "show real/all postings") ,renderKey ("z ", "show nonzero/all amounts") ,renderKey ("U/P/C ", "show unmarked/pending/cleared") ,renderKey ("S-DOWN /S-UP ", "shrink/grow period") ,renderKey ("S-RIGHT/S-LEFT", "next/previous period") ,renderKey ("T ", "set period to today") ,renderKey ("DEL ", "reset filters") ,str " " ,withAttr (attrName "help" <> attrName "heading") $ str "Other" ,renderKey ("a ", "add transaction (hledger add)") ,renderKey ("A ", "add transaction (hledger-iadd)") ,renderKey ("B ", "show amounts/costs") ,renderKey ("E ", "open editor") ,renderKey ("I ", "toggle balance assertions") ,renderKey ("V ", "show amounts/market values") ,renderKey ("g ", "reload data") ,renderKey ("C-l ", "redraw & recenter") ,renderKey ("C-z ", "suspend") ,renderKey ("q ", "quit") ] ] -- ,vBox [ -- str " " -- ,hCenter $ padLeftRight 1 $ -- hCenter (str "MANUAL") -- <=> -- hCenter (hBox [ -- renderKey ("t", "text") -- ,str " " -- ,renderKey ("m", "man page") -- ,str " " -- ,renderKey ("i", "info") -- ]) -- ] ] where renderKey (key,desc) = withAttr (attrName "help" <> attrName "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 :: BrickEvent Name AppEvent -> EventM Name UIState () helpHandle ev = do ui <- get let ui' = ui{aMode=Normal} case ev of VtyEvent e | e `elem` closeHelpEvents -> put' ui' VtyEvent (EvKey (KChar 'p') []) -> suspendAndResume (runPagerForTopic "hledger-ui" Nothing >> return ui') VtyEvent (EvKey (KChar 'm') []) -> suspendAndResume (runManForTopic "hledger-ui" Nothing >> return ui') VtyEvent (EvKey (KChar 'i') []) -> suspendAndResume (runInfoForTopic "hledger-ui" Nothing >> return ui') _ -> return () where closeHelpEvents = moveLeftEvents ++ [EvKey KEsc [], EvKey (KChar '?') [], EvKey (KChar 'q') []] -- | Draw the minibuffer with the given label. minibuffer :: T.Text -> Editor String Name -> Widget Name minibuffer string ed = forceAttr (attrName "border" <> attrName "minibuffer") $ hBox [txt $ string <> ": ", renderEditor (str . unlines) True ed] borderQueryStr :: String -> Widget Name borderQueryStr "" = str "" borderQueryStr qry = str " matching " <+> withAttr (attrName "border" <> attrName "query") (str qry) borderDepthStr :: Maybe Int -> Widget Name borderDepthStr Nothing = str "" borderDepthStr (Just d) = str " to depth " <+> withAttr (attrName "border" <> attrName "query") (str $ show d) borderPeriodStr :: String -> Period -> Widget Name borderPeriodStr _ PeriodAll = str "" borderPeriodStr preposition p = str (" "++preposition++" ") <+> withAttr (attrName "border" <> attrName "query") (str . T.unpack $ showPeriod p) borderKeysStr :: [(String,String)] -> Widget Name borderKeysStr = borderKeysStr' . map (second str) borderKeysStr' :: [(String,Widget Name)] -> Widget Name borderKeysStr' keydescs = hBox $ intersperse sep $ [withAttr (attrName "border" <> attrName "key") (str keys) <+> str ":" <+> desc | (keys, desc) <- keydescs] where -- sep = str " | " sep = str " " -- | Show both states of a toggle ("aaa/bbb"), highlighting the active one. renderToggle :: Bool -> String -> String -> Widget Name renderToggle isright l r = let bold = withAttr (attrName "border" <> attrName "selected") in if isright then str (l++"/") <+> bold (str r) else bold (str l) <+> str ("/"++r) -- | Show a toggle's label, highlighted (bold) when the toggle is active. renderToggle1 :: Bool -> String -> Widget Name renderToggle1 isactive l = let bold = withAttr (attrName "border" <> attrName "selected") in if isactive then bold (str l) else str l -- temporary shenanigans: -- | Replace the special account names "*" and "..." (from balance reports 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 (attrName "border") $ toplabel <+> str debugmsg) <=> body' <=> hBorderWithLabel (withAttr (attrName "border") bottomlabel) ---- XXX should be equivalent to the above, but isn't (page down goes offscreen) --_topBottomBorderWithLabel :: Widget Name -> Widget Name -> Widget Name --_topBottomBorderWithLabel 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 rsDraw). margin :: Int -> Int -> Maybe Color -> Widget Name -> Widget Name margin h v mcolour w = Widget Greedy Greedy $ do ctx <- getContext let w' = vLimit (ctx^.availHeightL - v*2) $ hLimit (ctx^.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 [(attrName "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 :: Brick.Widgets.List.List Name item -> EventM Name UIState () scrollSelectionToMiddle list = do case list^.listSelectedL of Nothing -> return () Just selectedrow -> do Vty{outputIface} <- getVtyHandle pageheight <- dbg4 "pageheight" . snd <$> liftIO (displayBounds outputIface) let itemheight = dbg4 "itemheight" $ list^.listItemHeightL itemsperpage = dbg4 "itemsperpage" $ pageheight `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 $ list^.listNameL) toprow -- arrow keys vi keys emacs keys enter key 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], EvKey KEnter []] normaliseMovementKeys ev | ev `elem` moveUpEvents = EvKey KUp [] | ev `elem` moveDownEvents = EvKey KDown [] | ev `elem` moveLeftEvents = EvKey KLeft [] | ev `elem` moveRightEvents = EvKey KRight [] | otherwise = ev -- | Restrict the ReportSpec's query by adding the given additional query. reportSpecAddQuery :: Query -> ReportSpec -> ReportSpec reportSpecAddQuery q rspec = rspec{_rsQuery=simplifyQuery $ And [_rsQuery rspec, q]} -- | Update the ReportSpec's query to exclude future transactions (later than its "today" date) -- and forecast transactions (generated by --forecast), if the given forecast DateSpan is Nothing, -- and include them otherwise. reportSpecSetFutureAndForecast :: Maybe DateSpan -> ReportSpec -> ReportSpec reportSpecSetFutureAndForecast fcast rspec = rspec{_rsQuery=simplifyQuery $ And [_rsQuery rspec, periodq, excludeforecastq fcast]} where periodq = Date . periodAsDateSpan . period_ $ _rsReportOpts rspec -- Except in forecast mode, exclude future/forecast transactions. excludeforecastq (Just _) = Any excludeforecastq Nothing = -- not:date:tomorrow- not:tag:generated-transaction And [ Not (Date $ DateSpan (Just $ Exact $ addDays 1 $ _rsDay rspec) Nothing) ,Not generatedTransactionTag ] -- Vertically scroll the named list's viewport with the given number of non-empty items -- by the given positive or negative number of items (usually 1 or -1). -- The selection will be moved when necessary to keep it visible and allow the scroll. listScrollPushingSelection :: Name -> Int -> Int -> EventM Name (Brick.Widgets.List.List Name item) (GenericList Name Vector item) listScrollPushingSelection name listheight scrollamt = do list <- get viewportScroll name `vScrollBy` scrollamt mvp <- lookupViewport name case mvp of Just VP{_vpTop, _vpSize=(_,vpheight)} -> do let mselidx = listSelected list case mselidx of Just selidx -> return $ pushsel list where pushsel | scrollamt > 0, selidx <= _vpTop && selidx < (listheight-1) = listMoveDown | scrollamt < 0, selidx >= _vpTop + vpheight - 1 && selidx > 0 = listMoveUp | otherwise = id _ -> return list _ -> return list -- | A debug logging helper for hledger-ui code: at any debug level >= 1, -- logs the string to hledger-ui.log before returning the second argument. -- Uses unsafePerformIO. dbgui :: String -> a -> a dbgui = dbg1Msg -- | Like dbgui, but convenient to use in IO. dbguiIO :: String -> IO () dbguiIO = dbg1MsgIO -- | Like dbgui, but convenient to use in EventM handlers. dbguiEv :: String -> EventM Name s () dbguiEv s = dbg1Msg s $ return () -- | Like dbguiEv, but log a compact view of the current screen stack. -- See showScreenStack. -- To just log the stack: @dbguiScreensEv "" showScreenId ui@ dbguiScreensEv :: String -> (Screen -> String) -> UIState -> EventM Name UIState () dbguiScreensEv postfix showscr ui = dbguiEv $ showScreenStack postfix showscr ui -- Render a compact labelled view of the current screen stack, -- adding the given postfix to the label (can be empty), -- from the topmost screen to the currently-viewed screen, -- with each screen rendered by the given rendering function. -- Useful for inspecting states across the whole screen stack. -- Some screen rendering functions are -- @showScreenId@, @showScreenSelection@, @showScreenRegisterDescriptions@. -- -- Eg to just show the stack: @showScreenStack "" showScreenId ui@ -- -- To to show the stack plus selected item indexes: @showScreenStack "" showScreenSelection ui@ -- showScreenStack :: String -> (Screen -> String) -> UIState -> String showScreenStack postfix showscr ui = concat [ "screen stack" ,if null postfix then "" else ", " ++ postfix ,": " ,unwords $ mapScreens showscr ui ] -- | Run a function on each screen in a UIState's screen "stack", -- from topmost screen down to currently-viewed screen. mapScreens :: (Screen -> a) -> UIState -> [a] mapScreens f UIState{aPrevScreens, aScreen} = map f $ reverse $ aScreen : aPrevScreens -- Show a screen's compact id (first letter of its constructor). showScreenId :: Screen -> String showScreenId = \case MS _ -> "M" -- menu AS _ -> "A" -- all accounts CS _ -> "C" -- cash accounts BS _ -> "B" -- bs accounts IS _ -> "I" -- is accounts RS _ -> "R" -- menu TS _ -> "T" -- transaction ES _ -> "E" -- error -- Show a screen's compact id, plus for register screens, the transaction descriptions. showScreenRegisterDescriptions :: Screen -> String showScreenRegisterDescriptions scr = case scr of RS sst -> ((showScreenId scr ++ ":") ++) $ -- menu intercalate "," $ map (T.unpack . rsItemDescription) $ takeWhile (not . T.null . rsItemDate) $ V.toList $ listElements $ _rssList sst _ -> showScreenId scr -- Show a screen's compact id, plus index of its selected list item if any. showScreenSelection :: Screen -> String showScreenSelection = \case MS MSS{_mssList} -> "M" ++ (maybe "" show $ listSelected _mssList) -- menu AS ASS{_assList} -> "A" ++ (maybe "" show $ listSelected _assList) -- all accounts CS ASS{_assList} -> "C" ++ (maybe "" show $ listSelected _assList) -- cash accounts BS ASS{_assList} -> "B" ++ (maybe "" show $ listSelected _assList) -- bs accounts IS ASS{_assList} -> "I" ++ (maybe "" show $ listSelected _assList) -- is accounts RS RSS{_rssList} -> "R" ++ (maybe "" show $ listSelected _rssList) -- menu TS _ -> "T" -- transaction ES _ -> "E" -- error -- | How many blank items to add to lists to fill the full window height. uiNumBlankItems :: Int uiNumBlankItems -- | debugLevel >= uiDebugLevel = 0 -- suppress to improve debug output. -- | otherwise = 100 -- 100 ought to be enough for anyone -- Send some events to vty, atomically so they won't have other events interleaved. -- (But there may be events already in the channel ahead of them.) sendVtyEvents :: [Event] -> EventM n s () sendVtyEvents evs = do input <- eventChannel . inputIface <$> getVtyHandle liftIO $ atomically $ mapM_ (writeTChan input . InputEvent) evs hledger-ui-1.50.3/app/hledger-ui.hs0000644000000000000000000000011315054061121015142 0ustar0000000000000000import Hledger.UI.Main (hledgerUiMain) main :: IO () main = hledgerUiMain hledger-ui-1.50.3/CHANGES.md0000644000000000000000000007103415107174442013417 0ustar0000000000000000 User-visible changes in hledger-ui. See also the hledger changelog. # 1.50.3 2025-11-18 - `--watch` mode now also detects changes from apps which overwrite the file, such as VS Code. (Caleb Maclennan) - When hledger-ui is started with --pivot, re-enabling balance assertions with the I key now does a full journal reload, to check assertions more accurately. [#2451] - The old "threaded" build flag, which cabal could turn off, has been dropped. [#2495] - Allow brick 2.10, vty 6.5. - Uses hledger 1.50.3. # 1.50.2 2025-09-26 - Uses hledger 1.50.2 # 1.50.1 2025-09-16 Fixes - When the journal is reloaded by the `g` key or `--watch`, the `--pivot` (and `--obfuscate`) options are now preserved, and spurious errors are avoided. [#2451] - The transaction screen and error screen now update on data changes like other screens, eg when using the `E` or `g` keys or `--watch`. [#2014], [#2288] - The `Z` key (and the `-E` command line flag) toggle zero-balance accounts again. (Stephen Morgan, [#2454]) Improvements - Debug output has improved, eg it's easier to see changes to the screen stack. API - Hledger.UI.ErrorScreen: uiReloadJournal -> uiReload, uiReloadJournalIfChanged -> uiReloadIfFileChanged - Hledger.UI.UIState: enableForecastPreservingPeriod -> enableForecast # 1.50 2025-09-03 Breaking changes - hledger now requires at least GHC 9.6 (and base 4.18), to ease maintenance. Improvements - Use hledger 1.50 # 1.43.2 2025-06-13 - Use hledger-1.43.2 # 1.43.1 2025-06-04 - More error messages were made consistent, hiding call stack etc. [#2367] - Allow brick 2.9 # 1.43 2025-06-01 Fixes - Require fsnotify >=0.4.2.0, which fixes some events being ignored on mac, possibly making hledger-ui --watch more reliable in this regard. Improvements - CLI error messages now have consistent clean format independent of GHC version. [#2367] - Support GHC 9.12. Docs - Update --watch docs. - Drop obsolete mention of Windows non-support. # 1.42.2 2025-05-16 Fixes - Require fsnotify-0.4.2.0+/hfsevents-0.1.8+, which fixes some events being ignored on mac (see https://github.com/luite/hfsevents/pull/19), which should help `hledger-ui --watch` a little. - Require extra >= 1.7.11, fixing the stack8.10.yaml build. (Thomas Miedema) Docs - Update --watch notes - Drop obsolete Windows non-support note # 1.42.1 2025-03-12 - allow vty 6.4 # 1.42 2025-03-07 Fixes - Startup arguments provided at the CLI are no longer passed to `add` when pressing the `a` key. [#2313] Improvements - Allow vty 6.3. - Allow brick 2.8. # 1.41 2024-12-09 Breaking changes - When built with ghc 9.10.1, error messages are displayed with two extra trailing newlines. Fixes - V (value) and C (cost) toggle keys once again reset each other as they should (broken since 1.21). (Gal Lakovnik Gorenec, [#2284]) - Bash shell completions are now up to date. [#986] Features Improvements - Allow clipping depth to be configured per account (until adjusted in app, at least). (Stephen Morgan, [#2292]) - Added helix as a supported editor for the `e` key. (amano.kenji) - Added --pager and --color options as in hledger, affecting command line help. Also --color=no forces use of the "terminal" theme. - Added a new `debug` build flag. Builds made with ghc 9.10+ and this flag will show some kind of partial stack trace if the program exits with an error. These will improve in future ghc versions. - Disabled the unused `ghcdebug` build flag and ghc-debug support, for now. - Allow megaparsec 9.7. - Allow brick 2.5, 2.6. - Avoid brick 2.3.2, which doesn't build on windows. - ghc 9.10 / base 4.20 are now supported. Docs - Mention that period navigation uses standard periods [#2293] - Install, manual: new shell completions doc. [#986] # 1.40 2024-09-09 Improvements - The menu screen now supports the shift arrow and shift T keys, and its header shows any narrowed time period in effect, like other screens. - Support brick 2.4. Docs - The description of the shift-T key (set period to today) has been fixed. - The shift arrow keys and period narrowing have been clarified # 1.34 2024-06-01 Features - You can now get a quick list of example command lines by running with `--tldr` (or just `--tl`). For best appearance, install the [`tldr`][tldr] client, though it's not required. Improvements - The general flags in `--help` have been updated and grouped, consistent with hledger. - When built with the `ghcdebug` flag and started with `--debug=-1`, hledger-ui can be controlled by [ghc-debug] clients like ghc-debug-brick or a ghc-debug query script, for analysing memory/profile info. [tldr]: https://tldr.sh [ghc-debug]: https://gitlab.haskell.org/ghc/ghc-debug # 1.33.1 2024-05-02 - Require vty-windows-0.2.0.2+ to avoid display problems in recent MS Terminal on Windows. - We no longer require process >=1.6.19.0, as it hurt installability and seems not strictly needed. [#2149] [#2149]: https://github.com/simonmichael/hledger/issues/2149 # 1.33 2024-04-18 Fixes - Require process 1.6.19.0+ to avoid any vulnerabilities on Windows from [HSEC-2024-0003](https://haskell.github.io/security-advisories/advisory/HSEC-2024-0003.html). Features - Add a `dark` theme. (Jonathan Dowland) Improvements - Allow building with GHC 9.8. - Require safe >=0.3.20. # 1.32.3 2024-01-28 - Use hledger-1.32.3 - Allow vty 6.2, brick 2.3 # 1.32.2 2023-12-31 Features - hledger-ui is now available on Windows (ShrykeWindgrace) Improvements - Use Notepad as default editor on Windows (ShrykeWindgrace) - Allow brick 2.2 (Vekhir) - Allow megaparsec 9.6 # 1.32.1 2023-12-07 - Use hledger-1.32.1 # 1.32 2023-12-01 Fixes - The V key now preserves the valuation mode specified at the command line, if any. (#2084) - The hledger-ui package no longer wastefully builds its modules twice. - Add upper bounds for vty & brick. # 1.31 2023-09-03 Improvements - Allow megaparsec 9.5 # 1.30 2023-06-01 Features - A "Cash accounts" screen has been added, showing accounts of the `Cash` type. Improvements - The top-level menu screen is now the default screen. Power users can use the `--cash`/`--bs`/`--is`/`--all` flags to start up in another screen. - "All accounts" screen has been moved to the bottom of the list. - Screens' help footers have been improved. Docs - The transaction screen's inability to update is now noted. - Miscellaneous manual cleanups. # 1.29.2 2023-04-07 Improvements - A pager is used to show --help output when needed, as in `hledger`. Fixes - The corruption in 1.29's info manual is fixed. (#2023) # 1.29.1 2023-03-16 - Allow building with GHC 9.6.1 (#2011) # 1.29 2023-03-11 - In the help dialog, mention that LEFT shows other screens. - In the manual, mention shift-up/down config needed for Terminal.app. # 1.28 2022-12-01 Features - New "Balance sheet accounts" and "Income statement accounts" screens have been added, along with a new top-level "Menu" screen for navigating between these and the "All accounts" screen. - hledger-ui now starts in the "Balance sheet accounts" screen by default (unless no asset/liability/equity accounts can be detected, or command line account query arguments are provided). This provides a more useful default view than the giant "All accounts" list. Or, you can force a particular starting screen with the new --menu/--all/--bs/--is flags (eg, `hledger-ui --all` to replicate the old behaviour). Improvements - The ENTER key is equivalent to RIGHT for navigation. - hledger-ui debug output is now always logged to ./hledger-ui.log rather than the console, --debug with no argument is equivalent to --debug=1, and debug output is much more informative. - Support GHC 9.4. - Support megaparsec 9.3 (Felix Yan) - Support (and require) brick 1.5, fsnotify 0.4.x. Fixes - Mouse-clicking in empty space below the last list item no longer navigates back. It was too obtrusive, eg when you just want to focus the window. You can still navigate back with the mouse by clicking the left edge of the window. - A possible bug with detecting change of date while in --watch mode has been fixed. API - hledger-ui's internal types have been changed to allow fewer invalid states and make it easier to develop and debug. (#1889, #1919). - Debug logging helpers have been added and cleaned up in Hledger.Ui.UIUtils: dbgui dbguiIO dbguiEv dbguiScreensEv mapScreens screenId screenRegisterDescriptions # 1.27.1 2022-09-18 - Uses hledger-1.27.1 # 1.27 2022-09-01 Improvements - At --debug=2 and up, log debug output to ./debug.log. - Use/require brick 1.0+. (#1889) - Use hledger 1.27 # 1.26.1 2022-07-11 - support doclayout 0.4, brick 0.72+ - require safe 0.3.19+ to avoid deprecation warning # 1.26 2022-06-04 - Uses hledger 1.26. # 1.25 2022-03-04 - Uses hledger 1.25. # 1.24.1 2021-12-10 Fixes - An extra "root" account is no longer shown (a regression in 1.24). (#1782) - Declared accounts are now filtered correctly by a not:ACCT query. (#1783) - More reliable --version output, with commit date and without patch level. # 1.24 2021-12-01 Features - hledger-ui can now be controlled with mouse or touchpad. Click to enter things, click left margin or bottom blank area to return to previous screen, and use mouse wheel / swipe to scroll. - In addition to accounts with postings, hledger-ui now also shows declared accounts, even if they are empty (just leaf accounts, not parents). The idea is to show a useful list of accounts out of the box, when all you have is a starter file with account declarations. Improvements - The `Z` key for toggling display of zeroes is now the easier lower-case `z`. - The `--watch` feature now has a convenient short flag, `-w`. - Drop the base-compat-batteries dependency. (Stephen Morgan) - Allow megaparsec 9.2 Fixes - When an invalid regular expression is entered at the `/` (filter) prompt, we now display an error instead of silently ignoring it. (#1394, Stephen Morgan) - Entering the register screen now always positions the selection mid-screen. Previously it would be at bottom of screen on the first entry. - Report layout in the terminal is now robust with more kinds of wide characters, such as emoji. (#895, Stephen Morgan) # 1.23 2021-09-21 Improvements - Require base >=4.11, prevent red squares on Hackage's build matrix. Fixes - Do not display a screen full of .. when there are no transactions. (#822) API changes - Lenses are now available for UIState etc., saving a lot of boilerplate. (Stephen Morgan) - Renamed: ``` version -> packageversion versiondescription -> versionStringFor UIOpts fields ``` # 1.22.2 2021-08-07 - Use hledger 1.22.2. # 1.22.1 2021-08-02 Improvements - Document watch mode and its limitations. (#1617, #911, #836) - Allow megaparsec 9.1. Fixes - Up/down keys work on the transaction screen again (broken since 1.22). (#1607, Stephen Morgan) - Fix a possible off-by-one bug with valuation date when using `V` key on the transaction screen. (If it ever needs to use the journal's last day as valuation date, use that day, not the day after.) # 1.22 2021-07-03 Improvements - Don't reset the `B`/`V` (cost, value) state when reloading with `g` or `--watch`. (Stephen Morgan) - The accounts screen is a little smarter at allocating space to columns. (Stephen Morgan) - Add support for the kakoune editor, and improve the invocations of some other editors. (crocket) - The `--version` flag shows more detail (git tag/patchlevel/commit hash, platform/architecture). (Stephen Morgan) - GHC 9.0 is now officially supported, and GHC 8.0, 8.2, 8.4 are not; building hledger now requires GHC 8.6 or greater. - Added a now-required lower bound on containers. (#1514) Fixes - Queries in the register screen work again (broken in 1.21). (#1523) (Stephen Morgan) - Don't write to `./debug.log` when toggling value with `V`, or when reloading with `g` or `--watch` in the Transaction screen. (#1556) (Simon Michael, Stephen Morgan) # 1.21 2021-03-10 - Register screen: also show transactions below the depth limit, as in 1.19, keeping the register balance in agreement with the balance shown on the accounts screen. This regressed in 1.20. (#1468) - Transaction screen: all decimal places are now shown. On the accounts screen and register screen we round amounts according to commodity display styles, but when you drill down to a transaction you probably want to see the unrounded amounts. (Like print, #cf 931.) - New flags `--man` and `--info` open the man page or info manual. (See hledger changelog) # 1.20.4 2021-01-29 - ui: register: show all txns in/under an account at the depth limit (#1468). In 1.20-1.20.3, the register screen had stopped showing transactions in accounts below a depth limit. Now it properly shows all subaccount transactions, even when there is a depth limit, ensuring that the register's final total matches the balance shown on the account screen. # 1.20.3 2021-01-14 - Use hledger 1.20.3. # 1.20.2 2020-12-28 - Fix loss of capitalisation in part of the manual. - Fix the info manual's node structure. - Use hledger 1.20.2. # 1.20.1 2020-12-15 - Fix the F key (toggle future/forecast transactions), which in 1.20 would only work twice. (#1411) - Fix loss of forecasted transactions when the journal was reloaded while they were hidden. (#1204) # 1.20 2020-12-05 - When entering a query with `/`, malformed queries/regular expressions no longer cause the program to exit. (Stephen Morgan) - Eliding of multicommodity amounts now makes better use of available space. (Stephen Morgan) - `E` now parses the `HLEDGER_UI_EDITOR` or `EDITOR` environment variable correctly on Windows (ignoring the file extension), so if you have that set it should be better at opening your editor at the correct line. - `E` now supports positioning when `HLEDGER_UI_EDITOR` or `EDITOR` is VS Code ("`code`") (#1359) - hledger-ui now has a (human-powered) test suite. # 1.19.1 2020-09-07 - Allow megaparsec 9 # 1.19 2020-09-01 - The --color/--colour=WHEN command line option, support for the NO_COLOR environment variable, and smarter autodetection of colour terminals have been added (#1296) - -t and -l command line flags have been added as short forms of --tree and --flat (#1286) - Flat (AKA list) mode is now the default - t now toggles tree mode, while T sets the "today" period (#1286) - register: multicommodity amounts containing more than two commodities are now elided - register: a transaction dated outside the report period now is not shown even if it has postings dated inside the report period. - ESC now restores exactly the app's state at startup, which includes clearing any report period limit (#1286) - DEL/BS no longer changes the tree/list mode - q now exits help before exiting the app (#1286) - The help dialog's layout is improved # 1.18.1 2020-06-21 - Fix regression in 'F' (#1255) (Dmitry Astapov) # 1.18 2020-06-07 - builds with hledger 1.18 # 1.17.1.1 2020-03-19 - update bounds after some belated hledger-* version bumps # 1.17.1 2020-03-19 - fix a regression, empty register of depth-limited account (fix #1208) - require newer Decimal, math-functions libs to ensure consistent rounding behaviour, even when built with old GHCs/snapshots. hledger uses banker's rounding (rounds to nearest even number, eg 0.5 displayed with zero decimal places is "0"). # 1.17 2020-03-01 - don't enable --auto by default - don't enable --forecast by default; drop the --future flag (#1193) Previously, periodic transactions occurring today were always shown, in both "present" and "future" modes. Now, generation of periodic transactions and display of future transactions (all kinds) are combined as "forecast mode", which can be enabled with --forecast and/or the F key. The --future flag is now a hidden alias for --forecast, and deprecated. # 1.16.2 2020-01-14 - add support for megaparsec 8 (#1175) # 1.16.1 2019-12-03 - use hledger 1.16.1, fixing GHC 8.0/8.2 build # 1.16 2019-12-01 - add support for GHC 8.8, base-compat 0.11 (#1090) - drop support for GHC 7.10 - the B and V keys toggle cost or value display (like the -B and -V command line flags) # 1.15 2019-09-01 - allow brick >=0.47 - use hledger 1.15 # 1.14.2 2019-03-20 - support brick 0.47+ as well, to get into stackage nightly. # 1.14.1 2019-03-20 - require brick <0.47 to fix build (#995) - use hledger 1.14.2 # 1.14 2019-03-01 - use hledger 1.14 # 1.13.1 (2019/02/02) - fix build issues with older brick/stack resolvers; require brick 0.23+ # 1.13 (2019/02/01) - on posix systems, control-z suspends the program - control-l now works everywhere and redraws more reliably - the top status info is clearer - use hledger 1.13 # 1.12.1 (2018/12/10) - avoid build issue with brick 0.44+ (#935) # 1.12 (2018/12/02) - fix "Any" build error with GHC < 8.4 - error screen: always show error position properly (#904) (Mykola Orliuk) - accounts screen: show correct balances when there's only periodic transactions - drop the --status-toggles flag - periodic transactions and transaction modifiers are always enabled. Rule-based transactions and postings are always generated (--forecast and --auto are always on). Experimental. - escape key resets to flat mode. Flat mode is the default at startup. Probably it should reset to tree mode if --tree was used at startup. - tree mode tweaks: add --tree/-T/-F flags, make flat mode the default,\ toggle tree mode with T, ensure a visible effect on register screen - hide future txns by default, add --future flag, toggle with F. You may have transactions dated later than today, perhaps piped from print --forecast or recorded in the journal, which you don't want to see except when forecasting. By default, we now hide future transactions, showing "today's balance". This can be toggled with the F key, which is easier than setting a date query. --present and --future flags have been added to set the initial mode. (Experimental. Interactions with date queries have not been explored.) - quick help tweaks; try to show most useful info first - reorganise help dialog, fit content into 80x25 again - styling tweaks; cyan/blue -> white/yellow - less noisy styling in horizontal borders (#838) - register screen: positive amounts: green -> black The green/red scheme helped distinguish the changes column from the black/red balance column, but the default green is hard to read on the pale background in some terminals. Also the changes column is non-bold now. - use hledger 1.12 # 1.11.1 (2018/10/06) - use hledger 1.11.1 # 1.11 (2018/9/30) - use hledger 1.11 # 1.10.1 (2018/7/3) - restore support for fsnotify 0.2.1.2, as well as 0.3.x (#833) - fix a vty version bound & possibly build failures with old vty (#494) # 1.10 (2018/6/30) - the effect of --value, --forecast, and --anon flags is now preserved on reload (#753) - edit-at-transaction-position is now also supported when $EDITOR is neovim - support/require fsnotify 0.3.0.1+ - use hledger-lib 1.10 # 1.9.1 (2018/4/30) - use hledger-lib 1.9.1 # 1.9 (2018/3/31) - support ghc 8.4, latest deps - when the system text encoding is UTF-8, ignore any UTF-8 BOM prefix found when reading files - -E/--empty toggles zeroes at startup (with opposite default to cli) # 1.5 (2017/12/31) - fix help -> view manual (on posix platforms) #623 - support -V/--value, --forecast, --auto - remove upper bounds on all but hledger* and base (experimental) # 1.4 (2017/9/30) - a @FILE argument reads flags & args from FILE, one per line - enable --pivot and --anon options, like hledger CLI (#474) (Jakub Zárybnický) - accept -NUM as a shortcut for --depth NUM - deps: allow ansi-terminal 0.7 - deps: drop oldtime flag, require time 1.5+ # 1.3.1 (2017/8/25) - allow megaparsec 6 (#594, Simon Michael, Hans-Peter Deifel) - allow megaparsec-6.1 (Hans-Peter Deifel) - allow vty 5.17 (Felix Yan) - allow brick 0.24 - restore upper bounds on hledger packages # 1.3 (2017/6/30) The register screen now shows transaction status marks. The "uncleared" status, and associated UI flags and keys, have been renamed to "unmarked" to remove ambiguity and confusion. This means that we have dropped the `--uncleared` flag, and our `-U` flag now matches only unmarked things and not pending ones. See the issue and linked mail list discussion for more background. (#564) The P key toggles pending mode, consistent with U (unmarked) and C (cleared). There is also a temporary --status-toggles flag for testing other toggle styles; see `hledger-ui -h`. (#564) There is now less "warping" of selection when lists change: - When the selected account disappears, eg when toggling zero accounts, the selection moves to the alphabetically preceding item, instead of the first one. - When the selected transaction disappears, eg when toggling status filters, the selection moves to the nearest transaction by date (and if several have the same date, by journal order), instead of the last one. In the accounts and register screens, you can now scroll down further so that the last item need not always be shown at the bottom of the screen. And we now try to show the selected item centered in the following situations: - after moving to the end with Page down/End - after toggling filters (status, real, historical..) - on pressing the control-l key (should force a screen redraw, also) - on entering the register screen from the accounts screen (there's a known problem with this: it doesn't work the first time). (Items near the top can't be centered, as we don't scroll higher than the top of the list.) Emacs movement keys are now supported, as well as VI keys. hjkl and CTRL-bfnp should work wherever unmodified arrow keys work. In the transaction screen, amounts are now better aligned, eg when there are posting status marks or virtual postings. Deps: allow brick 0.19 (#575, Felix Yan, Simon Michael) # 1.2 (2017/3/31) Fix a pattern match failure when pressing E on the transaction screen (fixes #508) Accounts with ? in name had empty registers (fixes #498) (Bryan Richter) Allow brick 0.16 (Joshua Chia) and brick 0.17/vty 0.15 (Peter Simons) Allow megaparsec 5.2 (fixes #503) Allow text-zipper 0.10 # 1.1.1 (2017/1/20) - allow brick 0.16 (Joshua Chia) - drop obsolete --no-elide flag # 1.1 (2016/12/31) - with --watch, the display updates automatically to show file or date changes hledger-ui --watch will reload data when the journal file (or any included file) changes. Also, when viewing a current standard period (ie this day/week/month/quarter/year), the period will move as needed to track the current system date. - the --change flag shows period changes at startup instead of historical ending balances - the A key runs the hledger-iadd tool, if installed - always reload when g is pressed Previously it would check the modification time and reload only if it looked newer than the last reload. - mark hledger-ui as "stable" - allow brick 0.15, vty 5.14, text-zipper 0.9 # 1.0.4 (2016/11/2) - allow brick 0.13 # 1.0.3 (2016/10/31) - use brick 0.12 # 1.0.2 (2016/10/27) - use latest brick 0.11 # 1.0.1 (2016/10/27) - allow megaparsec 5.0 or 5.1 # 1.0 (2016/10/26) ## accounts screen - at depth 0, show accounts on one "All" line and show all transactions in the register - 0 now sets depth limit to 0 instead of clearing it - always use --no-elide for a more regular accounts tree ## register screen - registers can now include/exclude subaccount transactions. The register screen now includes subaccounts' transactions if the accounts screen was in tree mode, or when showing an account which was at the depth limit. Ie, it always shows the transactions contributing to the balance displayed on the accounts screen. As on the accounts screen, F toggles between tree mode/subaccount txns included by default and flat mode/subaccount txns excluded by default. (At least, it does when it would make a difference.) - register transactions are filtered by realness and status (#354). Two fixes for the account transactions report when --real/--cleared/real:/status: are in effect, affecting hledger-ui and hledger-web: 1. exclude transactions which affect the current account via an excluded posting type. Eg when --real is in effect, a transaction posting to the current account with only virtual postings will not appear in the report. 2. when showing historical balances, don't count excluded posting types in the starting balance. Eg with --real, the starting balance will be the sum of only the non-virtual prior postings. This is complicated and there might be some ways to confuse it still, causing wrongly included/excluded transactions or wrong historical balances/running totals (transactions with both real and virtual postings to the current account, perhaps ?) - show more accurate dates when postings have their own dates. If postings to the register account matched by the register's filter query have their own dates, we show the earliest of these as the transaction date. ## misc - H toggles between showing "historical" or "period" balances (#392). By default hledger-ui now shows historical balances, which include transactions before the report start date (like hledger balance --historical). Use the H key to toggle to "period" mode, where balances start from 0 on the report start date. - shift arrow keys allow quick period browsing - shift-down narrows to the next smaller standard period (year/quarter/month/week/day), shift-up does the reverse - when narrowed to a standard period, shift-right/left moves to the next/previous period - \`t\` sets the period to today. - a runs the add command - E runs $HLEDGER_UI_EDITOR or $EDITOR or a default editor (vi) on the journal file. When using emacs or vi, if a transaction is selected the cursor will be positioned at its journal entry. - / key sets the filter query; BACKSPACE/DELETE clears it - Z toggles display of zero items (like --empty), and they are shown by default. -E/--empty is now the default for hledger-ui, so accounts with 0 balance and transactions posting 0 change are shown by default. The Z key toggles this, entering "nonzero" mode which hides zero items. - R toggles inclusion of only real (non-virtual) postings - U toggles inclusion of only uncleared transactions/postings - I toggles balance assertions checking, useful for troubleshooting - vi-style movement keys are now supported (for help, you must now use ? not h) (#357) - ESC cancels minibuffer/help or clears the filter query and jumps to top screen - ENTER has been reserved for later use - reloading now preserves any options and modes in effect - reloading on the error screen now updates the message rather than entering a new error screen - the help dialog is more detailed, includes the hledger-ui manual, and uses the full terminal width if needed - the header/footer content is more efficient; historical/period and tree/flat modes are now indicated in the footer - date: query args on the command line now affect the report period. A date2: arg or --date2 flag might also affect it (untested). - hledger-ui now uses the quicker-building microlens 0.27.3 (2016/1/12) - allow brick 0.4 0.27.2 (2016/1/11) - allow brick 0.3.x 0.27.1 (2015/12/3) - allow lens 4.13 - make reloading work on the transaction screen 0.27 (2015/10/30) - hledger-ui is a new curses-style UI, intended to be a standard part of the hledger toolset for all users (except on native MS Windows, where the vty lib is not yet supported). The UI is quite simple, allowing just browsing of accounts and transactions, but it has a number of improvements over the old hledger-vty, which it replaces: - adapts to screen size - handles wide characters - shows multi-commodity amounts on one line - manages cursor and scroll position better - allows depth adjustment - allows --flat toggle - allows --cleared toggle - allows journal reloading - shows a more useful transaction register, like hledger-web - offers multiple color themes - includes some built-in help hledger-ui is built with brick, a new higher-level UI library based on vty, making it relatively easy to grow and maintain. hledger-ui-1.50.3/README.md0000644000000000000000000000041015106732206013267 0ustar0000000000000000# hledger-ui A simple curses-style text user interface for the hledger accounting system. It can be a more convenient way to browse your accounts than the CLI. See also: the [project README](https://hledger.org/README.html) and [home page](https://hledger.org). hledger-ui-1.50.3/hledger-ui.10000644000000000000000000005467515107174442014150 0ustar0000000000000000 .TH "HLEDGER\-UI" "1" "November 2025" "hledger-ui-1.50.3 " "hledger User Manuals" .SH NAME hledger\-ui \- terminal interface (TUI) for \f[CR]hledger\f[R], a robust, friendly plain text accounting app. .SH SYNOPSIS \f[CR]hledger\-ui [OPTS] [QUERYARGS]\f[R] .PD 0 .P .PD or .PD 0 .P .PD \f[CR]hledger ui [OPTS] [QUERYARGS]\f[R] .SH DESCRIPTION This manual is for hledger\[aq]s terminal interface, version 1.50.3. See also the hledger manual for common concepts and file formats. .PP hledger is a robust, user\-friendly, cross\-platform set of programs for tracking money, time, or any other commodity, using double\-entry accounting and a simple, editable file format. hledger is inspired by and largely compatible with ledger(1), and largely interconvertible with beancount(1). .PP hledger\-ui is hledger\[aq]s terminal interface, providing an efficient full\-window text UI for viewing accounts and transactions, and some limited data entry capability. It is easier than hledger\[aq]s command\-line interface, and sometimes quicker and more convenient than the web interface. .PP Like hledger, it reads from (and appends to) a journal file specified by the \f[CR]LEDGER_FILE\f[R] environment variable (defaulting to \f[CR]$HOME/.hledger.journal\f[R]); or you can specify files with \f[CR]\-f\f[R] options. It can also read timeclock files, timedot files, or any CSV/SSV/TSV file with a date field. (See hledger(1) \-> Input for details.) .PP Unlike hledger, hledger\-ui hides all future\-dated transactions by default. They can be revealed, along with any rule\-generated periodic transactions, by pressing the F key (or starting with \-\-forecast) to enable \[dq]forecast mode\[dq]. .SH OPTIONS Any arguments are interpreted as a hledger query which filters the data. hledger\-ui provides the following options: .IP .EX Flags: \-w \-\-watch watch for data and date changes and reload automatically \-\-theme=THEME use this custom display theme (default, greenterm, terminal, dark) \-\-cash start in the cash accounts screen \-\-bs start in the balance sheet accounts screen \-\-is start in the income statement accounts screen \-\-all start in the all accounts screen \-\-register=ACCTREGEX start in the (first matched) account\[aq]s register \-\-change show period balances (changes) at startup instead of historical balances \-l \-\-flat show accounts as a flat list (default) \-t \-\-tree show accounts as a tree .EE .PP and also supports many of hledger\[aq]s general options: .IP .EX General input/data transformation flags: \-f \-\-file=[FMT:]FILE Read data from FILE, or from stdin if FILE is \-, inferring format from extension or a FMT: prefix. Can be specified more than once. If not specified, reads from $LEDGER_FILE or $HOME/.hledger.journal. \-\-rules=RULESFILE Use rules defined in this rules file for converting subsequent CSV/SSV/TSV files. If not specified, uses FILE.csv.rules for each FILE.csv. \-\-alias=A=B|/RGX/=RPL transform account names from A to B, or by replacing regular expression matches \-\-auto generate extra postings by applying auto posting rules (\[dq]=\[dq]) to all transactions \-\-forecast[=PERIOD] Generate extra transactions from periodic rules (\[dq]\[ti]\[dq]), from after the latest ordinary transaction until 6 months from now. Or, during the specified PERIOD (the equals is required). Auto posting rules will also be applied to these transactions. In hledger\-ui, also make future\-dated transactions visible at startup. \-I \-\-ignore\-assertions don\[aq]t check balance assertions by default \-\-txn\-balancing=... how to check that transactions are balanced: \[aq]old\[aq]: use global display precision \[aq]exact\[aq]: use transaction precision (default) \-\-infer\-costs infer conversion equity postings from costs \-\-infer\-equity infer costs from conversion equity postings \-\-infer\-market\-prices infer market prices from costs \-\-pivot=TAGNAME use a different field or tag as account names \-s \-\-strict do extra error checks (and override \-I) \-\-verbose\-tags add tags indicating generated/modified data General output/reporting flags (supported by some commands): \-b \-\-begin=DATE include postings/transactions on/after this date \-e \-\-end=DATE include postings/transactions before this date (with a report interval, will be adjusted to following subperiod end) \-D \-\-daily multiperiod report with 1 day interval \-W \-\-weekly multiperiod report with 1 week interval \-M \-\-monthly multiperiod report with 1 month interval \-Q \-\-quarterly multiperiod report with 1 quarter interval \-Y \-\-yearly multiperiod report with 1 year interval \-p \-\-period=PERIODEXP set begin date, end date, and/or report interval, with more flexibility \-\-today=DATE override today\[aq]s date (affects relative dates) \-\-date2 match/use secondary dates instead (deprecated) \-U \-\-unmarked include only unmarked postings/transactions \-P \-\-pending include only pending postings/transactions \-C \-\-cleared include only cleared postings/transactions (\-U/\-P/\-C can be combined) \-R \-\-real include only non\-virtual postings \-E \-\-empty Show zero items, which are normally hidden. In hledger\-ui & hledger\-web, do the opposite. \-\-depth=DEPTHEXP if a number (or \-NUM): show only top NUM levels of accounts. If REGEXP=NUM, only apply limiting to accounts matching the regular expression. \-B \-\-cost show amounts converted to their cost/sale amount \-V \-\-market Show amounts converted to their value at period end(s) in their default valuation commodity. Equivalent to \-\-value=end. \-X \-\-exchange=COMM Show amounts converted to their value at period end(s) in the specified commodity. Equivalent to \-\-value=end,COMM. \-\-value=WHEN[,COMM] show amounts converted to their value on the specified date(s) in their default valuation commodity or a specified commodity. WHEN can be: \[aq]then\[aq]: value on transaction dates \[aq]end\[aq]: value at period end(s) \[aq]now\[aq]: value today YYYY\-MM\-DD: value on given date \-c \-\-commodity\-style=S Override a commodity\[aq]s display style. Eg: \-c \[aq].\[aq] or \-c \[aq]1.000,00 EUR\[aq] \-\-pretty[=YN] Use box\-drawing characters in text output? Can be \[aq]y\[aq]/\[aq]yes\[aq] or \[aq]n\[aq]/\[aq]no\[aq]. If YN is specified, the equals is required. General help flags: \-h \-\-help show command line help \-\-tldr show command examples with tldr \-\-info show the manual with info \-\-man show the manual with man \-\-version show version information \-\-debug=[1\-9] show this much debug output (default: 1) \-\-pager=YN use a pager when needed ? y/yes (default) or n/no \-\-color=YNA \-\-colour use ANSI color ? y/yes, n/no, or auto (default) .EE .PP With hledger\-ui, the \f[CR]\-\-debug\f[R] option sends debug output to a \f[CR]hledger\-ui.log\f[R] file in the current directory. .PP If you use the bash shell, you can auto\-complete flags by pressing TAB in the command line. If this is not working see Install > Shell completions. .SH MOUSE In most modern terminals, you can navigate through the screens with a mouse or touchpad: .IP \[bu] 2 Use mouse wheel or trackpad to scroll up and down .IP \[bu] 2 Click on list items to go deeper .IP \[bu] 2 Click on the left margin (column 0) to go back. .SH KEYS Keyboard gives more control. .PP \f[CR]?\f[R] shows a help dialog listing all keys. (Some of these also appear in the quick help at the bottom of each screen.) Press \f[CR]?\f[R] again (or \f[CR]ESCAPE\f[R], or \f[CR]LEFT\f[R], or \f[CR]q\f[R]) to close it. The following keys work on most screens: .PP The cursor keys navigate: \f[CR]RIGHT\f[R] or \f[CR]ENTER\f[R] goes deeper, \f[CR]LEFT\f[R] returns to the previous screen, \f[CR]UP\f[R]/\f[CR]DOWN\f[R]/\f[CR]PGUP\f[R]/\f[CR]PGDN\f[R]/\f[CR]HOME\f[R]/\f[CR]END\f[R] move up and down through lists. Emacs\-style (\f[CR]CTRL\-p\f[R]/\f[CR]CTRL\-n\f[R]/\f[CR]CTRL\-f\f[R]/\f[CR]CTRL\-b\f[R]) and VI\-style (\f[CR]k\f[R],\f[CR]j\f[R],\f[CR]l\f[R],\f[CR]h\f[R]) movement keys are also supported. .PP (Tip: movement speed is limited by your keyboard repeat rate, to move faster you may want to adjust it. On a mac, the Karabiner app is one way to do that.) .PP \f[CR]/\f[R] lets you set a general filter query limiting the data shown, using the same query terms as in hledger and hledger\-web. While editing the query, you can use CTRL\-a/e/d/k, BS, cursor keys; press \f[CR]ENTER\f[R] to set it, or \f[CR]ESCAPE\f[R]to cancel. There are also keys for quickly adjusting some common filters like account depth and transaction status (see below). \f[CR]BACKSPACE\f[R] or \f[CR]DELETE\f[R] removes all filters, showing all transactions. .PP As mentioned above, by default hledger\-ui hides future transactions \- both ordinary transactions recorded in the journal, and periodic transactions generated by rule. \f[CR]F\f[R] toggles forecast mode, in which future/forecasted transactions are shown. .PP Pressing \f[CR]SHIFT\-DOWN\f[R] narrows the report period, and pressing \f[CR]SHIFT\-UP\f[R] expands it again. When narrowed, the current report period is displayed in the header line, pressing \f[CR]SHIFT\-LEFT\f[R] or \f[CR]SHIFT\-RIGHT\f[R] moves to the previous or next period, and pressing \f[CR]T\f[R] sets the period to \[dq]today\[dq]. If you are using \f[CR]\-w/\-\-watch\f[R] and viewing a narrowed period containing today, the view will follow any changes in system date (moving to the period containing the new date). (These keys work only with the standard Julian calendar year/quarter/month/week/day periods; they are not affected by a custom report interval specified at the command line.) .PP You can also specify a non\-standard period with \f[CR]/\f[R] and a \f[CR]date:\f[R] query; in this case, the period is not movable with the arrow keys. .PP (Tip: arrow keys with Shift do not work out of the box in all terminal software. Eg in Apple\[aq]s Terminal, the SHIFT\-DOWN and SHIFT\-UP keys must be configured as follows: in Terminal\[aq]s preferences, click Profiles, select your current profile on the left, click Keyboard on the right, click + and add this for SHIFT\-DOWN: \f[CR]\[rs]033[1;2B\f[R], click + and add this for SHIFT\-UP: \f[CR]\[rs]033[1;2A\f[R]. \ In other terminals (Windows Terminal ?) you might need to configure SHIFT\-RIGHT and SHIFT\-LEFT to emit \f[CR]\[rs]033[1;2C\f[R] and \f[CR]\[rs]033[1;2D\f[R] respectively.) .PP \f[CR]ESCAPE\f[R] resets the UI state and jumps back to the top screen, restoring the app\[aq]s initial state at startup. Or, it cancels minibuffer data entry or the help dialog. .PP \f[CR]CTRL\-l\f[R] redraws the screen and centers the selection if possible (selections near the top won\[aq]t be centered, since we don\[aq]t scroll above the top). .PP \f[CR]g\f[R] reloads from the data file(s) and updates the current screen and any previous screens. (With large files, this could cause a noticeable pause.) .PP \f[CR]I\f[R] toggles balance assertion checking. Disabling balance assertions temporarily can be useful for troubleshooting. (If hledger\-ui was started with a \f[CR]\-\-pivot\f[R] option, re\-enabling balance assertions with the \f[CR]I\f[R] key also reloads the journal, like \f[CR]g\f[R].) .PP \f[CR]a\f[R] runs command\-line hledger\[aq]s add command, and reloads the updated file. This allows some basic data entry. .PP \f[CR]A\f[R] is like \f[CR]a\f[R], but runs the hledger\-iadd tool, which provides a terminal interface. This key will be available if \f[CR]hledger\-iadd\f[R] is installed in $path. .PP \f[CR]E\f[R] runs $HLEDGER_UI_EDITOR, or $EDITOR, or a default (\f[CR]emacsclient \-a \[dq]\[dq] \-nw\f[R]) on the journal file. With some editors (emacs, vi), the cursor will be positioned at the current transaction when invoked from the register and transaction screens, and at the error location (if possible) when invoked from the error screen. .PP \f[CR]B\f[R] toggles cost mode, showing amounts converted to their cost\[aq]s commodity (see hledger manual > Cost reporting. .PP \f[CR]V\f[R] toggles value mode, showing amounts converted to their market value (see hledger manual > Valuation flag). More specifically, .IP "1." 3 By default, the \f[CR]V\f[R] key toggles showing end value (\f[CR]\-\-value=end\f[R]) on or off. The valuation date will be the report end date if specified, otherwise today. .IP "2." 3 If you started hledger\-ui with some other valuation (such as \f[CR]\-\-value=then,EUR\f[R]), the \f[CR]V\f[R] key toggles that off or on. .PP Cost/value tips: \- When showing end value, you can change the report end date without restarting, by pressing \f[CR]/\f[R] and adding a query like \f[CR]date:..YYYY\-MM\-DD\f[R]. \- Either cost mode, or value mode, can be active, but not both at once. Cost mode takes precedence. \- There\[aq]s not yet any visual indicator that cost or value mode is active, other than the amount values. .PP \f[CR]q\f[R] quits the application. .PP Additional screen\-specific keys are described below. .SH SCREENS At startup, hledger\-ui shows a menu screen by default. From here you can navigate to other screens using the cursor keys: \f[CR]UP\f[R]/\f[CR]DOWN\f[R] to select, \f[CR]RIGHT\f[R] to move to the selected screen, \f[CR]LEFT\f[R] to return to the previous screen. Or you can use \f[CR]ESC\f[R] to return directly to the top menu screen. .PP You can also use a command line flag to specific a different startup screen (\f[CR]\-\-cs\f[R], \f[CR]\-\-bs\f[R], \f[CR]\-\-is\f[R], \f[CR]\-\-all\f[R], or \f[CR]\-\-register=ACCT\f[R]). .SS Menu screen This is the top\-most screen. From here you can navigate to several screens listing accounts of various types. Note some of these may not show anything until you have configured account types. .SS Cash accounts screen This screen shows \[dq]cash\[dq] (ie, liquid asset) accounts (like \f[CR]hledger balancesheet type:c\f[R]). It always shows balances (historical ending balances on the date shown in the title line). .SS Balance sheet accounts screen This screen shows asset, liability and equity accounts (like \f[CR]hledger balancesheetequity\f[R]). It always shows balances. .SS Income statement accounts screen This screen shows revenue and expense accounts (like \f[CR]hledger incomestatement\f[R]). It always shows changes (balance changes in the period shown in the title line). .SS All accounts screen This screen shows all accounts in your journal (unless filtered by a query; like \f[CR]hledger balance\f[R]). It shows balances by default; you can toggle showing changes with the \f[CR]H\f[R] key. .SS Register screen This screen shows the transactions affecting a particular account. 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 total after the transaction. With the \f[CR]H\f[R] key you can toggle between .RS 2 .IP \[bu] 2 the period total, which is from just the transactions displayed .IP \[bu] 2 or the historical total, which includes any undisplayed transactions before the start of the report period (and matching the filter query if any). This will be the running historical balance (what you would see on a bank\[aq]s website, eg) if not disturbed by a query. .RE .PP Note, this screen combines each transaction\[aq]s in\-period postings to a single line item, dated with the earliest in\-period transaction or posting date (like hledger\[aq]s \f[CR]aregister\f[R]). So custom posting dates can cause the running balance to be temporarily inaccurate. (See hledger manual > aregister and posting dates.) .PP Transactions affecting this account\[aq]s subaccounts will be included in the register if the accounts screen is in tree mode, or if it\[aq]s in list mode but this account has subaccounts which are not shown due to a depth limit. In other words, the register always shows the transactions contributing to the balance shown on the accounts screen. Tree mode/list mode can be toggled with \f[CR]t\f[R] here also. .PP \f[CR]U\f[R] toggles filtering by unmarked status, showing or hiding unmarked transactions. Similarly, \f[CR]P\f[R] toggles pending transactions, and \f[CR]C\f[R] toggles cleared transactions. (By default, transactions with all statuses are shown; if you activate one or two status filters, only those transactions are shown; and if you activate all three, the filter is removed.) .PP \f[CR]R\f[R] toggles real mode, in which virtual postings are ignored. .PP \f[CR]z\f[R] toggles nonzero mode, in which only transactions posting a nonzero change are shown (hledger\-ui shows zero items by default, unlike command\-line hledger). .PP Press \f[CR]RIGHT\f[R] to view the selected transaction in detail. .SS Transaction screen 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[CR]UP\f[R] and \f[CR]DOWN\f[R] will step through all transactions listed in the previous account register screen. In the title bar, the numbers in parentheses show your position within that account register. They will vary depending on which account register you came from (remember most transactions appear in multiple account registers). The #N number preceding them is the transaction\[aq]s position within the complete unfiltered journal, which is a more stable id (at least until the next reload). .PP On this screen (and the register screen), the \f[CR]E\f[R] key will open your text editor with the cursor positioned at the current transaction if possible. .SS 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.) .SH WATCH MODE One of hledger\-ui\[aq]s best features is the auto\-reloading \f[CR]\-w/\-\-watch\f[R] mode. With this flag, it will update the display automatically whenever changes are saved to the data files. .PP This is very useful when reconciling. A good workflow is to have your bank\[aq]s online register open in a browser window, for reference; the journal file open in an editor window; and hledger\-ui in watch mode in a terminal window, eg: .IP .EX $ hledger\-ui \-\-watch \-\-register checking \-C .EE .PP As you mark things cleared in the editor, you can see the effect immediately without having to context switch. This leaves more mental bandwidth for your accounting. Of course you can still interact with hledger\-ui when needed, eg to toggle cleared mode, or to explore the history. .SS \-\-watch problems \f[I]However.\f[R] There are limitations/unresolved bugs with \f[CR]\-\-watch\f[R]: .IP \[bu] 2 It may not work at all for you, depending on platform or system configuration. On some unix systems, increasing fs.inotify.max_user_watches or fs.file\-max parameters in /etc/sysctl.conf might help. (#836) .IP \[bu] 2 It may not detect changes made from outside a virtual machine, ie by an editor running on the host system. .IP \[bu] 2 It may not detect file changes on certain less common filesystems. .IP \[bu] 2 It may use increasing CPU and RAM over time, especially with large files. (This is probably not \-\-watch specific, you may be able to reproduce it by pressing \f[CR]g\f[R] repeatedly.) (#1825) .PP Tips/workarounds: .IP \[bu] 2 If \-\-watch won\[aq]t work for you, press \f[CR]g\f[R] to reload data manually instead. .IP \[bu] 2 If \-\-watch is leaking resources over time, quit and restart (or suspend and resume) hledger\-ui when you\[aq]re not using it. .IP \[bu] 2 When running hledger\-ui inside a VM, also make file changes inside the VM. .IP \[bu] 2 When working with files mounted from another machine, make sure the system clocks on both machines are roughly in agreement. .SH ENVIRONMENT \f[B]LEDGER_FILE\f[R] The main journal file to use when not specified with \f[CR]\-f/\-\-file\f[R]. Default: \f[CR]$HOME/.hledger.journal\f[R]. .SH BUGS We welcome bug reports in the hledger issue tracker (https://bugs.hledger.org), or on the hledger chat or mail list (https://hledger.org/support). .PP Some known issues: .PP \f[CR]\-f\-\f[R] doesn\[aq]t work (hledger\-ui can\[aq]t read from stdin). .PP \f[CR]\-\-watch\f[R] is not robust, especially with large files (see WATCH MODE above). .PP If you press \f[CR]g\f[R] with large files, there could be a noticeable pause with the UI unresponsive. .SH AUTHORS Simon Michael and contributors. .br See http://hledger.org/CREDITS.html .SH COPYRIGHT Copyright 2007-2023 Simon Michael and contributors. .SH LICENSE Released under GNU GPL v3 or later. .SH SEE ALSO hledger(1), hledger\-ui(1), hledger\-web(1), ledger(1) hledger-ui-1.50.3/hledger-ui.txt0000644000000000000000000006000115107174442014603 0ustar0000000000000000 HLEDGER-UI(1) hledger User Manuals HLEDGER-UI(1) NAME hledger-ui - terminal interface (TUI) for hledger, a robust, friendly plain text accounting app. SYNOPSIS hledger-ui [OPTS] [QUERYARGS] or hledger ui [OPTS] [QUERYARGS] DESCRIPTION This manual is for hledger's terminal interface, version 1.50.3. See also the hledger manual for common concepts and file formats. hledger is a robust, user-friendly, cross-platform set of programs for tracking money, time, or any other commodity, using double-entry ac- counting and a simple, editable file format. hledger is inspired by and largely compatible with ledger(1), and largely interconvertible with beancount(1). hledger-ui is hledger's terminal interface, providing an efficient full-window text UI for viewing accounts and transactions, and some limited data entry capability. It is easier than hledger's com- mand-line interface, and sometimes quicker and more convenient than the web interface. Like hledger, it reads from (and appends to) a journal file specified by the LEDGER_FILE environment variable (defaulting to $HOME/.hledger.journal); or you can specify files with -f options. It can also read timeclock files, timedot files, or any CSV/SSV/TSV file with a date field. (See hledger(1) -> Input for details.) Unlike hledger, hledger-ui hides all future-dated transactions by de- fault. They can be revealed, along with any rule-generated periodic transactions, by pressing the F key (or starting with --forecast) to enable "forecast mode". OPTIONS Any arguments are interpreted as a hledger query which filters the data. hledger-ui provides the following options: Flags: -w --watch watch for data and date changes and reload automatically --theme=THEME use this custom display theme (default, greenterm, terminal, dark) --cash start in the cash accounts screen --bs start in the balance sheet accounts screen --is start in the income statement accounts screen --all start in the all accounts screen --register=ACCTREGEX start in the (first matched) account's register --change show period balances (changes) at startup instead of historical balances -l --flat show accounts as a flat list (default) -t --tree show accounts as a tree and also supports many of hledger's general options: General input/data transformation flags: -f --file=[FMT:]FILE Read data from FILE, or from stdin if FILE is -, inferring format from extension or a FMT: prefix. Can be specified more than once. If not specified, reads from $LEDGER_FILE or $HOME/.hledger.journal. --rules=RULESFILE Use rules defined in this rules file for converting subsequent CSV/SSV/TSV files. If not specified, uses FILE.csv.rules for each FILE.csv. --alias=A=B|/RGX/=RPL transform account names from A to B, or by replacing regular expression matches --auto generate extra postings by applying auto posting rules ("=") to all transactions --forecast[=PERIOD] Generate extra transactions from periodic rules ("~"), from after the latest ordinary transaction until 6 months from now. Or, during the specified PERIOD (the equals is required). Auto posting rules will also be applied to these transactions. In hledger-ui, also make future-dated transactions visible at startup. -I --ignore-assertions don't check balance assertions by default --txn-balancing=... how to check that transactions are balanced: 'old': use global display precision 'exact': use transaction precision (default) --infer-costs infer conversion equity postings from costs --infer-equity infer costs from conversion equity postings --infer-market-prices infer market prices from costs --pivot=TAGNAME use a different field or tag as account names -s --strict do extra error checks (and override -I) --verbose-tags add tags indicating generated/modified data General output/reporting flags (supported by some commands): -b --begin=DATE include postings/transactions on/after this date -e --end=DATE include postings/transactions before this date (with a report interval, will be adjusted to following subperiod end) -D --daily multiperiod report with 1 day interval -W --weekly multiperiod report with 1 week interval -M --monthly multiperiod report with 1 month interval -Q --quarterly multiperiod report with 1 quarter interval -Y --yearly multiperiod report with 1 year interval -p --period=PERIODEXP set begin date, end date, and/or report interval, with more flexibility --today=DATE override today's date (affects relative dates) --date2 match/use secondary dates instead (deprecated) -U --unmarked include only unmarked postings/transactions -P --pending include only pending postings/transactions -C --cleared include only cleared postings/transactions (-U/-P/-C can be combined) -R --real include only non-virtual postings -E --empty Show zero items, which are normally hidden. In hledger-ui & hledger-web, do the opposite. --depth=DEPTHEXP if a number (or -NUM): show only top NUM levels of accounts. If REGEXP=NUM, only apply limiting to accounts matching the regular expression. -B --cost show amounts converted to their cost/sale amount -V --market Show amounts converted to their value at period end(s) in their default valuation commodity. Equivalent to --value=end. -X --exchange=COMM Show amounts converted to their value at period end(s) in the specified commodity. Equivalent to --value=end,COMM. --value=WHEN[,COMM] show amounts converted to their value on the specified date(s) in their default valuation commodity or a specified commodity. WHEN can be: 'then': value on transaction dates 'end': value at period end(s) 'now': value today YYYY-MM-DD: value on given date -c --commodity-style=S Override a commodity's display style. Eg: -c '.' or -c '1.000,00 EUR' --pretty[=YN] Use box-drawing characters in text output? Can be 'y'/'yes' or 'n'/'no'. If YN is specified, the equals is required. General help flags: -h --help show command line help --tldr show command examples with tldr --info show the manual with info --man show the manual with man --version show version information --debug=[1-9] show this much debug output (default: 1) --pager=YN use a pager when needed ? y/yes (default) or n/no --color=YNA --colour use ANSI color ? y/yes, n/no, or auto (default) With hledger-ui, the --debug option sends debug output to a hledger-ui.log file in the current directory. If you use the bash shell, you can auto-complete flags by pressing TAB in the command line. If this is not working see Install > Shell com- pletions. MOUSE In most modern terminals, you can navigate through the screens with a mouse or touchpad: o Use mouse wheel or trackpad to scroll up and down o Click on list items to go deeper o Click on the left margin (column 0) to go back. KEYS Keyboard gives more control. ? 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 ES- CAPE, or LEFT, or q) to close it. The following keys work on most screens: The cursor keys navigate: RIGHT or ENTER goes deeper, LEFT returns to the previous screen, UP/DOWN/PGUP/PGDN/HOME/END move up and down through lists. Emacs-style (CTRL-p/CTRL-n/CTRL-f/CTRL-b) and VI-style (k,j,l,h) movement keys are also supported. (Tip: movement speed is limited by your keyboard repeat rate, to move faster you may want to adjust it. On a mac, the Karabiner app is one way to do that.) / lets you set a general filter query limiting the data shown, using the same query terms as in hledger and hledger-web. While editing the query, you can use CTRL-a/e/d/k, BS, cursor keys; press ENTER to set it, or ESCAPEto cancel. There are also keys for quickly adjusting some common filters like account depth and transaction status (see below). BACKSPACE or DELETE removes all filters, showing all transactions. As mentioned above, by default hledger-ui hides future transactions - both ordinary transactions recorded in the journal, and periodic trans- actions generated by rule. F toggles forecast mode, in which fu- ture/forecasted transactions are shown. Pressing SHIFT-DOWN narrows the report period, and pressing SHIFT-UP expands it again. When narrowed, the current report period is dis- played in the header line, pressing SHIFT-LEFT or SHIFT-RIGHT moves to the previous or next period, and pressing T sets the period to "today". If you are using -w/--watch and viewing a narrowed period containing today, the view will follow any changes in system date (moving to the period containing the new date). (These keys work only with the stan- dard Julian calendar year/quarter/month/week/day periods; they are not affected by a custom report interval specified at the command line.) You can also specify a non-standard period with / and a date: query; in this case, the period is not movable with the arrow keys. (Tip: arrow keys with Shift do not work out of the box in all terminal software. Eg in Apple's Terminal, the SHIFT-DOWN and SHIFT-UP keys must be configured as follows: in Terminal's preferences, click Pro- files, select your current profile on the left, click Keyboard on the right, click + and add this for SHIFT-DOWN: \033[1;2B, click + and add this for SHIFT-UP: \033[1;2A. In other terminals (Windows Terminal ?) you might need to configure SHIFT-RIGHT and SHIFT-LEFT to emit \033[1;2C and \033[1;2D respectively.) ESCAPE resets the UI state and jumps back to the top screen, restoring the app's initial state at startup. Or, it cancels minibuffer data en- try or the help dialog. CTRL-l redraws the screen and centers the selection if possible (selec- tions near the top won't be centered, since we don't scroll above the top). g reloads from the data file(s) and updates the current screen and any previous screens. (With large files, this could cause a noticeable pause.) I toggles balance assertion checking. Disabling balance assertions temporarily can be useful for troubleshooting. (If hledger-ui was started with a --pivot option, re-enabling balance assertions with the I key also reloads the journal, like g.) a runs command-line hledger's add command, and reloads the updated file. This allows some basic data entry. A is like a, but runs the hledger-iadd tool, which provides a terminal interface. This key will be available if hledger-iadd is installed in $path. E runs $HLEDGER_UI_EDITOR, or $EDITOR, or a default (emacsclient -a "" -nw) on the journal file. With some editors (emacs, vi), the cursor will be positioned at the current transaction when invoked from the register and transaction screens, and at the error location (if possi- ble) when invoked from the error screen. B toggles cost mode, showing amounts converted to their cost's commod- ity (see hledger manual > Cost reporting. V toggles value mode, showing amounts converted to their market value (see hledger manual > Valuation flag). More specifically, 1. By default, the V key toggles showing end value (--value=end) on or off. The valuation date will be the report end date if specified, otherwise today. 2. If you started hledger-ui with some other valuation (such as --value=then,EUR), the V key toggles that off or on. Cost/value tips: - When showing end value, you can change the report end date without restarting, by pressing / and adding a query like date:..YYYY-MM-DD. - Either cost mode, or value mode, can be active, but not both at once. Cost mode takes precedence. - There's not yet any visual indicator that cost or value mode is active, other than the amount values. q quits the application. Additional screen-specific keys are described below. SCREENS At startup, hledger-ui shows a menu screen by default. From here you can navigate to other screens using the cursor keys: UP/DOWN to select, RIGHT to move to the selected screen, LEFT to return to the previous screen. Or you can use ESC to return directly to the top menu screen. You can also use a command line flag to specific a different startup screen (--cs, --bs, --is, --all, or --register=ACCT). Menu screen This is the top-most screen. From here you can navigate to several screens listing accounts of various types. Note some of these may not show anything until you have configured account types. Cash accounts screen This screen shows "cash" (ie, liquid asset) accounts (like hledger bal- ancesheet type:c). It always shows balances (historical ending bal- ances on the date shown in the title line). Balance sheet accounts screen This screen shows asset, liability and equity accounts (like hledger balancesheetequity). It always shows balances. Income statement accounts screen This screen shows revenue and expense accounts (like hledger incomes- tatement). It always shows changes (balance changes in the period shown in the title line). All accounts screen This screen shows all accounts in your journal (unless filtered by a query; like hledger balance). It shows balances by default; you can toggle showing changes with the H key. Register screen This screen shows the transactions affecting a particular account. 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 total after the transaction. With the H key you can tog- gle between o the period total, which is from just the transactions displayed o or the historical total, which includes any undisplayed transac- tions before the start of the report period (and matching the fil- ter query if any). This will be the running historical balance (what you would see on a bank's website, eg) if not disturbed by a query. Note, this screen combines each transaction's in-period postings to a single line item, dated with the earliest in-period transaction or posting date (like hledger's aregister). So custom posting dates can cause the running balance to be temporarily inaccurate. (See hledger manual > aregister and posting dates.) Transactions affecting this account's subaccounts will be included in the register if the accounts screen is in tree mode, or if it's in list mode but this account has subaccounts which are not shown due to a depth limit. In other words, the register always shows the transac- tions contributing to the balance shown on the accounts screen. Tree mode/list mode can be toggled with t here also. U toggles filtering by unmarked status, showing or hiding unmarked transactions. Similarly, P toggles pending transactions, and C toggles cleared transactions. (By default, transactions with all statuses are shown; if you activate one or two status filters, only those transac- tions are shown; and if you activate all three, the filter is removed.) R toggles real mode, in which virtual postings are ignored. z toggles nonzero mode, in which only transactions posting a nonzero change are shown (hledger-ui shows zero items by default, unlike com- mand-line hledger). Press RIGHT to view the selected transaction in detail. Transaction screen This screen shows a single transaction, as a general journal entry, similar to hledger's print command and journal format (hledger_jour- nal(5)). The transaction's date(s) and any cleared flag, transaction code, de- scription, comments, along with all of its account postings are shown. Simple transactions have two postings, but there can be more (or in certain cases, fewer). UP and DOWN will step through all transactions listed in the previous account register screen. In the title bar, the numbers in parentheses show your position within that account register. They will vary de- pending on which account register you came from (remember most transac- tions appear in multiple account registers). The #N number preceding them is the transaction's position within the complete unfiltered jour- nal, which is a more stable id (at least until the next reload). On this screen (and the register screen), the E key will open your text editor with the cursor positioned at the current transaction if possi- ble. 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.) WATCH MODE One of hledger-ui's best features is the auto-reloading -w/--watch mode. With this flag, it will update the display automatically when- ever changes are saved to the data files. This is very useful when reconciling. A good workflow is to have your bank's online register open in a browser window, for reference; the journal file open in an editor window; and hledger-ui in watch mode in a terminal window, eg: $ hledger-ui --watch --register checking -C As you mark things cleared in the editor, you can see the effect imme- diately without having to context switch. This leaves more mental bandwidth for your accounting. Of course you can still interact with hledger-ui when needed, eg to toggle cleared mode, or to explore the history. --watch problems However. There are limitations/unresolved bugs with --watch: o It may not work at all for you, depending on platform or system con- figuration. On some unix systems, increasing fs.ino- tify.max_user_watches or fs.file-max parameters in /etc/sysctl.conf might help. (#836) o It may not detect changes made from outside a virtual machine, ie by an editor running on the host system. o It may not detect file changes on certain less common filesystems. o It may use increasing CPU and RAM over time, especially with large files. (This is probably not --watch specific, you may be able to reproduce it by pressing g repeatedly.) (#1825) Tips/workarounds: o If --watch won't work for you, press g to reload data manually in- stead. o If --watch is leaking resources over time, quit and restart (or sus- pend and resume) hledger-ui when you're not using it. o When running hledger-ui inside a VM, also make file changes inside the VM. o When working with files mounted from another machine, make sure the system clocks on both machines are roughly in agreement. ENVIRONMENT LEDGER_FILE The main journal file to use when not specified with -f/--file. Default: $HOME/.hledger.journal. BUGS We welcome bug reports in the hledger issue tracker (https://bugs.hledger.org), or on the hledger chat or mail list (https://hledger.org/support). Some known issues: -f- doesn't work (hledger-ui can't read from stdin). --watch is not robust, especially with large files (see WATCH MODE above). If you press g with large files, there could be a noticeable pause with the UI unresponsive. AUTHORS Simon Michael and contributors. See http://hledger.org/CREDITS.html COPYRIGHT Copyright 2007-2023 Simon Michael and contributors. LICENSE Released under GNU GPL v3 or later. SEE ALSO hledger(1), hledger-ui(1), hledger-web(1), ledger(1) hledger-ui-1.50.3 November 2025 HLEDGER-UI(1) hledger-ui-1.50.3/hledger-ui.info0000644000000000000000000005704115107174442014731 0ustar0000000000000000This is hledger-ui.info, produced by makeinfo version 7.2 from stdin. INFO-DIR-SECTION User Applications START-INFO-DIR-ENTRY * hledger-ui: (hledger-ui). Terminal UI for the hledger accounting tool. END-INFO-DIR-ENTRY  File: hledger-ui.info, Node: Top, Next: OPTIONS, Up: (dir) hledger-ui(1) ************* hledger-ui - terminal interface (TUI) for 'hledger', a robust, friendly plain text accounting app. 'hledger-ui [OPTS] [QUERYARGS]' or 'hledger ui [OPTS] [QUERYARGS]' This manual is for hledger's terminal interface, version 1.50.3. See also the hledger manual for common concepts and file formats. hledger is a robust, user-friendly, cross-platform set of programs for tracking money, time, or any other commodity, using double-entry accounting and a simple, editable file format. hledger is inspired by and largely compatible with ledger(1), and largely interconvertible with beancount(1). hledger-ui is hledger's terminal interface, providing an efficient full-window text UI for viewing accounts and transactions, and some limited data entry capability. It is easier than hledger's command-line interface, and sometimes quicker and more convenient than the web interface. Like hledger, it reads from (and appends to) a journal file specified by the 'LEDGER_FILE' environment variable (defaulting to '$HOME/.hledger.journal'); or you can specify files with '-f' options. It can also read timeclock files, timedot files, or any CSV/SSV/TSV file with a date field. (See hledger(1) -> Input for details.) Unlike hledger, hledger-ui hides all future-dated transactions by default. They can be revealed, along with any rule-generated periodic transactions, by pressing the F key (or starting with -forecast) to enable "forecast mode". * Menu: * OPTIONS:: * MOUSE:: * KEYS:: * SCREENS:: * WATCH MODE:: * ENVIRONMENT:: * BUGS::  File: hledger-ui.info, Node: OPTIONS, Next: MOUSE, Prev: Top, Up: Top 1 OPTIONS ********* Any arguments are interpreted as a hledger query which filters the data. hledger-ui provides the following options: Flags: -w --watch watch for data and date changes and reload automatically --theme=THEME use this custom display theme (default, greenterm, terminal, dark) --cash start in the cash accounts screen --bs start in the balance sheet accounts screen --is start in the income statement accounts screen --all start in the all accounts screen --register=ACCTREGEX start in the (first matched) account's register --change show period balances (changes) at startup instead of historical balances -l --flat show accounts as a flat list (default) -t --tree show accounts as a tree and also supports many of hledger's general options: General input/data transformation flags: -f --file=[FMT:]FILE Read data from FILE, or from stdin if FILE is -, inferring format from extension or a FMT: prefix. Can be specified more than once. If not specified, reads from $LEDGER_FILE or $HOME/.hledger.journal. --rules=RULESFILE Use rules defined in this rules file for converting subsequent CSV/SSV/TSV files. If not specified, uses FILE.csv.rules for each FILE.csv. --alias=A=B|/RGX/=RPL transform account names from A to B, or by replacing regular expression matches --auto generate extra postings by applying auto posting rules ("=") to all transactions --forecast[=PERIOD] Generate extra transactions from periodic rules ("~"), from after the latest ordinary transaction until 6 months from now. Or, during the specified PERIOD (the equals is required). Auto posting rules will also be applied to these transactions. In hledger-ui, also make future-dated transactions visible at startup. -I --ignore-assertions don't check balance assertions by default --txn-balancing=... how to check that transactions are balanced: 'old': use global display precision 'exact': use transaction precision (default) --infer-costs infer conversion equity postings from costs --infer-equity infer costs from conversion equity postings --infer-market-prices infer market prices from costs --pivot=TAGNAME use a different field or tag as account names -s --strict do extra error checks (and override -I) --verbose-tags add tags indicating generated/modified data General output/reporting flags (supported by some commands): -b --begin=DATE include postings/transactions on/after this date -e --end=DATE include postings/transactions before this date (with a report interval, will be adjusted to following subperiod end) -D --daily multiperiod report with 1 day interval -W --weekly multiperiod report with 1 week interval -M --monthly multiperiod report with 1 month interval -Q --quarterly multiperiod report with 1 quarter interval -Y --yearly multiperiod report with 1 year interval -p --period=PERIODEXP set begin date, end date, and/or report interval, with more flexibility --today=DATE override today's date (affects relative dates) --date2 match/use secondary dates instead (deprecated) -U --unmarked include only unmarked postings/transactions -P --pending include only pending postings/transactions -C --cleared include only cleared postings/transactions (-U/-P/-C can be combined) -R --real include only non-virtual postings -E --empty Show zero items, which are normally hidden. In hledger-ui & hledger-web, do the opposite. --depth=DEPTHEXP if a number (or -NUM): show only top NUM levels of accounts. If REGEXP=NUM, only apply limiting to accounts matching the regular expression. -B --cost show amounts converted to their cost/sale amount -V --market Show amounts converted to their value at period end(s) in their default valuation commodity. Equivalent to --value=end. -X --exchange=COMM Show amounts converted to their value at period end(s) in the specified commodity. Equivalent to --value=end,COMM. --value=WHEN[,COMM] show amounts converted to their value on the specified date(s) in their default valuation commodity or a specified commodity. WHEN can be: 'then': value on transaction dates 'end': value at period end(s) 'now': value today YYYY-MM-DD: value on given date -c --commodity-style=S Override a commodity's display style. Eg: -c '.' or -c '1.000,00 EUR' --pretty[=YN] Use box-drawing characters in text output? Can be 'y'/'yes' or 'n'/'no'. If YN is specified, the equals is required. General help flags: -h --help show command line help --tldr show command examples with tldr --info show the manual with info --man show the manual with man --version show version information --debug=[1-9] show this much debug output (default: 1) --pager=YN use a pager when needed ? y/yes (default) or n/no --color=YNA --colour use ANSI color ? y/yes, n/no, or auto (default) With hledger-ui, the '--debug' option sends debug output to a 'hledger-ui.log' file in the current directory. If you use the bash shell, you can auto-complete flags by pressing TAB in the command line. If this is not working see Install > Shell completions.  File: hledger-ui.info, Node: MOUSE, Next: KEYS, Prev: OPTIONS, Up: Top 2 MOUSE ******* In most modern terminals, you can navigate through the screens with a mouse or touchpad: * Use mouse wheel or trackpad to scroll up and down * Click on list items to go deeper * Click on the left margin (column 0) to go back.  File: hledger-ui.info, Node: KEYS, Next: SCREENS, Prev: MOUSE, Up: Top 3 KEYS ****** Keyboard gives more control. '?' shows a help dialog listing all keys. (Some of these also appear in the quick help at the bottom of each screen.) Press '?' again (or 'ESCAPE', or 'LEFT', or 'q') to close it. The following keys work on most screens: The cursor keys navigate: 'RIGHT' or 'ENTER' goes deeper, 'LEFT' returns to the previous screen, 'UP'/'DOWN'/'PGUP'/'PGDN'/'HOME'/'END' move up and down through lists. Emacs-style ('CTRL-p'/'CTRL-n'/'CTRL-f'/'CTRL-b') and VI-style ('k','j','l','h') movement keys are also supported. (Tip: movement speed is limited by your keyboard repeat rate, to move faster you may want to adjust it. On a mac, the Karabiner app is one way to do that.) '/' lets you set a general filter query limiting the data shown, using the same query terms as in hledger and hledger-web. While editing the query, you can use CTRL-a/e/d/k, BS, cursor keys; press 'ENTER' to set it, or 'ESCAPE'to cancel. There are also keys for quickly adjusting some common filters like account depth and transaction status (see below). 'BACKSPACE' or 'DELETE' removes all filters, showing all transactions. As mentioned above, by default hledger-ui hides future transactions - both ordinary transactions recorded in the journal, and periodic transactions generated by rule. 'F' toggles forecast mode, in which future/forecasted transactions are shown. Pressing 'SHIFT-DOWN' narrows the report period, and pressing 'SHIFT-UP' expands it again. When narrowed, the current report period is displayed in the header line, pressing 'SHIFT-LEFT' or 'SHIFT-RIGHT' moves to the previous or next period, and pressing 'T' sets the period to "today". If you are using '-w/--watch' and viewing a narrowed period containing today, the view will follow any changes in system date (moving to the period containing the new date). (These keys work only with the standard Julian calendar year/quarter/month/week/day periods; they are not affected by a custom report interval specified at the command line.) You can also specify a non-standard period with '/' and a 'date:' query; in this case, the period is not movable with the arrow keys. (Tip: arrow keys with Shift do not work out of the box in all terminal software. Eg in Apple's Terminal, the SHIFT-DOWN and SHIFT-UP keys must be configured as follows: in Terminal's preferences, click Profiles, select your current profile on the left, click Keyboard on the right, click + and add this for SHIFT-DOWN: '\033[1;2B', click + and add this for SHIFT-UP: '\033[1;2A'. In other terminals (Windows Terminal ?) you might need to configure SHIFT-RIGHT and SHIFT-LEFT to emit '\033[1;2C' and '\033[1;2D' respectively.) 'ESCAPE' resets the UI state and jumps back to the top screen, restoring the app's initial state at startup. Or, it cancels minibuffer data entry or the help dialog. 'CTRL-l' redraws the screen and centers the selection if possible (selections near the top won't be centered, since we don't scroll above the top). 'g' reloads from the data file(s) and updates the current screen and any previous screens. (With large files, this could cause a noticeable pause.) 'I' toggles balance assertion checking. Disabling balance assertions temporarily can be useful for troubleshooting. (If hledger-ui was started with a '--pivot' option, re-enabling balance assertions with the 'I' key also reloads the journal, like 'g'.) 'a' runs command-line hledger's add command, and reloads the updated file. This allows some basic data entry. 'A' is like 'a', but runs the hledger-iadd tool, which provides a terminal interface. This key will be available if 'hledger-iadd' is installed in $path. 'E' runs $HLEDGER_UI_EDITOR, or $EDITOR, or a default ('emacsclient -a "" -nw') on the journal file. With some editors (emacs, vi), the cursor will be positioned at the current transaction when invoked from the register and transaction screens, and at the error location (if possible) when invoked from the error screen. 'B' toggles cost mode, showing amounts converted to their cost's commodity (see hledger manual > Cost reporting. 'V' toggles value mode, showing amounts converted to their market value (see hledger manual > Valuation flag). More specifically, 1. By default, the 'V' key toggles showing end value ('--value=end') on or off. The valuation date will be the report end date if specified, otherwise today. 2. If you started hledger-ui with some other valuation (such as '--value=then,EUR'), the 'V' key toggles that off or on. Cost/value tips: - When showing end value, you can change the report end date without restarting, by pressing '/' and adding a query like 'date:..YYYY-MM-DD'. - Either cost mode, or value mode, can be active, but not both at once. Cost mode takes precedence. - There's not yet any visual indicator that cost or value mode is active, other than the amount values. 'q' quits the application. Additional screen-specific keys are described below.  File: hledger-ui.info, Node: SCREENS, Next: WATCH MODE, Prev: KEYS, Up: Top 4 SCREENS ********* At startup, hledger-ui shows a menu screen by default. From here you can navigate to other screens using the cursor keys: 'UP'/'DOWN' to select, 'RIGHT' to move to the selected screen, 'LEFT' to return to the previous screen. Or you can use 'ESC' to return directly to the top menu screen. You can also use a command line flag to specific a different startup screen ('--cs', '--bs', '--is', '--all', or '--register=ACCT'). * Menu: * Menu screen:: * Cash accounts screen:: * Balance sheet accounts screen:: * Income statement accounts screen:: * All accounts screen:: * Register screen:: * Transaction screen:: * Error screen::  File: hledger-ui.info, Node: Menu screen, Next: Cash accounts screen, Up: SCREENS 4.1 Menu screen =============== This is the top-most screen. From here you can navigate to several screens listing accounts of various types. Note some of these may not show anything until you have configured account types.  File: hledger-ui.info, Node: Cash accounts screen, Next: Balance sheet accounts screen, Prev: Menu screen, Up: SCREENS 4.2 Cash accounts screen ======================== This screen shows "cash" (ie, liquid asset) accounts (like 'hledger balancesheet type:c'). It always shows balances (historical ending balances on the date shown in the title line).  File: hledger-ui.info, Node: Balance sheet accounts screen, Next: Income statement accounts screen, Prev: Cash accounts screen, Up: SCREENS 4.3 Balance sheet accounts screen ================================= This screen shows asset, liability and equity accounts (like 'hledger balancesheetequity'). It always shows balances.  File: hledger-ui.info, Node: Income statement accounts screen, Next: All accounts screen, Prev: Balance sheet accounts screen, Up: SCREENS 4.4 Income statement accounts screen ==================================== This screen shows revenue and expense accounts (like 'hledger incomestatement'). It always shows changes (balance changes in the period shown in the title line).  File: hledger-ui.info, Node: All accounts screen, Next: Register screen, Prev: Income statement accounts screen, Up: SCREENS 4.5 All accounts screen ======================= This screen shows all accounts in your journal (unless filtered by a query; like 'hledger balance'). It shows balances by default; you can toggle showing changes with the 'H' key.  File: hledger-ui.info, Node: Register screen, Next: Transaction screen, Prev: All accounts screen, Up: SCREENS 4.6 Register screen =================== This screen shows the transactions affecting a particular account. 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 total after the transaction. With the 'H' key you can toggle between * the period total, which is from just the transactions displayed * or the historical total, which includes any undisplayed transactions before the start of the report period (and matching the filter query if any). This will be the running historical balance (what you would see on a bank's website, eg) if not disturbed by a query. Note, this screen combines each transaction's in-period postings to a single line item, dated with the earliest in-period transaction or posting date (like hledger's 'aregister'). So custom posting dates can cause the running balance to be temporarily inaccurate. (See hledger manual > aregister and posting dates.) Transactions affecting this account's subaccounts will be included in the register if the accounts screen is in tree mode, or if it's in list mode but this account has subaccounts which are not shown due to a depth limit. In other words, the register always shows the transactions contributing to the balance shown on the accounts screen. Tree mode/list mode can be toggled with 't' here also. 'U' toggles filtering by unmarked status, showing or hiding unmarked transactions. Similarly, 'P' toggles pending transactions, and 'C' toggles cleared transactions. (By default, transactions with all statuses are shown; if you activate one or two status filters, only those transactions are shown; and if you activate all three, the filter is removed.) 'R' toggles real mode, in which virtual postings are ignored. 'z' toggles nonzero mode, in which only transactions posting a nonzero change are shown (hledger-ui shows zero items by default, unlike command-line hledger). Press 'RIGHT' to view the selected transaction in detail.  File: hledger-ui.info, Node: Transaction screen, Next: Error screen, Prev: Register screen, Up: SCREENS 4.7 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). On this screen (and the register screen), the 'E' key will open your text editor with the cursor positioned at the current transaction if possible.  File: hledger-ui.info, Node: Error screen, Prev: Transaction screen, Up: SCREENS 4.8 Error screen ================ This screen will appear if there is a problem, such as a parse error, when you press g to reload. Once you have fixed the problem, press g again to reload and resume normal operation. (Or, you can press escape to cancel the reload attempt.)  File: hledger-ui.info, Node: WATCH MODE, Next: ENVIRONMENT, Prev: SCREENS, Up: Top 5 WATCH MODE ************ One of hledger-ui's best features is the auto-reloading '-w/--watch' mode. With this flag, it will update the display automatically whenever changes are saved to the data files. This is very useful when reconciling. A good workflow is to have your bank's online register open in a browser window, for reference; the journal file open in an editor window; and hledger-ui in watch mode in a terminal window, eg: $ hledger-ui --watch --register checking -C As you mark things cleared in the editor, you can see the effect immediately without having to context switch. This leaves more mental bandwidth for your accounting. Of course you can still interact with hledger-ui when needed, eg to toggle cleared mode, or to explore the history. * Menu: * --watch problems::  File: hledger-ui.info, Node: --watch problems, Up: WATCH MODE 5.1 -watch problems =================== _However._ There are limitations/unresolved bugs with '--watch': * It may not work at all for you, depending on platform or system configuration. On some unix systems, increasing fs.inotify.max_user_watches or fs.file-max parameters in /etc/sysctl.conf might help. (#836) * It may not detect changes made from outside a virtual machine, ie by an editor running on the host system. * It may not detect file changes on certain less common filesystems. * It may use increasing CPU and RAM over time, especially with large files. (This is probably not -watch specific, you may be able to reproduce it by pressing 'g' repeatedly.) (#1825) Tips/workarounds: * If -watch won't work for you, press 'g' to reload data manually instead. * If -watch is leaking resources over time, quit and restart (or suspend and resume) hledger-ui when you're not using it. * When running hledger-ui inside a VM, also make file changes inside the VM. * When working with files mounted from another machine, make sure the system clocks on both machines are roughly in agreement.  File: hledger-ui.info, Node: ENVIRONMENT, Next: BUGS, Prev: WATCH MODE, Up: Top 6 ENVIRONMENT ************* *LEDGER_FILE* The main journal file to use when not specified with '-f/--file'. Default: '$HOME/.hledger.journal'.  File: hledger-ui.info, Node: BUGS, Prev: ENVIRONMENT, Up: Top 7 BUGS ****** We welcome bug reports in the hledger issue tracker (https://bugs.hledger.org), or on the hledger chat or mail list (https://hledger.org/support). Some known issues: '-f-' doesn't work (hledger-ui can't read from stdin). '--watch' is not robust, especially with large files (see WATCH MODE above). If you press 'g' with large files, there could be a noticeable pause with the UI unresponsive.  Tag Table: Node: Top221 Node: OPTIONS1869 Node: MOUSE8755 Node: KEYS9087 Node: SCREENS14229 Node: Menu screen14969 Node: Cash accounts screen15285 Node: Balance sheet accounts screen15646 Node: Income statement accounts screen15982 Node: All accounts screen16367 Node: Register screen16730 Node: Transaction screen19173 Node: Error screen20353 Node: WATCH MODE20719 Node: --watch problems21617 Node: ENVIRONMENT22864 Node: BUGS23097  End Tag Table  Local Variables: coding: utf-8 End: hledger-ui-1.50.3/LICENSE0000644000000000000000000010451515106732206013030 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.50.3/Setup.hs0000644000000000000000000000005615022704461013451 0ustar0000000000000000import Distribution.Simple main = defaultMain hledger-ui-1.50.3/hledger-ui.cabal0000644000000000000000000000723315107174442015036 0ustar0000000000000000cabal-version: 2.2 -- This file has been generated from package.yaml by hpack version 0.38.1. -- -- see: https://github.com/sol/hpack name: hledger-ui version: 1.50.3 synopsis: Terminal interface for the hledger accounting system description: A simple terminal user interface for the hledger accounting system. It can be a more convenient way to browse your accounts than the CLI. . hledger is a robust, cross-platform set of tools for tracking money, time, or any other commodity, using double-entry accounting and a simple, editable file format, with command-line, terminal and web interfaces. It is a Haskell rewrite of Ledger, and one of the leading implementations of Plain Text Accounting. Read more at: category: Finance, Console stability: stable homepage: http://hledger.org bug-reports: http://bugs.hledger.org author: Simon Michael maintainer: Simon Michael license: GPL-3.0-or-later license-file: LICENSE build-type: Simple tested-with: ghc==9.6.7, ghc==9.8.4, ghc==9.10.2, ghc==9.12.2 extra-source-files: CHANGES.md README.md hledger-ui.1 hledger-ui.txt hledger-ui.info source-repository head type: git location: https://github.com/simonmichael/hledger flag debug description: Build with GHC 9.10+ stack traces enabled manual: True default: False library exposed-modules: Hledger.UI Hledger.UI.Main Hledger.UI.Theme Hledger.UI.UIOptions other-modules: Hledger.UI.AccountsScreen Hledger.UI.BalancesheetScreen Hledger.UI.CashScreen Hledger.UI.Editor Hledger.UI.ErrorScreen Hledger.UI.IncomestatementScreen Hledger.UI.MenuScreen Hledger.UI.RegisterScreen Hledger.UI.TransactionScreen Hledger.UI.UIScreens Hledger.UI.UIState Hledger.UI.UITypes Hledger.UI.UIUtils Paths_hledger_ui autogen-modules: Paths_hledger_ui hs-source-dirs: ./ ghc-options: -Wall -Wno-incomplete-uni-patterns -Wno-missing-signatures -Wno-orphans -Wno-type-defaults -Wno-unused-do-bind cpp-options: -DVERSION="1.50.3" -DVERSION="1.50.3" build-depends: ansi-terminal >=0.9 , async , base >=4.18 && <4.22 , brick >=2.1.1 && <2.3.2 || >2.3.2 && <2.11 , cmdargs >=0.8 , containers >=0.5.9 , data-default , directory , doclayout >=0.3 && <0.6 , extra >=1.7.11 , filepath , fsnotify >=0.4.2.0 && <0.5 , githash >=0.1.6.2 , hledger >=1.50.3 && <1.51 , hledger-lib >=1.50.3 && <1.51 , megaparsec >=7.0.0 && <9.8 , microlens >=0.4 , microlens-platform >=0.2.3.1 , mtl >=2.2.1 , process >=1.2 , safe >=0.3.20 , split >=0.1 , stm , text >=1.2.4.1 , text-zipper >=0.4 , time >=1.5 , transformers , vector , vty >=6.1 && <6.6 , vty-crossplatform >=0.4.0.0 && <0.5.0.0 default-language: GHC2021 if (flag(debug)) cpp-options: -DDEBUG if os(windows) build-depends: vty-windows >=0.2.0.1 && <0.3.0.0 else build-depends: unix executable hledger-ui main-is: hledger-ui.hs other-modules: Paths_hledger_ui autogen-modules: Paths_hledger_ui hs-source-dirs: app ghc-options: -Wall -Wno-incomplete-uni-patterns -Wno-missing-signatures -Wno-orphans -Wno-type-defaults -Wno-unused-do-bind -threaded cpp-options: -DVERSION="1.50.3" build-depends: base >=4.18 && <4.22 , hledger-ui default-language: GHC2021 if (flag(debug)) cpp-options: -DDEBUG