packages feed

hledger-ui 1.52.4 → 2.0

raw patch · 23 files changed

+2168/−1206 lines, 23 filesdep +tastydep +tasty-hunitdep +vty-unixdep −githashdep ~brickdep ~hledgerdep ~hledger-libPVP ok

version bump matches the API change (PVP)

Dependencies added: tasty, tasty-hunit, vty-unix

Dependencies removed: githash

Dependency ranges changed: brick, hledger, hledger-lib

API changes (from Hackage documentation)

- Hledger.UI.BalancesheetScreen: bsDraw :: UIState -> [Widget Name]
- Hledger.UI.BalancesheetScreen: bsHandle :: BrickEvent Name AppEvent -> EventM Name UIState ()
- Hledger.UI.BalancesheetScreen: bsNew :: UIOpts -> Day -> Journal -> Maybe AccountName -> Screen
- Hledger.UI.BalancesheetScreen: bsUpdate :: UIOpts -> Day -> Journal -> AccountsScreenState -> AccountsScreenState
- Hledger.UI.CashScreen: csDraw :: UIState -> [Widget Name]
- Hledger.UI.CashScreen: csHandle :: BrickEvent Name AppEvent -> EventM Name UIState ()
- Hledger.UI.CashScreen: csNew :: UIOpts -> Day -> Journal -> Maybe AccountName -> Screen
- Hledger.UI.CashScreen: csUpdate :: UIOpts -> Day -> Journal -> AccountsScreenState -> AccountsScreenState
- Hledger.UI.IncomestatementScreen: isDraw :: UIState -> [Widget Name]
- Hledger.UI.IncomestatementScreen: isHandle :: BrickEvent Name AppEvent -> EventM Name UIState ()
- Hledger.UI.IncomestatementScreen: isNew :: UIOpts -> Day -> Journal -> Maybe AccountName -> Screen
- Hledger.UI.IncomestatementScreen: isUpdate :: UIOpts -> Day -> Journal -> AccountsScreenState -> AccountsScreenState
- Hledger.UI.UIScreens: bsNew :: UIOpts -> Day -> Journal -> Maybe AccountName -> Screen
- Hledger.UI.UIScreens: bsUpdate :: UIOpts -> Day -> Journal -> AccountsScreenState -> AccountsScreenState
- Hledger.UI.UIScreens: csNew :: UIOpts -> Day -> Journal -> Maybe AccountName -> Screen
- Hledger.UI.UIScreens: csUpdate :: UIOpts -> Day -> Journal -> AccountsScreenState -> AccountsScreenState
- Hledger.UI.UIScreens: isNew :: UIOpts -> Day -> Journal -> Maybe AccountName -> Screen
- Hledger.UI.UIScreens: isUpdate :: UIOpts -> Day -> Journal -> AccountsScreenState -> AccountsScreenState
- Hledger.UI.UITypes: ALS :: (AccountsScreenState -> Screen) -> AccountsScreenState -> AccountsLikeScreen
- Hledger.UI.UITypes: Accounts :: ScreenName
- Hledger.UI.UITypes: BS :: AccountsScreenState -> Screen
- Hledger.UI.UITypes: Balancesheet :: ScreenName
- Hledger.UI.UITypes: CS :: AccountsScreenState -> Screen
- Hledger.UI.UITypes: CashScreen :: ScreenName
- Hledger.UI.UITypes: IS :: AccountsScreenState -> Screen
- Hledger.UI.UITypes: Incomestatement :: ScreenName
- Hledger.UI.UITypes: data AccountsLikeScreen
- Hledger.UI.UITypes: data ScreenName
- Hledger.UI.UITypes: errorWrongScreenType :: String -> a
- Hledger.UI.UITypes: fromAccountsLikeScreen :: AccountsLikeScreen -> Screen
- Hledger.UI.UITypes: instance GHC.Classes.Eq Hledger.UI.UITypes.ScreenName
- Hledger.UI.UITypes: instance GHC.Classes.Ord Hledger.UI.UITypes.ScreenName
- Hledger.UI.UITypes: instance GHC.Show.Show Hledger.UI.UITypes.AccountsLikeScreen
- Hledger.UI.UITypes: instance GHC.Show.Show Hledger.UI.UITypes.ScreenName
- Hledger.UI.UITypes: toAccountsLikeScreen :: Screen -> Maybe AccountsLikeScreen
+ Hledger.UI.ErrorScreen: uiAdjustOpts :: UIOpts -> CliOpts -> CliOpts
+ Hledger.UI.Main: openTerminal :: IO Fd
+ Hledger.UI.Main: translateLayer :: Location -> Widget n -> Widget n
+ Hledger.UI.Main: ttyVtyMaker :: IO (IO Vty)
+ Hledger.UI.Main: uiInitialState :: UIOpts -> Journal -> UIState
+ Hledger.UI.Main: warningOverlay :: String -> Int -> Widget Name
+ Hledger.UI.UIOptions: uiLoadOpts :: CliOpts -> CliOpts
+ Hledger.UI.UIScreens: accountsScreenQuery :: AccountsScreenKind -> Query
+ Hledger.UI.UIScreens: accountsScreenRoptsMod :: AccountsScreenKind -> ReportOpts -> ReportOpts
+ Hledger.UI.UIScreens: listMoveToIfDisplayItems :: Int -> [item] -> GenericList Name Vector item -> GenericList Name Vector item
+ Hledger.UI.UIScreens: uiDisplayAccount :: UIOpts -> AccountName -> AccountName
+ Hledger.UI.UIState: toggleLots :: UIState -> UIState
+ Hledger.UI.UIState: uiDisplayJournal :: UIOpts -> Journal -> Journal
+ Hledger.UI.UITypes: AllAccounts :: AccountsScreenKind
+ Hledger.UI.UITypes: BalancesheetAccounts :: AccountsScreenKind
+ Hledger.UI.UITypes: CashAccounts :: AccountsScreenKind
+ Hledger.UI.UITypes: FocusGainedAt :: UTCTime -> ClickFocus
+ Hledger.UI.UITypes: IgnoringClick :: ClickFocus
+ Hledger.UI.UITypes: IncomestatementAccounts :: AccountsScreenKind
+ Hledger.UI.UITypes: Unfocused :: ClickFocus
+ Hledger.UI.UITypes: [_assKind] :: AccountsScreenState -> AccountsScreenKind
+ Hledger.UI.UITypes: [_tssForceInclusive] :: TransactionScreenState -> Bool
+ Hledger.UI.UITypes: [aClickFocus] :: UIState -> ClickFocus
+ Hledger.UI.UITypes: [aWarnings] :: UIState -> [String]
+ Hledger.UI.UITypes: [auncollapsedjournal] :: UIState -> Journal
+ Hledger.UI.UITypes: assKind :: Lens' AccountsScreenState AccountsScreenKind
+ Hledger.UI.UITypes: data AccountsScreenKind
+ Hledger.UI.UITypes: data ClickFocus
+ Hledger.UI.UITypes: instance GHC.Classes.Eq Hledger.UI.UITypes.AccountsScreenKind
+ Hledger.UI.UITypes: instance GHC.Classes.Eq Hledger.UI.UITypes.ClickFocus
+ Hledger.UI.UITypes: instance GHC.Classes.Ord Hledger.UI.UITypes.AccountsScreenKind
+ Hledger.UI.UITypes: instance GHC.Show.Show Hledger.UI.UITypes.AccountsScreenKind
+ Hledger.UI.UITypes: instance GHC.Show.Show Hledger.UI.UITypes.ClickFocus
+ Hledger.UI.UITypes: tssForceInclusive :: Lens' TransactionScreenState Bool
+ Hledger.UI.UIUtils: clickFocusStep :: UTCTime -> BrickEvent n e -> ClickFocus -> (ClickFocus, Bool)
+ Hledger.UI.UIUtils: journalIsFromStdin :: Journal -> Bool
+ Hledger.UI.UIUtils: uiInstallWarningCollector :: IO ()
+ Hledger.UI.UIUtils: uiTakeWarnings :: IO [String]
- Hledger.UI.AccountsScreen: asDraw :: UIState -> [Widget Name]
+ Hledger.UI.AccountsScreen: asDraw :: AccountsScreenState -> UIState -> [Widget Name]
- Hledger.UI.AccountsScreen: asDrawHelper :: UIState -> ReportOpts -> String -> [Widget Name]
+ Hledger.UI.AccountsScreen: asDrawHelper :: AccountsScreenState -> UIState -> ReportOpts -> String -> [Widget Name]
- Hledger.UI.AccountsScreen: asHandle :: BrickEvent Name AppEvent -> EventM Name UIState ()
+ Hledger.UI.AccountsScreen: asHandle :: AccountsScreenState -> BrickEvent Name AppEvent -> EventM Name UIState ()
- Hledger.UI.AccountsScreen: asHandleNormalMode :: AccountsLikeScreen -> BrickEvent Name AppEvent -> EventM Name UIState ()
+ Hledger.UI.AccountsScreen: asHandleNormalMode :: AccountsScreenState -> BrickEvent Name AppEvent -> EventM Name UIState ()
- Hledger.UI.AccountsScreen: asNew :: UIOpts -> Day -> Journal -> Maybe AccountName -> Screen
+ Hledger.UI.AccountsScreen: asNew :: AccountsScreenKind -> UIOpts -> Day -> Journal -> Maybe AccountName -> Screen
- Hledger.UI.ErrorScreen: esDraw :: UIState -> [Widget Name]
+ Hledger.UI.ErrorScreen: esDraw :: ErrorScreenState -> UIState -> [Widget Name]
- Hledger.UI.ErrorScreen: esHandle :: BrickEvent Name AppEvent -> EventM Name UIState ()
+ Hledger.UI.ErrorScreen: esHandle :: ErrorScreenState -> BrickEvent Name AppEvent -> EventM Name UIState ()
- Hledger.UI.MenuScreen: msDraw :: UIState -> [Widget Name]
+ Hledger.UI.MenuScreen: msDraw :: MenuScreenState -> UIState -> [Widget Name]
- Hledger.UI.MenuScreen: msHandle :: BrickEvent Name AppEvent -> EventM Name UIState ()
+ Hledger.UI.MenuScreen: msHandle :: MenuScreenState -> BrickEvent Name AppEvent -> EventM Name UIState ()
- Hledger.UI.RegisterScreen: rsDraw :: UIState -> [Widget Name]
+ Hledger.UI.RegisterScreen: rsDraw :: RegisterScreenState -> UIState -> [Widget Name]
- Hledger.UI.RegisterScreen: rsHandle :: BrickEvent Name AppEvent -> EventM Name UIState ()
+ Hledger.UI.RegisterScreen: rsHandle :: RegisterScreenState -> BrickEvent Name AppEvent -> EventM Name UIState ()
- Hledger.UI.TransactionScreen: tsDraw :: UIState -> [Widget Name]
+ Hledger.UI.TransactionScreen: tsDraw :: TransactionScreenState -> UIState -> [Widget Name]
- Hledger.UI.TransactionScreen: tsHandle :: BrickEvent Name AppEvent -> EventM Name UIState ()
+ Hledger.UI.TransactionScreen: tsHandle :: TransactionScreenState -> BrickEvent Name AppEvent -> EventM Name UIState ()
- Hledger.UI.TransactionScreen: tsNew :: AccountName -> [NumberedTransaction] -> NumberedTransaction -> Screen
+ Hledger.UI.TransactionScreen: tsNew :: AccountName -> Bool -> [NumberedTransaction] -> NumberedTransaction -> Screen
- Hledger.UI.TransactionScreen: tsUpdate :: TransactionScreenState -> TransactionScreenState
+ Hledger.UI.TransactionScreen: tsUpdate :: UIOpts -> Day -> Journal -> TransactionScreenState -> TransactionScreenState
- Hledger.UI.UIScreens: asNew :: UIOpts -> Day -> Journal -> Maybe AccountName -> Screen
+ Hledger.UI.UIScreens: asNew :: AccountsScreenKind -> UIOpts -> Day -> Journal -> Maybe AccountName -> Screen
- Hledger.UI.UIScreens: tsNew :: AccountName -> [NumberedTransaction] -> NumberedTransaction -> Screen
+ Hledger.UI.UIScreens: tsNew :: AccountName -> Bool -> [NumberedTransaction] -> NumberedTransaction -> Screen
- Hledger.UI.UIScreens: tsUpdate :: TransactionScreenState -> TransactionScreenState
+ Hledger.UI.UIScreens: tsUpdate :: UIOpts -> Day -> Journal -> TransactionScreenState -> TransactionScreenState
- Hledger.UI.UIState: regenerateScreens :: Journal -> Day -> UIState -> UIState
+ Hledger.UI.UIState: regenerateScreens :: Day -> UIState -> UIState
- Hledger.UI.UITypes: ASS :: AccountName -> List Name AccountsScreenItem -> AccountsScreenState
+ Hledger.UI.UITypes: ASS :: AccountsScreenKind -> AccountName -> List Name AccountsScreenItem -> AccountsScreenState
- Hledger.UI.UITypes: MenuScreenItem :: Text -> ScreenName -> MenuScreenItem
+ Hledger.UI.UITypes: MenuScreenItem :: Text -> AccountsScreenKind -> MenuScreenItem
- Hledger.UI.UITypes: TSS :: AccountName -> [NumberedTransaction] -> NumberedTransaction -> TransactionScreenState
+ Hledger.UI.UITypes: TSS :: AccountName -> Bool -> [NumberedTransaction] -> NumberedTransaction -> TransactionScreenState
- Hledger.UI.UITypes: UIState :: UIOpts -> UIOpts -> Journal -> [Screen] -> Screen -> Mode -> UIState
+ Hledger.UI.UITypes: UIState :: UIOpts -> UIOpts -> Journal -> Journal -> ~Screen -> ~[Screen] -> Mode -> [String] -> ClickFocus -> UIState
- Hledger.UI.UITypes: [aPrevScreens] :: UIState -> [Screen]
+ Hledger.UI.UITypes: [aPrevScreens] :: UIState -> ~[Screen]
- Hledger.UI.UITypes: [aScreen] :: UIState -> Screen
+ Hledger.UI.UITypes: [aScreen] :: UIState -> ~Screen
- Hledger.UI.UITypes: [msItemScreen] :: MenuScreenItem -> ScreenName
+ Hledger.UI.UITypes: [msItemScreen] :: MenuScreenItem -> AccountsScreenKind
- Hledger.UI.UIUtils: listScrollPushingSelection :: Name -> Int -> Int -> EventM Name (List Name item) (GenericList Name Vector item)
+ Hledger.UI.UIUtils: listScrollPushingSelection :: Name -> Int -> Int -> EventM Name (List Name item) ()
- Hledger.UI.UIUtils: scrollSelectionToMiddle :: List Name item -> EventM Name UIState ()
+ Hledger.UI.UIUtils: scrollSelectionToMiddle :: Int -> List Name item -> EventM Name UIState ()

Files

CHANGES.md view
@@ -5,24 +5,127 @@ | |_| | |  \__,_|_| -Breaking changes+Item order: security fixes first, then breaking changes, then the rest.+Section headings: "Security" first if any, then "Breaking changes"+if any; then topic headings,+or a suitable generic heading (eg Fixes, Improvements), as needed. -Fixes+--> -Features+User-visible changes in hledger-ui.+See also the hledger changelog. -Improvements -Docs+# 2.0 2026-12-01 -API+All changes since hledger-ui 1.52.4.+For the 1.99.x preview releases, and 2.0's changes since the last of them (1.99.6),+see <https://hledger.org/relnotes199.html>.+See also the hledger changelog, for changes affecting all the hledger tools+(lot tracking, commodity aliases, the `::` find query, translations, faster starts and reloads, etc.) --->+## Highlights -User-visible changes in hledger-ui.-See also the hledger changelog.+The most notable changes since hledger-ui 1.52; each is described below. +- Watch mode is on by default, with no memory leak, and reloads more robustly. (Breaking changes, Fixes, Improvements)+- The `L` key shows or hides lot subaccounts and per-lot detail, for journals using hledger 2's lot tracking. (Improvements)+- Assert rules are checked on load and reload and when `I` re-enables checks. (Improvements)+- Translations: the `--lang` option shows the UI in other languages. (Improvements)+- The journal can be read from stdin, on unix-like systems. (Improvements)+- And hledger's improvements (more speed, commodity aliases, new queries; see the hledger changelog). +## Breaking changes++- Automatic reloading is now enabled by default: hledger-ui watches for data and date changes, and reloads automatically.+  The new `--no-watch` flag disables this, reloading only with the `g` key.+  The rightmost `--watch`/`--no-watch` flag wins, so a config file setting can be overridden on the command line.++- With more than one of `--cash`/`--bs`/`--is`/`--all`/`--register`, the last one wins,+  so a config file's choice can be overridden on the command line. (Previously they had a fixed priority order.)++- `--tldr` is renamed to `--examples` (see the hledger changelog).++## Fixes++- Fixed a long-standing memory leak (and background CPU use) when reloading in watch mode.+  Now watch mode has no extra memory/CPU cost, and can be used freely with large journals.+  ([#1825])++- hledger-ui gracefully handles more reloading failures,+  such as failure caused by a changed CSV file or rules file,+  or by a file momentarily removed when your editor saves it.+  Instead of quitting, it now shows the error screen, allowing recovery.++- The transaction screen now always shows the whole journal entry.+  Previously with a `cur:` or `amt:` query in effect, it showed the entry without the non-matching postings.+  (A long-standing bug, since hledger 1.23.)++- The mouse wheel now scrolls all the way. Previously it moved the viewport at most to the current selection+  and then stopped; you had to move the selection with the arrow keys to get any further.++- Pressing `DOWN` at the last list item, or `C-l` (recenter) when near the end of a list,+  no longer scrolls into blank padding space; hledger-ui now keeps as many items as possible on screen.+  (Juan Wajnerman, [#2278], [#2593])++- With `--pivot`, re-enabling checks with `I` did not really recheck them, so failures went unreported.++- On Windows, the `A` key (running hledger-iadd), the `E` key (running `$EDITOR`),+  and the running of info/man/tldr/pager helpers now correctly quote file paths containing spaces.+  ([#2646])++## Improvements++- The `L` key toggles showing lot subaccounts and per-lot detail (like the CLI's `--lots` flag),+  for journals using hledger 2's lot tracking. `ESC` resets it to the startup state.++- hledger-ui checks the new assert rules (see the hledger changelog),+  when the journal is loaded or reloaded, and when checks are re-enabled with `I`.+  They always see future-dated ordinary transactions, even when those are hidden behind the `F` key.+  They see transactions generated by periodic rules only when `--forecast` is used.++- The new `--lang` option shows hledger-ui's menu and accounts screen names in other languages (see the hledger changelog).+  The help dialog and the register screen's labels are not yet translated.+  (Arthur Cinader)++- hledger-ui can now read the journal from stdin (`-f-`), on unix-like systems.+  With a stdin journal the data can't be re-read or edited, so the `g`, `a`, `A` and `E` keys and watch mode have no effect.++- Changes to CSV rules files now trigger a reload, like changes to data files.++- The transaction screen now refreshes in place when there's a reload. Previously you had to exit and re-enter it.+  ([#1825])++- Warnings (eg CSV data warnings, which could appear on every reload) no longer scroll and disrupt the display;+  they are shown on the bottom line, until the next key press.+  Also the screen is fully repainted after a reload, repairing any other stray terminal output,+  and error screen reloading is less flickery and more robust.++- The `E` key now jumps to the error position with the Zed and Sublime Text editors, also.+  (Rostislav Raykov)++- `CTRL-c` now quits, like `q`, from any screen or mode, including while the help or a minibuffer is open.+  Previously it was ignored.++- Clicking a background hledger-ui window now just brings it forward,+  without also selecting or entering the item under the pointer.++- The `-?` and `--webman` flags are added (see the hledger changelog).++- Allow brick 3.x (with 3.1 support from GuillaumedeVolpiano), doclayout 0.6. Exclude megaparsec 9.8.0, to avoid a position marker bug in error messages+  ([megaparsec#572](https://github.com/mrkkrp/megaparsec/issues/572)).++## Docs++- The manual's KEYS section is grouped like the help dialog; the depth keys, help dialog keys, `CTRL-z` and editor variables+  are documented; and the watch mode and BUGS sections are updated.++[#1825]: https://github.com/hledgerorg/hledger/issues/1825+[#2278]: https://github.com/hledgerorg/hledger/issues/2278+[#2593]: https://github.com/hledgerorg/hledger/issues/2593+[#2646]: https://github.com/hledgerorg/hledger/issues/2646++ # 1.52.4 2026-09-10  Improvements@@ -71,15 +174,17 @@ - The selection colour has been changed to cyan, for better visibility in typical terminals.   (Rahul Shankar V, Simon Michael) [#2175], [#2551] -[#1911]: https://github.com/simonmichael/hledger/issues/1911-[#2168]: https://github.com/simonmichael/hledger/issues/2168-[#2175]: https://github.com/simonmichael/hledger/issues/2175-[#2476]: https://github.com/simonmichael/hledger/issues/2476-[#2544]: https://github.com/simonmichael/hledger/issues/2544-[#2550]: https://github.com/simonmichael/hledger/issues/2550-[#2551]: https://github.com/simonmichael/hledger/issues/2551+- Allow brick 2.11 +[#1911]: https://github.com/hledgerorg/hledger/issues/1911+[#2168]: https://github.com/hledgerorg/hledger/issues/2168+[#2175]: https://github.com/hledgerorg/hledger/issues/2175+[#2476]: https://github.com/hledgerorg/hledger/issues/2476+[#2544]: https://github.com/hledgerorg/hledger/issues/2544+[#2550]: https://github.com/hledgerorg/hledger/issues/2550+[#2551]: https://github.com/hledgerorg/hledger/issues/2551 + # 1.51.2 2026-01-08  - hledger add invoked via the `a` key now shows output properly,@@ -89,7 +194,7 @@  - Allow base 4.22 / ghc 9.14. -[#2512]: https://github.com/simonmichael/hledger/issues/2512+[#2512]: https://github.com/hledgerorg/hledger/issues/2512   # 1.51.1 2025-12-08@@ -97,6 +202,11 @@ - Uses hledger 1.51.1.  +# 1.50.5 2025-12-08++- Uses hledger 1.50.5.++ # 1.51 2025-12-05  Improvements@@ -106,11 +216,6 @@ - Uses hledger 1.51.  -# 1.50.5 2025-12-08--- Uses hledger 1.50.5.-- # 1.50.4 2025-12-04  - Uses hledger 1.50.4.@@ -166,10 +271,10 @@ - Hledger.UI.UIState:   enableForecastPreservingPeriod -> enableForecast -[#2014]: https://github.com/simonmichael/hledger/issues/2014-[#2288]: https://github.com/simonmichael/hledger/issues/2288-[#2451]: https://github.com/simonmichael/hledger/issues/2451-[#2454]: https://github.com/simonmichael/hledger/issues/2454+[#2014]: https://github.com/hledgerorg/hledger/issues/2014+[#2288]: https://github.com/hledgerorg/hledger/issues/2288+[#2451]: https://github.com/hledgerorg/hledger/issues/2451+[#2454]: https://github.com/hledgerorg/hledger/issues/2454   # 1.50 2025-09-03@@ -339,7 +444,7 @@   and seems not strictly needed.   [#2149] -[#2149]: https://github.com/simonmichael/hledger/issues/2149+[#2149]: https://github.com/hledgerorg/hledger/issues/2149   # 1.33 2024-04-18
Hledger/UI/AccountsScreen.hs view
@@ -40,6 +40,7 @@ import System.FilePath (takeFileName) import Text.DocLayout (realLength) +import Hledger.Utils.I18n (tr) import Hledger import Hledger.Cli hiding (Mode, mode, progname, prognameandversion) import Hledger.UI.UIOptions@@ -55,22 +56,29 @@ import Safe (headDef)  -asDraw :: UIState -> [Widget Name]-asDraw ui = dbgui "asDraw" $ asDrawHelper ui ropts' scrname+asDraw :: AccountsScreenState -> UIState -> [Widget Name]+asDraw ass@ASS{_assKind=kind} ui = dbgui "asDraw" $ asDrawHelper ass ui ropts' scrname   where-    ropts' = _rsReportOpts $ reportspec_ $ uoCliOpts $ aopts ui-    scrname = "account " ++ if ishistorical then "balances" else "changes"-      where ishistorical = balanceaccum_ ropts' == Historical+    ropts'  = accountsScreenRoptsMod kind $ _rsReportOpts $ reportspec_ $ uoCliOpts $ aopts ui+    scrname = accountsScreenName kind ropts' +-- | The display name shown in an accounts-like screen's header, for the given kind.+accountsScreenName :: AccountsScreenKind -> ReportOpts -> String+accountsScreenName kind ropts = T.unpack $ case kind of+  AllAccounts | balanceaccum_ ropts == Historical -> tr trs "account balances"+              | otherwise                         -> tr trs "account changes"+  CashAccounts            -> tr trs "cash balances"+  BalancesheetAccounts    -> tr trs "balance sheet balances"+  IncomestatementAccounts -> tr trs "income statement changes"+  where trs = translations_ ropts+ -- | 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 =+asDrawHelper :: AccountsScreenState -> UIState -> ReportOpts -> String -> [Widget Name]+asDrawHelper ass UIState{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+  case mode of       Help -> [helpDialog, maincontent]       _    -> [maincontent]       where@@ -108,7 +116,7 @@             ishistorical = balanceaccum_ ropts == Historical              toplabel =-                  withAttr (attrName "border" <> attrName "filename") files+                  withAttr (attrName "border" <> attrName "filename") fs               <+> toggles               <+> str (" " ++ scrname)               <+> borderPeriodStr (if ishistorical then "at end of" else "in") (period_ ropts)@@ -119,7 +127,7 @@                   then withAttr (attrName "border" <> attrName "query") (str " ignoring balance assertions")                   else str "")               where-                files = case journalFilePaths j of+                fs = case journalFilePaths j of                               [] -> str ""                               f:_ -> str $ takeFileName f                               -- [f,_:[]] -> (withAttr ("border" <> "bold") $ str $ takeFileName f) <+> str " (& 1 included file)"@@ -149,11 +157,12 @@                   -- ,("t", str "tree")                   -- ,("l", str "list")                   ,("-+", str "depth")-                  ,case scr of-                    BS _ -> ("", str "")-                    IS _ -> ("", str "")-                    _    -> ("H", renderToggle (not ishistorical) "end-bals" "changes")+                  ,case _assKind ass of+                    BalancesheetAccounts    -> ("", str "")+                    IncomestatementAccounts -> ("", str "")+                    _                       -> ("H", renderToggle (not ishistorical) "end-bals" "changes")                   ,("F", renderToggle1 (isJust . forecast_ $ inputopts_ copts) "forecast")+                  ,("L", renderToggle1 (boolopt "lots" $ rawopts_ copts) "lots")                   --,("/", "filter")                   --,("DEL", "unfilter")                   --,("ESC", "cancel/top")@@ -184,24 +193,21 @@             | 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+asHandle :: AccountsScreenState -> BrickEvent Name AppEvent -> EventM Name UIState ()+asHandle ass 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+  ui0@UIState{aMode=mode} <- get'+  -- save the currently selected account, in case we leave this screen and lose the selection+  put' ui0{aScreen=AS ass{_assSelectedAccount=asSelectedAccount ass}}+  case mode of+    Normal          -> asHandleNormalMode ass 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+-- The provided state should be the ui state's current screen.+asHandleNormalMode :: AccountsScreenState -> BrickEvent Name AppEvent -> EventM Name UIState ()+asHandleNormalMode ass ev = do   dbguiEv "asHandleNormalMode"    ui@UIState{aopts=UIOpts{uoCliOpts=copts}, ajournal=j} <- get'@@ -209,7 +215,7 @@   let     l = _assList ass     selacct = asSelectedAccount ass-    centerSelection = scrollSelectionToMiddle l+    centerSelection = scrollSelectionToMiddle (asListSize l) l     clickedAcctAt y =       case asItemAccountName <$> listElements l !? y of         Just t | not $ T.null t -> Just t@@ -237,12 +243,12 @@     -- 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)+      modify' (setReportPeriod (DayPeriod d) >>> regenerateScreens 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)+    VtyEvent (EvKey (KChar '/') []) -> modify' (showMinibuffer "filter" Nothing >>> regenerateScreens d)+    VtyEvent (EvKey k           []) | k `elem` [KBS, KDel] -> modify' (resetFilter >>> regenerateScreens d)      -- run external programs:     VtyEvent (EvKey (KChar 'a') []) -> suspendAndResume $ clearScreen >> setCursorPosition 0 0 >> add (cliOptsDropArgs copts) j >> uiReloadIfFileChanged copts d j ui@@ -255,44 +261,45 @@       let l'' = if isBlankItem (listSelectedElement l')                 then listMoveTo lastnonblankidx l'                 else l'-      put' ui{aScreen=scons ass{_assList=l''}}+      put' ui{aScreen=AS ass{_assList=l''}}      VtyEvent (EvKey (KChar 'K') []) -> do       let l' = listMoveBy (-10) l-      put' ui{aScreen=scons ass{_assList=l'}}+      put' ui{aScreen=AS ass{_assList=l'}}      -- 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)+    VtyEvent (EvKey (KChar 'T') []) ->       modify' (setReportPeriod (DayPeriod d)    >>> regenerateScreens d)+    VtyEvent (EvKey (KDown)     [MShift]) -> modify' (shrinkReportPeriod d             >>> regenerateScreens d)+    VtyEvent (EvKey (KUp)       [MShift]) -> modify' (growReportPeriod d               >>> regenerateScreens d)+    VtyEvent (EvKey (KRight)    [MShift]) -> modify' (nextReportPeriod journalspan     >>> regenerateScreens d)+    VtyEvent (EvKey (KLeft)     [MShift]) -> modify' (previousReportPeriod journalspan >>> regenerateScreens 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)+    VtyEvent (EvKey (KChar 'F') []) -> modify' (toggleForecast d   >>> regenerateScreens d)+    VtyEvent (EvKey (KChar 'B') []) -> modify' (toggleConversionOp >>> regenerateScreens d)+    VtyEvent (EvKey (KChar 'V') []) -> modify' (toggleValue        >>> regenerateScreens d)+    VtyEvent (EvKey (KChar '0') []) -> modify' (setDepth (Just 0)  >>> regenerateScreens d)+    VtyEvent (EvKey (KChar '1') []) -> modify' (setDepth (Just 1)  >>> regenerateScreens d)+    VtyEvent (EvKey (KChar '2') []) -> modify' (setDepth (Just 2)  >>> regenerateScreens d)+    VtyEvent (EvKey (KChar '3') []) -> modify' (setDepth (Just 3)  >>> regenerateScreens d)+    VtyEvent (EvKey (KChar '4') []) -> modify' (setDepth (Just 4)  >>> regenerateScreens d)+    VtyEvent (EvKey (KChar '5') []) -> modify' (setDepth (Just 5)  >>> regenerateScreens d)+    VtyEvent (EvKey (KChar '6') []) -> modify' (setDepth (Just 6)  >>> regenerateScreens d)+    VtyEvent (EvKey (KChar '7') []) -> modify' (setDepth (Just 7)  >>> regenerateScreens d)+    VtyEvent (EvKey (KChar '8') []) -> modify' (setDepth (Just 8)  >>> regenerateScreens d)+    VtyEvent (EvKey (KChar '9') []) -> modify' (setDepth (Just 9)  >>> regenerateScreens d)+    VtyEvent (EvKey (KChar c) []) | c `elem` ['-','_'] -> modify' (decDepth >>> regenerateScreens d)+    VtyEvent (EvKey (KChar c) []) | c `elem` ['+','='] -> modify' (incDepth >>> regenerateScreens 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+    VtyEvent (EvKey (KChar 'L') []) -> modify' (toggleLots         >>> regenerateScreens d) >> centerSelection+    VtyEvent (EvKey (KChar 'H') []) -> modify' (toggleHistorical   >>> regenerateScreens d) >> centerSelection  -- harmless on BS/IS screens+    VtyEvent (EvKey (KChar 't') []) -> modify' (toggleTree         >>> regenerateScreens d) >> centerSelection+    VtyEvent (EvKey (KChar 'R') []) -> modify' (toggleReal         >>> regenerateScreens d) >> centerSelection+    VtyEvent (EvKey (KChar 'U') []) -> modify' (toggleUnmarked     >>> regenerateScreens d) >> centerSelection+    VtyEvent (EvKey (KChar 'P') []) -> modify' (togglePending      >>> regenerateScreens d) >> centerSelection+    VtyEvent (EvKey (KChar 'C') []) -> modify' (toggleCleared      >>> regenerateScreens d) >> centerSelection+    VtyEvent (EvKey (KChar c) []) | c `elem` ['z','Z'] -> modify' (toggleEmpty >>> regenerateScreens 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@@ -305,7 +312,7 @@     -- 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'}+      put' ui{aScreen=AS ass'}       where         clickeditem = (0,) <$> listElements l !? y         ass' = ass{_assList=listMoveTo y l}@@ -314,7 +321,7 @@     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'}}+      put' ui{aScreen=AS 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.@@ -323,19 +330,19 @@       if isBlankItem $ listSelectedElement l1       then do         let l2 = listMoveTo lastnonblankidx l1-        scrollSelectionToMiddle l2-        put' ui{aScreen=scons ass{_assList=l2}}+        scrollSelectionToMiddle (asListSize l2) l2+        put' ui{aScreen=AS ass{_assList=l2}}       else-        put' ui{aScreen=scons ass{_assList=l1}}+        put' ui{aScreen=AS 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+    -- DOWN key when selection is at the last item: do nothing+    VtyEvent e | e `elem` moveDownEvents, isBlankItem mnextelement -> return ()       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}+      put' ui{aScreen=AS $ ass & assList .~ l' & assSelectedAccount .~ selacct}      -- Any other mouse/app event: ignore     MouseDown{} -> return ()@@ -344,11 +351,11 @@  -- | Handle events when in minibuffer mode on any screen. handleMinibufferMode ed ev = do-  ui@UIState{ajournal=j} <- get'+  ui <- get'   d <- liftIO getCurrentDay   case ev of     VtyEvent (EvKey KEsc   []) -> put' $ closeMinibuffer ui-    VtyEvent (EvKey KEnter []) -> put' $ regenerateScreens j d ui'+    VtyEvent (EvKey KEnter []) -> put' $ regenerateScreens d ui'       where         ui' = setFilter s (closeMinibuffer ui)           & fromRight (showMinibuffer "Cannot compile regular expression" (Just s) ui)@@ -398,8 +405,6 @@ 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} =@@ -414,7 +419,9 @@             where               as = map asItemAccountName $ V.toList $ listElements l -isBlankItem mitem = ((asItemAccountName . snd) <$> mitem) == Just ""+-- | Is this a blank account-list item, or no item at all (empty list / no selection) ?+-- Either way there is no real account here to act on.+isBlankItem mitem = maybe True (T.null . asItemAccountName . snd) mitem  asListSize = V.length . V.takeWhile ((/="").asItemAccountName) . listElements 
− Hledger/UI/BalancesheetScreen.hs
@@ -1,29 +0,0 @@--- 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/CashScreen.hs
@@ -1,29 +0,0 @@--- 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/Editor.hs view
@@ -33,13 +33,15 @@ -- 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+runIadd "-" = return ExitSuccess  -- journal was read from stdin; there is no file to add to+runIadd f = runCommand ("hledger-iadd -f " ++ shellQuoteIfNeeded 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 _ "-" = return ExitSuccess  -- journal was read from stdin; there is no file to edit runEditor mpos f = editFileAtPositionCommand mpos f >>= runCommand >>= waitForProcess  -- | Get a shell command line to open the user's preferred text editor@@ -81,6 +83,11 @@ -- vi & variants    Just (line, _)        vi +LINE FILE --                  Just ('-' : _, _)     vi +     FILE --                  Nothing               vi       FILE+-- +-- zed & sublime    Just (line, Just col) zed FILE:LINE:COL+--                  Just (line, Nothing)  zed FILE:LINE+--                  Just ('-' : _, _)     zed FILE+--                  Nothing               zed FILE -- -- (other PROG)     _                     PROG FILE --@@ -94,7 +101,7 @@ editFileAtPositionCommand mpos f = do   cmd <- getEditCommand   let editor = lowercase $ takeBaseName $ headDef "" $ words' cmd-      f' = singleQuoteIfNeeded f+      f' = shellQuoteIfNeeded f       mpos' = Just . bimap show (fmap show) =<< mpos       join sep = intercalate sep . catMaybes       args = case editor of@@ -125,6 +132,10 @@           Nothing -> [f']           Just ('-' : _, _) -> [f']           Just (l, _) -> ['+' : l, f']+        e | e `elem` ["zed", "subl"] -> case mpos' of+          Nothing -> [f']+          Just ('-' : _, _) -> [f']+          Just (l, mc) -> [join ":" [Just f', Just l, mc]]         _ -> [f']   return $ unwords $ cmd:args @@ -142,4 +153,3 @@   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/ErrorScreen.hs view
@@ -14,17 +14,20 @@  ,uiReload  ,uiReloadIfFileChanged  ,uiToggleBalanceAssertions+ ,uiAdjustOpts  ) where  import Brick -- import Brick.Widgets.Border ("border")+import Control.Exception (ErrorCall, IOException, catch) import Control.Monad.IO.Class (liftIO)+import Data.Function ((&))+import Data.Maybe (isNothing) import Data.Time.Calendar (Day) import Data.Void (Void) import Graphics.Vty (Event(..),Key(..),Modifier(..))-import Lens.Micro ((^.))-import Safe (headMay)+import Lens.Micro ((^.), set) import Text.Megaparsec import Text.Megaparsec.Char @@ -36,10 +39,8 @@ import Hledger.UI.UIScreens import Hledger.UI.Editor -esDraw :: UIState -> [Widget Name]-esDraw UIState{aScreen=ES ESS{..}-              ,aMode=mode-              } =+esDraw :: ErrorScreenState -> UIState -> [Widget Name]+esDraw ESS{..} UIState{aMode=mode} =   case mode of     Help       -> [helpDialog, maincontent]     _          -> [maincontent]@@ -64,14 +65,12 @@               ,("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+esHandle :: ErrorScreenState -> BrickEvent Name AppEvent -> EventM Name UIState ()+esHandle ESS{..} ev = do   ui0 <- get'   case ui0 of-    ui@UIState{aScreen=ES ESS{..}-              ,aopts=UIOpts{uoCliOpts=copts}+    ui@UIState{aopts=UIOpts{uoCliOpts=copts}               ,ajournal=j               ,aMode=mode               } ->@@ -108,29 +107,23 @@             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+      -- Reload from the error screen: drop the error screen, then reload and regenerate the+      -- revealed parent (uiReload re-pushes an error screen if it still fails), and recheck+      -- balance assertions. This works for any parent, since every screen now regenerates from+      -- its own stored parameters.+      esReload copts d ui =+        uiReload copts d (popScreen ui) >>= put' . uiCheckBalanceAssertions d+      esReloadIfFileChanged copts d j ui =+        liftIO (uiReloadIfFileChanged copts d j (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 '"'+  anySingle `manyTill` single '"'   f <- anySingle `manyTill` (oneOf ['"','\n'])   choice [       do@@ -142,19 +135,33 @@       do           string " (lines "           l <- read <$> some digitChar-          char '-'+          single '-'           some digitChar-          char ')'+          single ')'           return (f, l, 1)       ]   -- Defined here so it can reference the error screen: --- | Modify some input options for hledger-ui (enable --forecast).+-- | Modify some input options for loading the journal in hledger-ui, given its startup options:+-- always enable --forecast, so forecast transactions can be shown or hidden without reloading.+-- If --forecast wasn't used at startup, mark the forecast as only for display, so assert rules ignore it. uiAdjustOpts :: UIOpts -> CliOpts -> CliOpts-uiAdjustOpts uopts = enableForecast uopts+uiAdjustOpts uopts copts =+  enableForecast uopts copts & set forecastOnlyForDisplay (isNothing $ uopts ^. forecast) +-- | Run a journal-loading action, converting exceptions to Left so callers can+-- show them on the error screen instead of crashing the app. Journal reader+-- parse errors are returned as Left already, but some load errors are thrown+-- as exceptions: ErrorCall (from error', eg for CSV conversion problems) or+-- possibly IO errors (eg a watched file missing momentarily during an editor's save).+catchLoadErrors :: IO (Either String a) -> IO (Either String a)+catchLoadErrors act =+  act+  `catch` (\e -> return $ Left $ show (e :: ErrorCall))+  `catch` (\e -> return $ Left $ show (e :: IOException))+ -- | 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.@@ -166,15 +173,23 @@ -- 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)+uiReload copts d ui0 = do+  ej <- liftIO $+    let loadopts = uiLoadOpts $ uiAdjustOpts (astartupopts ui0) copts+    in if journalIsFromStdin (ajournal ui0)+       then return $ Right $ auncollapsedjournal ui0  -- stdin can't be re-read; keep the journal as loaded+       else catchLoadErrors $ runExceptT $ journalReload loadopts+  -- dbg1IO "uiReload before reload" (map tdescription $ jtxns $ ajournal ui0)+  -- show any warnings collected during the reload (until the next keypress)+  ui <- liftIO $ (\ws -> ui0{aWarnings=ws}) <$> uiTakeWarnings+  -- The reload may have written to the terminal, eg output from third-party code+  -- not using our warning handler; repaint the whole screen to repair any disruption.+  redraw   return $ case ej of-    Right j  ->-      -- dbg1 "uiReload after reload" (map tdescription $ jtxns j) $-      regenerateScreens j d ui+    Right jraw ->+      -- dbg1 "uiReload after reload" (map tdescription $ jtxns jraw) $+      -- save the uncollapsed journal; regenerateScreens derives the display journal from it+      regenerateScreens d ui{auncollapsedjournal = jraw}     Left err ->       case ui of         UIState{aScreen=ES _} -> ui{aScreen=esNew err}@@ -192,12 +207,17 @@ -- 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+uiReloadIfFileChanged copts d j ui0 = do   ej <--    let copts1 = uiAdjustOpts (astartupopts ui) copts-    in runExceptT $ journalReloadIfChanged copts1 d j+    let loadopts = uiLoadOpts $ uiAdjustOpts (astartupopts ui0) copts+    in catchLoadErrors $ runExceptT $ journalReloadIfChanged loadopts d j+  -- show any warnings collected during the reload (until the next keypress)+  ui <- (\ws -> ui0{aWarnings=ws}) <$> uiTakeWarnings   return $ case ej of-    Right (j', _) -> regenerateScreens j' d ui+    -- changed: save the uncollapsed journal; regenerateScreens derives the display journal from it+    Right (jraw, True)  -> regenerateScreens d ui{auncollapsedjournal = jraw}+    -- unchanged: nothing reloaded, refresh in place (opts/date may have changed), keep the journal+    Right (_,    False) -> regenerateScreens d ui     Left err -> case aScreen ui of         ES _ -> ui{aScreen=esNew err}         _    -> pushScreen (esNew err) ui@@ -211,23 +231,35 @@ 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+  | otherwise = either (uiShowError ui) (const ui) $ journalCheckBalanceAssertions j --- | Toggle ignoring balance assertions (when user presses I), and if no longer ignoring, recheck them.+-- | Recheck balance assertions and assert rules in the current journal (when the user re-enables checks),+-- and if any fail, enter (or update) the error screen.+-- Assert rules are checked as at load time: on the journal as loaded (with lot detail),+-- with the same input options (ignoring forecast transactions unless --forecast was used at startup),+-- with today's date.+-- Should not be used with --pivot or --obfuscate, which change account names.+uiCheckAssertions :: Day -> UIState -> UIState+uiCheckAssertions d ui@UIState{ajournal=j, auncollapsedjournal=uj, astartupopts=uopts, aopts=UIOpts{uoCliOpts=copts}} =+  either (uiShowError ui) (const ui) $ do+    journalCheckBalanceAssertions j+    journalCheckAssertsWith (inputopts_ $ uiAdjustOpts uopts copts){_ioDay=d} uj++-- | Show this error on the error screen, entering it or updating it.+uiShowError :: UIState -> String -> UIState+uiShowError ui err = case ui of+  UIState{aScreen=ES sst} -> ui{aScreen=ES sst{_essError=err}}+  _                        -> pushScreen (esNew err) ui++-- | Toggle ignoring balance assertions and assert rules (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).+-- But if --pivot or --obfuscate is active, a full journal reload is done instead+-- (because they change account names, so the checks can't be done on the in-memory journal).+-- In that case, this operation could be slower and could reveal other data changes (not just check failures). uiToggleBalanceAssertions :: Day -> UIState -> EventM Name UIState ()-uiToggleBalanceAssertions d ui@UIState{aopts=UIOpts{uoCliOpts=copts@CliOpts{inputopts_=InputOpts{pivot_=pivotval}}}} =+uiToggleBalanceAssertions d ui@UIState{aopts=UIOpts{uoCliOpts=CliOpts{inputopts_=InputOpts{pivot_=pivotval, anon_=obfuscated}}}} =   let ui' = toggleIgnoreBalanceAssertions ui-  in case (ui'^.ignore_assertions, null pivotval) of+  in case (ui'^.ignore_assertions, null pivotval && not obfuscated) 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+    (False, True)  -> put' $ uiCheckAssertions d ui'          -- account names unchanged, can check in memory+    (False, False) -> uiReload (ui'^.cliOpts) d ui' >>= put'  -- pivoted or obfuscated journal, must reload (with checks now enabled) to check it
− Hledger/UI/IncomestatementScreen.hs
@@ -1,29 +0,0 @@--- 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/Main.hs view
@@ -21,45 +21,53 @@ {-# 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 Control.Monad.IO.Class (liftIO) 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 Data.Time.Clock (getCurrentTime)+import Graphics.Vty (Event (EvKey), Key (KChar), Modifier (MCtrl), Mode (Focus, Mouse), Vty (outputIface), Output (setMode)) import Graphics.Vty.CrossPlatform (mkVty)+#ifndef mingw32_HOST_OS+import Control.Exception (throwIO)+import Graphics.Vty.Platform.Unix (mkVtyWithSettings)+import Graphics.Vty.Platform.Unix.Settings (UnixSettings(..), VtyUnixConfigurationError(..))+import System.Environment (lookupEnv)+import System.IO.Error (catchIOError)+import System.Posix.IO (OpenMode(ReadOnly), OpenFileFlags(..), defaultFileFlags, openFd, stdOutput)+import System.Posix.Terminal (getTerminalName, queryTerminal)+import System.Posix.Types (Fd)+#endif 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 import Brick.BChan qualified as BC  import Hledger import Hledger.Cli hiding (progname,prognameandversion)+import Hledger.Cli.Commands.Quickref (showQuickref) 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.UIState (uiState, uiDisplayJournal)+import Hledger.UI.UIUtils (clickFocusStep, dbguiEv, journalIsFromStdin, showScreenStack, showScreenSelection, uiInstallWarningCollector, uiTakeWarnings) 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@@ -96,7 +104,7 @@   dbg1IO "args" progArgs   dbg1IO "debugLevel" debugLevel -  opts1@UIOpts{uoCliOpts=copts@CliOpts{inputopts_=iopts,rawopts_=rawopts}} <- getHledgerUIOpts+  opts1@UIOpts{uoCliOpts=copts@CliOpts{rawopts_=rawopts}} <- getHledgerUIOpts   -- when (debug_ $ cliopts_ opts) $ printf "%s\n" prognameandversion >> printf "opts: %s\n" (show opts)    usecolor <- useColorOnStdout@@ -107,23 +115,75 @@   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}}+  let copts' = uiAdjustOpts opts copts +  -- always load the journal with full lot detail retained and amounts as recorded; the UI+  -- collapses lots and converts to cost for display (toggled by the L and B keys), so the+  -- loaded journal stays available without re-reading files.+  let loadcopts = uiLoadOpts copts'+   case True of+    _ | boolopt "quickref" rawopts -> showQuickref     _ | boolopt "help"    rawopts -> runPager $ showModeUsage uimode ++ "\n"-    _ | boolopt "tldr"    rawopts -> runTldrForPage "hledger-ui"+    _ | boolopt "examples" rawopts -> runTldrForPage "hledger-ui"     _ | boolopt "info"    rawopts -> runInfoForTopic "hledger-ui" Nothing     _ | boolopt "man"     rawopts -> runManForTopic  "hledger-ui" Nothing+    _ | boolopt "webman"  rawopts -> void $ openBrowserOn $ webManualUrl "hledger-ui" Nothing     _ | boolopt "version" rawopts -> putStrLn prognameandversion     -- _ | boolopt "binary-filename" rawopts -> putStrLn (binaryfilename progname)-    _                                         -> withJournal copts' (runBrickUi opts)+    _                                         -> do+        -- From here on, warnings (from loading or later reloading the journal) should be+        -- collected for display in the UI, not printed to stderr where they would be+        -- hidden or would disrupt the terminal display.+        uiInstallWarningCollector+        withJournal loadcopts (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+-- | Make an action like @mkVty mempty@, but reading keyboard input from the+-- controlling terminal's device rather than from stdin. Used when the journal data+-- was read from stdin, which leaves that handle consumed and closed.+-- The terminal is opened once, here; the returned action can be run repeatedly+-- (eg when resuming after a suspend). Unix only; on Windows this is just mkVty.+ttyVtyMaker :: IO (IO Vty)+#ifdef mingw32_HOST_OS+ttyVtyMaker = return $ mkVty mempty+#else+ttyVtyMaker = do+  term  <- lookupEnv "TERM" >>= maybe (throwIO MissingTermEnvVar) return+  ttyfd <- openTerminal+  return $ mkVtyWithSettings mempty UnixSettings+    { settingVmin      = 1+    , settingVtime     = 100+    , settingInputFd   = ttyfd+    , settingOutputFd  = stdOutput+    , settingTermName  = term+    }++-- | Open the controlling terminal for reading, without making it our controlling+-- terminal if we have none, and not inherited by child processes.+-- Prefer the terminal's real device path (eg /dev/ttys003) over /dev/tty:+-- macOS's kqueue can't wait on the latter, so vty's input thread would block+-- in read() and shutdown would hang until the next key press.+-- Fall back to /dev/tty if the device can't be opened (eg after su).+openTerminal :: IO Fd+openTerminal = do+  isterm <- queryTerminal stdOutput+  mdev   <- if isterm then Just <$> getTerminalName stdOutput else return Nothing+  let open p = openFd p ReadOnly defaultFileFlags{noctty = True, cloexec = True}+  case mdev of+    Nothing  -> open "/dev/tty"+    Just dev -> open dev `catchIOError` \_ -> open "/dev/tty"+#endif++-- | Build hledger-ui's startup state: normalise the options, choose the initial+-- screen, and set up the stack of previous screens as if the user had navigated+-- down to it from the menu. Uses the startup report date (@copts^.rsDay@), so it is+-- deterministic and reusable outside the brick app (eg from tests). Keep synced with msNew.+uiInitialState :: UIOpts -> Journal -> UIState+uiInitialState uopts0@UIOpts{uoCliOpts=copts@CliOpts{reportspec_=rspec@ReportSpec{_rsReportOpts=ropts}}} j =+  uiState uopts j prevscrs currscr+  where     today = copts^.rsDay      -- hledger-ui's query handling is currently in flux, mixing old and new approaches.@@ -170,7 +230,7 @@             _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)+               no_elide_ = accountlistmode_ ropts == ALTree,   -- 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                }@@ -184,19 +244,26 @@         filteredQuery q = simplifyQuery $ And [queryFromFlags ropts, filtered q]           where filtered = filterQuery (\x -> not $ queryIsDepth x || queryIsDate x) +    -- The journal collapsed for display per the current lots toggle; the initial screens+    -- are built from it, while uiState keeps the uncollapsed journal for the L toggle.+    jdisplay = uiDisplayJournal uopts j+     -- 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+    -- The screen-selecting flag given last wins, so eg a config file's choice+    -- can be overridden on the command line.+    mscreenflag = choiceopt (\n -> if n `elem` ["cash","bs","is","all","register"] then Just n else Nothing) rawopts     (prevscrs, currscr) =       dbg1With (showScreenStack "initial" showScreenSelection . uncurry2 (uiState defuiopts nulljournal)) $-      if+      case mscreenflag of         -- 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)+        Just "cash" -> ([msSetSelectedScreen csItemIndex menuscr], csacctsscr)+        Just "bs"   -> ([msSetSelectedScreen bsItemIndex menuscr], bsacctsscr)+        Just "is"   -> ([msSetSelectedScreen isItemIndex menuscr], isacctsscr)+        Just "all"  -> ([msSetSelectedScreen asItemIndex menuscr], allacctsscr)          -- A register screen is specified with --register=ACCT. The initial screen stack will be:         --@@ -204,11 +271,11 @@         --    ACCTSSCR (the accounts screen containing ACCT), with ACCT selected         --     register screen for ACCT         ---        | Just apat <- uoRegister uopts ->+        Just "register" | Just apat <- uoRegister uopts ->           let             -- the account being requested             acct = fromMaybe (error' $ "--register "++apat++" did not match any account")  -- PARTIAL:-              . firstMatch $ journalAccountNamesDeclaredOrImplied j+              . firstMatch $ journalAccountNamesDeclaredOrImplied jdisplay               where                 firstMatch = case toRegexCI $ T.pack apat of                     Right re -> find (regexMatchText re)@@ -217,16 +284,20 @@             -- the register screen for acct             regscr =                rsSetAccount acct False $-              rsNew uopts today j acct forceinclusive+              rsNew uopts today jdisplay acct forceinclusive                 where-                  forceinclusive = case getDepth ui of+                  -- Take the depth from uopts, not `getDepth ui`: ui depends on regscr+                  -- (this binding), so referencing ui here ties a knot that StrictData's+                  -- strict UIState fields turn into a <<loop>> at startup (#1825).+                  forceinclusive = case dsFlatDepth (depth_ regropts) of                                     Just de -> accountNameLevel acct >= de                                     Nothing -> False+                    where regropts = _rsReportOpts $ reportspec_ $ uoCliOpts uopts              -- The accounts screen containing acct.             -- Keep these selidx values synced with the menu items in msNew.             (acctsscr, selidx) =-              case journalAccountType j acct of+              case journalAccountType jdisplay acct of                 Just t | isBalanceSheetAccountType t    -> (bsacctsscr, 1)                 Just t | isIncomeStatementAccountType t -> (isacctsscr, 2)                 _                                       -> (allacctsscr,0)@@ -237,31 +308,49 @@           in ([acctsscr, menuscr'], regscr)          -- Otherwise, start on the menu screen.-        | otherwise -> ([], menuscr)+        _ -> ([], 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+          allacctsscr = asNew AllAccounts             uopts today jdisplay Nothing+          csacctsscr  = asNew CashAccounts            uopts today jdisplay Nothing+          bsacctsscr  = asNew BalancesheetAccounts    uopts today jdisplay Nothing+          isacctsscr  = asNew IncomestatementAccounts uopts today jdisplay Nothing -    ui = uiState uopts j prevscrs currscr-    app = brickApp (uoTheme uopts) +runBrickUi :: UIOpts -> Journal -> IO ()+runBrickUi uopts0 j =+  do+  -- show any warnings collected while loading the journal (until the first keypress)+  startupwarnings <- uiTakeWarnings++  let+    ui  = (uiInitialState uopts0 j){aWarnings=startupwarnings}+    app = brickApp (uoTheme uopts0)+   -- print (length (show ui)) >> exitSuccess  -- show any debug output to this point & quit -  let -    -- helper: make a Vty terminal controller with mouse support enabled+  let+  -- how to make a Vty terminal controller: the usual way, or when the journal+  -- came from stdin, reading keys from the terminal device instead+  mkvty <- if journalIsFromStdin j then ttyVtyMaker else return (mkVty mempty)++  let+    -- helper: make a Vty terminal controller with mouse support and focus reporting enabled     makevty = do-      v <- mkVty mempty+      v <- mkvty       setMode (outputIface v) Mouse True+      setMode (outputIface v) Focus True       return v -  if not (uoWatch uopts)+  if not (uoWatch uopts0)   then do+#if MIN_VERSION_brick(3,1,0)+    void $ customMain (Just makevty) Nothing app ui+#else     vty <- makevty     void $ customMain vty makevty Nothing app ui+#endif    else do     -- a channel for sending misc. events to the app@@ -293,9 +382,9 @@       -- 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+        fs <- mapM canonicalizePath $ filter (/= "-") $ journalAllFilePaths j+        let directories = nubSort $ map takeDirectory fs+        dbg1IO "files" fs         dbg1IO "directories to watch" directories          forM_ directories $ \d -> watchDir@@ -303,8 +392,8 @@           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+            Added f _ IsFile -> f `elem` fs -- for editors which write the whole file from scratch on saves+            Modified f _ IsFile -> f `elem` fs -- 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@@ -318,8 +407,12 @@             )          -- and start the app. Must be inside the withManager block. (XXX makevty too ?)+#if MIN_VERSION_brick(3,1,0)+        void $ customMain (Just makevty) (Just eventChan) app ui+#else         vty <- makevty         void $ customMain vty makevty (Just eventChan) app ui+#endif  brickApp :: Maybe String -> App UIState AppEvent Name brickApp mtheme = App {@@ -333,25 +426,55 @@ 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+  -- dismiss any displayed warnings on the next key press (which is otherwise handled as usual)+  case ev of+    VtyEvent (EvKey _ _) -> modify $ \u -> if null (aWarnings u) then u else u{aWarnings=[]}+    _ -> return ()+  -- track focus, to recognise and ignore a click that just brings the window forward+  now <- liftIO getCurrentTime+  ui0 <- get+  let (clickfocus, ignore) = clickFocusStep now ev (aClickFocus ui0)+      ui = ui0{aClickFocus=clickfocus}+  put ui+  case (ev, aScreen ui) of+    -- no redraw, to keep the time between a focus event and its click short+    _ | ignore -> continueWithoutRedraw+    -- C-c: quit, from any screen or mode (vty's raw mode delivers it as a key, not SIGINT)+    (VtyEvent (EvKey (KChar 'c') [MCtrl]), _) -> halt+    (_, MS sst) -> msHandle sst ev+    (_, AS sst) -> asHandle sst ev+    (_, RS sst) -> rsHandle sst ev+    (_, TS sst) -> tsHandle sst ev+    (_, ES sst) -> esHandle sst 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+uiDraw ui = case reverse $ aWarnings ui of+    []           -> screenlayers+    latest:older -> warningOverlay latest (length older) : screenlayers+  where+    screenlayers =+      case aScreen ui of+        MS sst -> msDraw sst ui+        AS sst -> asDraw sst ui+        RS sst -> rsDraw sst ui+        TS sst -> tsDraw sst ui+        ES sst -> esDraw sst ui++-- | An overlay layer showing the given (most recent) warning message,+-- and how many more there are, on the screen's bottom line until the next keypress.+warningOverlay :: String -> Int -> Widget Name+warningOverlay msg nolder =+  Widget Greedy Greedy $ do+    c <- getContext+    render $+      translateLayer (Location (0, c^.availHeightL - 1)) $+      withAttr (attrName "warning") $ str $+      " Warning: " ++ takeWhile (/='\n') msg ++ morestr ++ " "+  where+    morestr = if nolder > 0 then " (and " ++ show nolder ++ " more)" else ""++#if !MIN_VERSION_brick(3,0,0)+-- | brick 3.0 renamed translateBy to translateLayer.+translateLayer :: Location -> Widget n -> Widget n+translateLayer = translateBy+#endif
Hledger/UI/MenuScreen.hs view
@@ -26,6 +26,7 @@ import System.Console.ANSI import System.FilePath (takeFileName) +import Hledger.Utils.I18n (Translations, tr) import Hledger import Hledger.Cli hiding (mode, progname, prognameandversion) import Hledger.UI.UIOptions@@ -39,10 +40,9 @@ import Control.Arrow ((>>>))  -msDraw :: UIState -> [Widget Name]-msDraw UIState{aopts=_uopts@UIOpts{uoCliOpts=copts@CliOpts{reportspec_=_rspec@ReportSpec{_rsReportOpts=ropts}}}+msDraw :: MenuScreenState -> UIState -> [Widget Name]+msDraw sst UIState{aopts=_uopts@UIOpts{uoCliOpts=copts@CliOpts{reportspec_=_rspec@ReportSpec{_rsReportOpts=ropts}}}               ,ajournal=j-              ,aScreen=MS sst               ,aMode=mode               } = dbgui "msDraw" $     case mode of@@ -50,16 +50,16 @@       _                 -> [maincontent]   where     maincontent = Widget Greedy Greedy $ do-      render $ defaultLayout toplabel bottomlabel $ renderList msDrawItem True (sst ^. mssList)+      render $ defaultLayout toplabel bottomlabel $ renderList (msDrawItem (translations_ ropts)) True (sst ^. mssList)       where         toplabel =-              withAttr (attrName "border" <> attrName "filename") files+              withAttr (attrName "border" <> attrName "filename") fs           <+> 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+            fs = case journalFilePaths j of                            [] -> str ""                            f:_ -> str $ takeFileName f                            -- [f,_:[]] -> (withAttr ("border" <> "bold") $ str $ takeFileName f) <+> str " (& 1 included file)"@@ -87,18 +87,17 @@               ,("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{..} =+msDrawItem :: Translations -> Bool -> MenuScreenItem -> Widget Name+msDrawItem trs _selected MenuScreenItem{..} =   Widget Greedy Fixed $ do-    render $ txt msItemScreenName+    render $ txt $ tr trs msItemScreenName  -- XXX clean up like asHandle-msHandle :: BrickEvent Name AppEvent -> EventM Name UIState ()-msHandle ev = do+msHandle :: MenuScreenState -> BrickEvent Name AppEvent -> EventM Name UIState ()+msHandle sst ev = do   ui0 <- get'   dbguiEv "msHandle"   case ui0 of@@ -106,7 +105,6 @@        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@@ -122,7 +120,7 @@         Minibuffer _ ed ->           case ev of             VtyEvent (EvKey KEsc   []) -> put' $ closeMinibuffer ui-            VtyEvent (EvKey KEnter []) -> put' $ regenerateScreens j d $+            VtyEvent (EvKey KEnter []) -> put' $ regenerateScreens d $                 case setFilter s $ closeMinibuffer ui of                   Left bad -> showMinibuffer "Cannot compile regular expression" (Just bad) ui                   Right ui' -> ui'@@ -152,7 +150,7 @@             -- 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+              put' $ regenerateScreens d $ setReportPeriod (DayPeriod d) ui               where                 p = reportPeriod ui             e | e `elem` [VtyEvent (EvKey (KChar 'g') []), AppEvent FileChange] -> uiReload copts d ui >>= put'@@ -161,50 +159,50 @@             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+--             VtyEvent (EvKey (KChar 'B') []) -> put' $ regenerateScreens d $ toggleConversionOp ui+--             VtyEvent (EvKey (KChar 'V') []) -> put' $ regenerateScreens d $ toggleValue ui+--             VtyEvent (EvKey (KChar '0') []) -> put' $ regenerateScreens d $ setDepth (Just 0) ui+--             VtyEvent (EvKey (KChar '1') []) -> put' $ regenerateScreens d $ setDepth (Just 1) ui+--             VtyEvent (EvKey (KChar '2') []) -> put' $ regenerateScreens d $ setDepth (Just 2) ui+--             VtyEvent (EvKey (KChar '3') []) -> put' $ regenerateScreens d $ setDepth (Just 3) ui+--             VtyEvent (EvKey (KChar '4') []) -> put' $ regenerateScreens d $ setDepth (Just 4) ui+--             VtyEvent (EvKey (KChar '5') []) -> put' $ regenerateScreens d $ setDepth (Just 5) ui+--             VtyEvent (EvKey (KChar '6') []) -> put' $ regenerateScreens d $ setDepth (Just 6) ui+--             VtyEvent (EvKey (KChar '7') []) -> put' $ regenerateScreens d $ setDepth (Just 7) ui+--             VtyEvent (EvKey (KChar '8') []) -> put' $ regenerateScreens d $ setDepth (Just 8) ui+--             VtyEvent (EvKey (KChar '9') []) -> put' $ regenerateScreens d $ setDepth (Just 9) ui+--             VtyEvent (EvKey (KChar '-') []) -> put' $ regenerateScreens d $ decDepth ui+--             VtyEvent (EvKey (KChar '_') []) -> put' $ regenerateScreens d $ decDepth ui+--             VtyEvent (EvKey (KChar c)   []) | c `elem` ['+','='] -> put' $ regenerateScreens d $ incDepth ui+--             VtyEvent (EvKey (KChar 'T') []) -> put' $ regenerateScreens 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)+--             VtyEvent (EvKey (KChar 't') []) -> modify' (regenerateScreens d . toggleTree) >> msCenterAndContinue+--             VtyEvent (EvKey (KChar c) []) | c `elem` ['z','Z'] -> modify' (regenerateScreens d . toggleEmpty) >> msCenterAndContinue+--             VtyEvent (EvKey (KChar 'R') []) -> modify' (regenerateScreens d . toggleReal) >> msCenterAndContinue+--             VtyEvent (EvKey (KChar 'U') []) -> modify' (regenerateScreens d . toggleUnmarked) >> msCenterAndContinue+--             VtyEvent (EvKey (KChar 'P') []) -> modify' (regenerateScreens d . togglePending) >> msCenterAndContinue+--             VtyEvent (EvKey (KChar 'C') []) -> modify' (regenerateScreens d . toggleCleared) >> msCenterAndContinue+--             VtyEvent (EvKey (KChar 'F') []) -> modify' (regenerateScreens d . toggleForecast d)+            -- VtyEvent (EvKey (KChar 'H') []) -> modify' (toggleHistorical >>> regenerateScreens 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 (KDown)     [MShift]) -> modify' (shrinkReportPeriod d             >>> regenerateScreens d)+            VtyEvent (EvKey (KUp)       [MShift]) -> modify' (growReportPeriod d               >>> regenerateScreens d)+            VtyEvent (EvKey (KRight)    [MShift]) -> modify' (nextReportPeriod journalspan     >>> regenerateScreens d)+            VtyEvent (EvKey (KLeft)     [MShift]) -> modify' (previousReportPeriod journalspan >>> regenerateScreens d)+            VtyEvent (EvKey (KChar 'T') [])       -> modify' (setReportPeriod (DayPeriod d)    >>> regenerateScreens 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 '/') []) -> put' $ regenerateScreens d $ showMinibuffer "filter" Nothing ui+            VtyEvent (EvKey k           []) | k `elem` [KBS, KDel] -> (put' $ regenerateScreens d $ resetFilter ui) -            VtyEvent (EvKey (KChar 'l') [MCtrl]) -> scrollSelectionToMiddle (_mssList sst) >> redraw+            VtyEvent (EvKey (KChar 'l') [MCtrl]) -> scrollSelectionToMiddle (msListSize $ _mssList sst) (_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+              msEnterScreen d (fromMaybe AllAccounts mselscr) ui              -- MouseDown is sometimes duplicated, https://github.com/jtdaugherty/brick/issues/347             -- just use it to move the selection@@ -224,9 +222,8 @@                 -- 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+            -- when selection is at the last item, do nothing+            VtyEvent e | e `elem` moveDownEvents, isBlankElement mnextelement -> return ()               where mnextelement = listSelectedElement $ listMoveDown (_mssList sst)              -- mouse scroll wheel scrolls the viewport up or down to its maximum extent,@@ -242,7 +239,7 @@               if isBlankElement $ listSelectedElement l               then do                 let l' = listMoveTo lastnonblankidx l-                scrollSelectionToMiddle l'+                scrollSelectionToMiddle (msListSize l') l'                 put' ui{aScreen=MS sst{_mssList=l'}}               else                 put' ui{aScreen=MS sst{_mssList=l}}@@ -256,17 +253,11 @@             MouseUp{}   -> return ()             AppEvent _  -> return () -    _ -> dbguiEv "msHandle" >> errorWrongScreenType "msHandle" -msEnterScreen :: Day -> ScreenName -> UIState -> EventM Name UIState ()+msEnterScreen :: Day -> AccountsScreenKind -> 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+  let scr = asNew scrname uopts d j Nothing  -- scrname is also the accounts-like screen kind   put' $ pushScreen scr ui  -- | Set the selected list item on the menu screen. Has no effect on other screens.
Hledger/UI/RegisterScreen.hs view
@@ -45,9 +45,8 @@ 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{..}+rsDraw :: RegisterScreenState -> UIState -> [Widget Name]+rsDraw RSS{..} UIState{aopts=uopts@UIOpts{uoCliOpts=copts@CliOpts{reportspec_=rspec}}               ,aMode=mode               } = dbgui "rsDraw" $   case mode of@@ -104,7 +103,7 @@         -- inclusive = tree_ ropts || rsForceInclusive          toplabel =-              withAttr (attrName "border" <> attrName "bold") (str $ T.unpack $ replaceHiddenAccountsNameWith "All" _rssAccount)+              withAttr (attrName "border" <> attrName "bold") (str $ T.unpack $ replaceHiddenAccountsNameWith "All" $ uiDisplayAccount uopts _rssAccount) --           <+> withAttr ("border" <> "query") (str $ if inclusive then "" else " exclusive")           <+> togglefilters           <+> str " transactions"@@ -150,13 +149,13 @@                ,("H", renderToggle (not ishistorical) "historical" "period")               ,("F", renderToggle1 (isJust . forecast_ . inputopts_ $ copts) "forecast")+              ,("L", renderToggle1 (boolopt "lots" $ rawopts_ copts) "lots")               -- ,("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{..} =@@ -184,14 +183,13 @@         | otherwise = id  -- XXX clean up like asHandle-rsHandle :: BrickEvent Name AppEvent -> EventM Name UIState ()-rsHandle ev = do+rsHandle :: RegisterScreenState -> BrickEvent Name AppEvent -> EventM Name UIState ()+rsHandle sst@RSS{..} ev = do   ui0 <- get'   dbguiEv "rsHandle"   case ui0 of     ui@UIState{-      aScreen=RS sst@RSS{..}-      ,aopts=UIOpts{uoCliOpts=copts}+      aopts=UIOpts{uoCliOpts=copts}       ,ajournal=j       ,aMode=mode       } -> do@@ -211,12 +209,12 @@         Minibuffer _ ed ->           case ev of             VtyEvent (EvKey KEsc   []) -> modify' closeMinibuffer-            VtyEvent (EvKey KEnter []) -> put' $ regenerateScreens j d $+            VtyEvent (EvKey KEnter []) -> put' $ regenerateScreens 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 '/') []) -> put' $ regenerateScreens d $ showMinibuffer ui             VtyEvent (EvKey (KChar 'l') [MCtrl]) -> redraw             VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui             VtyEvent e -> do@@ -241,7 +239,7 @@              -- AppEvents arrive in --watch mode, see AccountsScreen             AppEvent (DateChange old _) | isStandardPeriod p && p `periodContainsDate` old ->-              put' $ regenerateScreens j d $ setReportPeriod (DayPeriod d) ui+              put' $ regenerateScreens d $ setReportPeriod (DayPeriod d) ui               where                 p = reportPeriod ui @@ -250,7 +248,7 @@             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 'T') []) -> put' $ regenerateScreens 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@@ -259,16 +257,17 @@                               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 'B') []) -> rsCenterSelection (regenerateScreens d $ toggleConversionOp ui) >>= put'+            VtyEvent (EvKey (KChar 'V') []) -> rsCenterSelection (regenerateScreens d $ toggleValue ui) >>= put'+            VtyEvent (EvKey (KChar 'H') []) -> rsCenterSelection (regenerateScreens d $ toggleHistorical ui) >>= put'+            VtyEvent (EvKey (KChar 't') []) -> rsCenterSelection (regenerateScreens d $ toggleTree ui) >>= put'+            VtyEvent (EvKey (KChar c) []) | c `elem` ['z','Z'] -> rsCenterSelection (regenerateScreens d $ toggleEmpty ui) >>= put'+            VtyEvent (EvKey (KChar 'R') []) -> rsCenterSelection (regenerateScreens d $ toggleReal ui) >>= put'+            VtyEvent (EvKey (KChar 'U') []) -> rsCenterSelection (regenerateScreens d $ toggleUnmarked ui) >>= put'+            VtyEvent (EvKey (KChar 'P') []) -> rsCenterSelection (regenerateScreens d $ togglePending ui) >>= put'+            VtyEvent (EvKey (KChar 'C') []) -> rsCenterSelection (regenerateScreens d $ toggleCleared ui) >>= put'+            VtyEvent (EvKey (KChar 'F') []) -> rsCenterSelection (regenerateScreens d $ toggleForecast d ui) >>= put'+            VtyEvent (EvKey (KChar 'L') []) -> rsCenterSelection (regenerateScreens d $ toggleLots ui) >>= put'             VtyEvent (EvKey (KChar 'J') []) -> do               let l' = listMoveBy 10 _rssList               let l'' = if isBlankElement (listSelectedElement l')@@ -279,13 +278,13 @@             VtyEvent (EvKey (KChar 'K') []) -> do               let l' = listMoveBy (-10) _rssList               put' ui{aScreen=RS sst{_rssList=l'}}-            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 '/') []) -> put' $ regenerateScreens d $ showMinibuffer "filter" Nothing ui+            VtyEvent (EvKey (KDown)     [MShift]) -> put' $ regenerateScreens d $ shrinkReportPeriod d ui+            VtyEvent (EvKey (KUp)       [MShift]) -> put' $ regenerateScreens d $ growReportPeriod d ui+            VtyEvent (EvKey (KRight)    [MShift]) -> put' $ regenerateScreens d $ nextReportPeriod journalspan ui+            VtyEvent (EvKey (KLeft)     [MShift]) -> put' $ regenerateScreens d $ previousReportPeriod journalspan ui+            VtyEvent (EvKey k           []) | k `elem` [KBS, KDel] -> (put' $ regenerateScreens d $ resetFilter ui)+            VtyEvent (EvKey (KChar 'l') [MCtrl]) -> scrollSelectionToMiddle (rsListSize _rssList) _rssList >> redraw             VtyEvent (EvKey (KChar 'z') [MCtrl]) -> suspend ui              -- exit screen on LEFT@@ -295,7 +294,7 @@              -- enter transaction screen on RIGHT             VtyEvent e | e `elem` moveRightEvents ->-              case mtxns of Nothing -> return (); Just (nts, nt) -> rsEnterTransactionScreen _rssAccount nts nt ui+              case mtxns of Nothing -> return (); Just (nts, nt) -> rsEnterTransactionScreen _rssAccount _rssForceInclusive 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@@ -304,12 +303,11 @@               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+              case mtxns of Nothing -> return (); Just (nts, nt) -> rsEnterTransactionScreen _rssAccount _rssForceInclusive 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+            -- when selection is at the last item, do nothing+            VtyEvent e | e `elem` moveDownEvents, isBlankElement mnextelement -> return ()               where mnextelement = listSelectedElement $ listMoveDown _rssList              -- mouse scroll wheel scrolls the viewport up or down to its maximum extent,@@ -325,7 +323,7 @@               if isBlankElement $ listSelectedElement l               then do                 let l' = listMoveTo lastnonblankidx l-                scrollSelectionToMiddle l'+                scrollSelectionToMiddle (rsListSize l') l'                 put' ui{aScreen=RS sst{_rssList=l'}}               else                 put' ui{aScreen=RS sst{_rssList=l}}@@ -340,7 +338,6 @@             MouseUp{}         -> return ()             AppEvent _        -> return () -    _ -> errorWrongScreenType "rsHandle"  isBlankElement mel = ((rsItemDate . snd) <$> mel) == Just "" @@ -355,11 +352,11 @@ -- No effect on other screens. rsCenterSelection :: UIState -> EventM Name UIState UIState rsCenterSelection ui@UIState{aScreen=RS sst} = do-  scrollSelectionToMiddle $ _rssList sst+  scrollSelectionToMiddle (rsListSize $ _rssList sst) (_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+rsEnterTransactionScreen :: AccountName -> Bool -> [NumberedTransaction] -> NumberedTransaction -> UIState -> EventM Name UIState ()+rsEnterTransactionScreen acct forceinclusive nts nt ui = do   dbguiEv "rsEnterTransactionScreen"-  put' $ pushScreen (tsNew acct nts nt) ui+  put' $ pushScreen (tsNew acct forceinclusive nts nt) ui
Hledger/UI/Theme.hs view
@@ -75,6 +75,7 @@     ,(attrName "border" <> attrName "query"                             , active)     ,(attrName "border" <> attrName "selected"                          , active)     ,(attrName "error"                                         , fg red)+    ,(attrName "warning"                                       , fg brightYellow & bold)  -- like the CLI's warning colour (ansiFormatWarning)     ,(attrName "help"                                          , white `on` black & dim)     ,(attrName "help" <> attrName "heading"                             , fg yellow)     ,(attrName "help" <> attrName "key"                                 , active)@@ -104,6 +105,7 @@     , (attrName "border" <> attrName "query"                                               , active)     , (attrName "border" <> attrName "selected"                                            , active)     , (attrName "error"                                                                    , fg red)+    , (attrName "warning"                                                                  , fg brightYellow & bold)  -- like the CLI's warning colour (ansiFormatWarning)     , (attrName "help"                                                                     , currentAttr & bold)     , (attrName "help" <> attrName "heading"                                               , fg blue)     , (attrName "help" <> attrName "key"                                                   , active)
Hledger/UI/TransactionScreen.hs view
@@ -14,11 +14,12 @@  import Brick import Brick.Widgets.Edit (editorText, renderEditor)-import Brick.Widgets.List (listMoveTo)+import Brick.Widgets.List (listElements) import Control.Monad.IO.Class (liftIO) import Data.List import Data.Maybe import Data.Text qualified as T+import Data.Vector qualified as V import Graphics.Vty (Event(..),Key(..),Modifier(..), Button (BLeft)) import System.Exit (ExitCode (..)) @@ -30,16 +31,15 @@ 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)+import Hledger.UI.ErrorScreen (uiReload, uiReloadIfFileChanged, uiToggleBalanceAssertions) -tsDraw :: UIState -> [Widget Name]-tsDraw UIState{aopts=UIOpts{uoCliOpts=copts@CliOpts{reportspec_=rspec@ReportSpec{_rsReportOpts=ropts}}}+tsDraw :: TransactionScreenState -> UIState -> [Widget Name]+tsDraw TSS{_tssTransaction=(i,t')+          ,_tssTransactions=nts+          ,_tssAccount=acct+          }+       UIState{aopts=uopts@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@@ -48,8 +48,13 @@   where     maincontent = Widget Greedy Greedy $ render $ defaultLayout toplabel bottomlabel txneditor       where+        -- The stored transaction, coming from accountTransactionsReport, may have had+        -- amounts excluded by a cur:/amt: query, or valued. This screen should always+        -- show the whole journal entry as written (with any valuation applied by showTxn+        -- below), so look up the original transaction in the journal by its index.+        torig = fromMaybe t' $ journalTransactionAt j (tindex t')         -- as with print, show amounts with all of their decimal places-        t = transactionMapPostingAmounts mixedAmountSetFullPrecision t'+        t = transactionMapPostingAmounts mixedAmountSetFullPrecision torig          -- XXX would like to shrink the editor to the size of the entry,         -- so handler can more easily detect clicks below it@@ -68,7 +73,7 @@           <+> str (" of "++show (length nts))           <+> togglefilters           <+> borderQueryStr (unwords . map (quoteIfNeeded . T.unpack) $ querystring_ ropts)-          <+> str (" in "++T.unpack (replaceHiddenAccountsNameWith "All" acct)++")")+          <+> str (" in "++T.unpack (replaceHiddenAccountsNameWith "All" $ uiDisplayAccount uopts acct)++")")           <+> (if ignore_assertions_ . balancingopts_ $ inputopts_ copts then withAttr (attrName "border" <> attrName "query") (str " ignoring balance assertions") else str "")           where             togglefilters =@@ -96,7 +101,6 @@               -- ,("q", "quit")               ] -tsDraw _ = errorWrongScreenType "tsDraw"  -- PARTIAL:  -- Render a transaction suitably for the transaction screen. showTxn :: ReportOpts -> ReportSpec -> Journal -> Transaction -> T.Text@@ -112,12 +116,11 @@       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+tsHandle :: TransactionScreenState -> BrickEvent Name AppEvent -> EventM Name UIState ()+tsHandle TSS{_tssTransaction=(i,t), _tssTransactions=nts} ev = do   ui0 <- get'   case ui0 of-    ui@UIState{aScreen=TS TSS{_tssTransaction=(i,t), _tssTransactions=nts}-              ,aopts=UIOpts{uoCliOpts=copts}+    ui@UIState{aopts=UIOpts{uoCliOpts=copts}               ,ajournal=j               ,aMode=mode               } ->@@ -158,7 +161,7 @@               tsReloadIfFileChanged copts d j ui              AppEvent (DateChange old _) | isStandardPeriod p && p `periodContainsDate` old ->-              put' $ regenerateScreens j d $ setReportPeriod (DayPeriod d) ui+              put' $ regenerateScreens d $ setReportPeriod (DayPeriod d) ui               where                 p = reportPeriod ui @@ -166,11 +169,12 @@              -- 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+            -- EvKey (KChar 'E') [] -> put' $ regenerateScreens d $ stToggleEmpty ui+            -- EvKey (KChar 'C') [] -> put' $ regenerateScreens d $ stToggleCleared ui+            -- EvKey (KChar 'R') [] -> put' $ regenerateScreens d $ stToggleReal ui+            VtyEvent (EvKey (KChar 'B') []) -> put' . regenerateScreens d $ toggleConversionOp ui+            VtyEvent (EvKey (KChar 'V') []) -> put' . regenerateScreens d $ toggleValue ui+            VtyEvent (EvKey (KChar 'L') []) -> put' . regenerateScreens d $ toggleLots ui              VtyEvent e | e `elem` moveUpEvents   -> put' $ tsSelect iprev tprev ui             VtyEvent e | e `elem` moveDownEvents -> put' $ tsSelect inext tnext ui@@ -184,53 +188,12 @@             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+      -- Reload the journal and regenerate the whole screen stack; tsUpdate now refreshes+      -- this transaction screen in place, so no exit/re-enter dance is needed.+      tsReload copts d ui = uiReload copts d ui >>= put'+      tsReloadIfFileChanged copts d j ui = liftIO (uiReloadIfFileChanged copts d j ui) >>= put'   -- | Select a new transaction and update the previous register screen@@ -241,7 +204,10 @@   where ui' = ui{aScreen=TS sst{_tssTransaction=(i,t)}} tsSelect _ _ ui = ui --- | Select the nth item on the register screen.+-- | Select the nth item on the register screen; or if it has no real items+-- (eg its account is a lot subaccount and lot display was just toggled off),+-- clear the selection, so no blank item appears selected. rsSelect :: Integer -> Screen -> Screen-rsSelect i (RS sst@RSS{..}) = RS sst{_rssList=listMoveTo (fromInteger $ i-1) _rssList}+rsSelect i (RS sst@RSS{..}) = RS sst{_rssList=listMoveToIfDisplayItems (fromInteger $ i-1) nonblanks _rssList}+  where nonblanks = V.toList $ V.takeWhile (not . T.null . rsItemDate) $ listElements _rssList rsSelect _ scr = scr
Hledger/UI/UIOptions.hs view
@@ -1,5 +1,4 @@ {-# LANGUAGE CPP #-}-{-# LANGUAGE TemplateHaskell #-}  module Hledger.UI.UIOptions where @@ -8,11 +7,11 @@ 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.Cli.GitInfo (gitInfo) import Hledger.UI.Theme (themes, themeNames)  -- cf Hledger.Cli.Version@@ -29,11 +28,10 @@ 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+  gitInfo #ifdef GHCDEBUG   True #else@@ -47,7 +45,8 @@   uiflags = [-   flagNone ["watch","w"] (setboolopt "watch") "watch for data and date changes and reload automatically"+   flagNone ["watch","w"] (setboolopt "watch") "watch for data and date changes and reload automatically (default)"+  ,flagNone ["no-watch"] (setboolopt "no-watch") "don't watch; reload only with the g key"   ,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"@@ -79,7 +78,8 @@         [flagNone ["future"] (setboolopt "forecast") "old flag, use --forecast instead"         ,flagNone ["menu"] (setboolopt "menu") "old flag, menu screen is now the default"         ]-      ,groupNamed = mkgeneralflagsgroups1 helpflags+      -- hledger-ui has no built-in tests+      ,groupNamed = mkgeneralflagsgroups1 $ filter ((`notElem` [["test"], ["write-lang"]]) . flagNames) helpflags       }   ,modeHelpSuffix=[     -- "Reads your ~/.hledger.journal file, or another specified by $LEDGER_FILE or -f, and starts the full-window TUI."@@ -95,7 +95,7 @@   } deriving (Show)  defuiopts = UIOpts-  { uoWatch    = False+  { uoWatch    = True   , uoTheme    = Nothing   , uoRegister = Nothing   , uoCliOpts  = defcliopts@@ -108,16 +108,30 @@   cliopts <- set balanceaccum accum <$> rawOptsToCliOpts rawopts   return     defuiopts {-       uoWatch    = boolopt "watch" rawopts+       uoWatch    = fromMaybe True $ choiceopt watchflag rawopts       ,uoTheme    = checkTheme <$> maybestringopt "theme" rawopts       ,uoRegister = maybestringopt "register" rawopts       ,uoCliOpts  = cliopts       }   where+    -- watch mode is enabled by default; the rightmost --watch/--no-watch flag wins+    watchflag "watch"    = Just True+    watchflag "no-watch" = Just False+    watchflag _          = Nothing     -- show historical balance by default (unlike hledger)     accum = fromMaybe Historical $ balanceAccumulationOverride rawopts     checkTheme t = let t' = if t == "default" then "light" else t  -- "default" is a deprecated alias for "light"                    in if t' `M.member` themes then t' else usageError $ "invalid theme name: " ++ t++-- | The options to load (or reload) the journal with: lot detail kept, and+-- no conversion to cost basis. The UI collapses lots and converts to cost+-- when it derives the display journal for the current options+-- (uiDisplayJournal), so that the L and B keys can turn either off again.+uiLoadOpts :: CliOpts -> CliOpts+uiLoadOpts copts@CliOpts{rawopts_=ro, reportspec_=rspec@ReportSpec{_rsReportOpts=ropts}} =+  copts{ rawopts_    = setboolopt "lots" ro+       , reportspec_ = rspec{_rsReportOpts = ropts{conversionop_ = Nothing}}+       }  -- XXX some refactoring seems due getHledgerUIOpts :: IO UIOpts
Hledger/UI/UIScreens.hs view
@@ -23,19 +23,17 @@ ,asNew ,asUpdate ,asItemIndex-,csNew-,csUpdate ,csItemIndex-,bsNew-,bsUpdate ,bsItemIndex-,isNew-,isUpdate ,isItemIndex+,accountsScreenRoptsMod+,accountsScreenQuery ,rsNew ,rsUpdate ,tsNew ,tsUpdate+,listMoveToIfDisplayItems+,uiDisplayAccount ) where @@ -48,6 +46,7 @@ import Safe import Data.Vector qualified as V +import Hledger.Utils.I18n (i18n) import Hledger.Cli hiding (mode, progname,prognameandversion) import Hledger.UI.UIOptions import Hledger.UI.UITypes@@ -58,14 +57,13 @@ -- | 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+  -- Force each regenerated screen state to WHNF so the strict selection-index+  -- binding in each updater fires, severing references to the previous generation (#1825).+  MS sst -> MS $! msUpdate sst  -- opts d j ass+  AS sst -> AS $! asUpdate opts d j sst+  RS sst -> RS $! rsUpdate opts d j sst+  TS sst -> TS $! tsUpdate opts d j sst+  ES sst -> ES $  esUpdate sst  -- | Construct an error screen. -- Screen-specific arguments: the error message to show.@@ -90,11 +88,12 @@   MS MSS { _mssList = list MenuList (V.fromList items ) 1, _mssUnused = () }   where     -- keep synced with: indexes below, initial screen stack setup in UI.Main+    -- TRANSLATORS: the menu screen's entries; translated when drawn.     items = [-       MenuScreenItem "Cash accounts" CashScreen-      ,MenuScreenItem "Balance sheet accounts" Balancesheet-      ,MenuScreenItem "Income statement accounts" Incomestatement-      ,MenuScreenItem "All accounts" Accounts+       MenuScreenItem (i18n "Cash accounts") CashAccounts+      ,MenuScreenItem (i18n "Balance sheet accounts") BalancesheetAccounts+      ,MenuScreenItem (i18n "Income statement accounts") IncomestatementAccounts+      ,MenuScreenItem (i18n "All accounts") AllAccounts       ]  -- keep synced with items above.@@ -111,31 +110,52 @@ msUpdate :: MenuScreenState -> MenuScreenState msUpdate = dbgui "msUpdate" -nullass macct = ASS {-   _assSelectedAccount = fromMaybe "" macct+nullass kind macct = ASS {+   _assKind            = kind+  ,_assSelectedAccount = fromMaybe "" macct   ,_assList            = list AccountsList (V.fromList []) 1   } --- | Construct an accounts screen listing the appropriate set of accounts,+-- | Construct an accounts-like screen (all accounts, cash, balance sheet or income+-- statement, selected by the AccountsScreenKind), 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+-- Screen-specific arguments: the kind of screen, and the account to select if any.+asNew :: AccountsScreenKind -> UIOpts -> Day -> Journal -> Maybe AccountName -> Screen+asNew kind uopts d j macct = dbgui "asNew" $ AS $ asUpdate uopts d j $ nullass kind macct --- | Update an accounts screen's state from these options, reporting date, and journal.+-- | Update an accounts-like screen's state from these options, reporting date, and journal.+-- The report is restricted and accumulated according to the screen's kind (_assKind). asUpdate :: UIOpts -> Day -> Journal -> AccountsScreenState -> AccountsScreenState-asUpdate uopts d = dbgui "asUpdate" .-  asUpdateHelper rspec d copts roptsmod extraquery+asUpdate uopts d j ass = dbgui "asUpdate" $+  asUpdateHelper rspec d copts (accountsScreenRoptsMod kind) (accountsScreenQuery kind) j ass   where     UIOpts{uoCliOpts=copts@CliOpts{reportspec_=rspec}} = uopts-    roptsmod       = id-    extraquery     = Any+    kind = _assKind ass +-- | The report-options modifier for an accounts-like screen of the given kind:+-- which balance accumulation it forces, if any.+accountsScreenRoptsMod :: AccountsScreenKind -> ReportOpts -> ReportOpts+accountsScreenRoptsMod kind ropts = case kind of+  AllAccounts             -> ropts+  CashAccounts            -> ropts{balanceaccum_=Historical}  -- always show historical end balances+  BalancesheetAccounts    -> ropts{balanceaccum_=Historical}  -- always show historical end balances+  IncomestatementAccounts -> ropts{balanceaccum_=PerPeriod}   -- always show period changes++-- | The extra query restricting an accounts-like screen of the given kind to its account types.+accountsScreenQuery :: AccountsScreenKind -> Query+accountsScreenQuery kind = case kind of+  AllAccounts             -> Any+  CashAccounts            -> Type [Cash]+  BalancesheetAccounts    -> Type [Asset,Liability,Equity]+  IncomestatementAccounts -> Type [Revenue,Expense]+ -- | 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}+asUpdateHelper rspec0 d copts roptsModify extraquery j ass = dbgui "asUpdateHelper" $+  -- Force the new list, which forces the bang-patterned selidx below, severing the+  -- reference to the previous generation's state (ass) so it can be GC'd (#1825).+  l `seq` ass{_assList=l}   where     ropts = roptsModify $ _rsReportOpts rspec0     rspec =@@ -149,7 +169,8 @@     l = listMoveToIfDisplayItems selidx displayitems $ list AccountsList (V.fromList $ displayitems ++ blankitems) 1       where         -- which account should be selected ?-        selidx = headDef 0 $ catMaybes [+        -- Strict: forced via `l `seq`` above, so the new list holds no thunk over ass (#1825).+        !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.@@ -181,51 +202,6 @@                             ,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,@@ -244,57 +220,13 @@ -- | 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'}+  dbgui "rsUpdate" $+  -- Force the new list, which forces the bang-patterned newselidx below, severing the+  -- reference to the previous generation's list (oldlist) so it can be GC'd (#1825).+  l' `seq` 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-                                                    -- _   -> "<split>"  -- 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'+    -- the rendered register items (one per transaction); shared with the transaction screen+    displayitems = registerScreenDisplayItems uopts d j _rssAccount _rssForceInclusive      -- 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.@@ -320,7 +252,8 @@     l' = listMoveToIfDisplayItems newselidx displayitems l       where         endidx = max 0 $ length displayitems - 1-        newselidx =+        -- Strict: forced via `l' `seq`` above, so the new list holds no thunk over oldlist (#1825).+        !newselidx =           -- case (forcedefaultselection, listSelectedElement _rssList) of           --   (True, _)    -> endidx           --   (_, Nothing) -> endidx@@ -345,25 +278,107 @@                   [(abs $ diffDays (tdate t) prevseld, abs (tindex t - prevselidx), tindex t) | t <- ts])                 ts = map rsItemTransaction displayitems +-- | The account a register-like screen should display: normally the screen's stored+-- account, but when that is a lot subaccount and lot detail is collapsed (so the+-- account doesn't exist in the display journal), its base account, where the+-- collapsed postings now appear. Keep the collapse condition synced with uiDisplayJournal.+uiDisplayAccount :: UIOpts -> AccountName -> AccountName+uiDisplayAccount uopts a+  | boolopt "lots" ro        = a+  | boolopt "ignore-lots" ro = a+  | otherwise                = lotBaseAccount a+  where ro = rawopts_ $ uoCliOpts uopts++-- | The rendered register items (one per transaction) for an account's register,+-- from these options, reporting date, journal, account name, and whether to include+-- subaccount transactions. Shared by the register screen and the transaction screen+-- so they show the same set of transactions.+-- The account is remapped with uiDisplayAccount, so a lot subaccount's register+-- shows its base account's transactions while lot detail is collapsed.+registerScreenDisplayItems :: UIOpts -> Day -> Journal -> AccountName -> Bool -> [RegisterScreenItem]+registerScreenDisplayItems uopts d j acct0 forceinclusive = map displayitem items'+  where+    acct = uiDisplayAccount uopts acct0+    UIOpts{uoCliOpts=copts@CliOpts{reportspec_=rspec@ReportSpec{_rsReportOpts=ropts}}} = uopts+    inclusive = tree_ ropts || forceinclusive+    thisacctq = Acct $ mkregex acct+      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+      }+    rspec' =+      updateReportSpec ropts' rspec{_rsDay=d}+      & either (error' "registerScreenDisplayItems: 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++    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+                                                -- _   -> "<split>"  -- 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'+ -- | 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 =+-- whether that register included subaccounts, the list of showable transactions,+-- the currently shown transaction.+tsNew :: AccountName -> Bool -> [NumberedTransaction] -> NumberedTransaction -> Screen+tsNew acct forceinclusive nts nt =   dbgui "tsNew" $   TS TSS{-     _tssAccount      = acct-    ,_tssTransactions = nts-    ,_tssTransaction  = nt+     _tssAccount        = acct+    ,_tssForceInclusive = forceinclusive+    ,_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"+-- | Update a transaction screen: rebuild its transaction list from the (possibly reloaded)+-- journal, and reselect the same transaction by its journal index, so the screen refreshes+-- in place on reload. If that transaction is gone, fall back to the one at the same position,+-- else the last, else a blank.+tsUpdate :: UIOpts -> Day -> Journal -> TransactionScreenState -> TransactionScreenState+tsUpdate uopts d j tss@TSS{_tssAccount, _tssForceInclusive, _tssTransaction=(oldpos, oldtxn)} =+  dbgui "tsUpdate" $+  length nts `seq` selected `seq`+  tss{_tssTransactions=nts, _tssTransaction=selected}+  where+    displayitems = registerScreenDisplayItems uopts d j _tssAccount _tssForceInclusive+    numberedtxns = zipWith (\i item -> (i, rsItemTransaction item)) [(1::Integer)..] displayitems+    (nts, selected)+      -- the same transaction is still in this account's register: keep it selected+      | Just sel <- find ((== tindex oldtxn) . tindex . snd) numberedtxns = (numberedtxns, sel)+      -- the register is now empty, eg because this screen's account was a lot subaccount+      -- and lot display was just toggled off: if the entry still exists in the journal,+      -- keep showing it (in its current form); otherwise show a blank transaction+      | null numberedtxns = case journalTransactionAt j (tindex oldtxn) of+          Just t  -> ([(1, t)], (1, t))+          Nothing -> ([], (0, nulltransaction))+      -- the transaction is gone but the register is not empty, eg after a file change:+      -- fall back to the transaction at the same position, or the last one+      | otherwise = (numberedtxns, fromMaybe (last numberedtxns) $ (\t -> (oldpos, t)) <$> lookup oldpos numberedtxns)  -- | Set selected index of a list if there are displayitems. -- If there are no displayitems, remove the selected index of the list.
Hledger/UI/UIState.hs view
@@ -14,6 +14,8 @@ ,toggleEmpty ,toggleForecast ,toggleHistorical+,toggleLots+,uiDisplayJournal ,togglePending ,toggleUnmarked ,toggleReal@@ -57,6 +59,7 @@  import Hledger import Hledger.Cli.CliOptions+import Hledger.Cli.Utils (journalPrepareLotDetail) import Hledger.UI.UITypes import Hledger.UI.UIOptions (UIOpts(uoCliOpts)) import Hledger.UI.UIScreens (screenUpdate)@@ -64,16 +67,43 @@  -- | Make an initial UI state with the given options, journal, -- parent screen stack if any, and starting screen.+-- The provided journal should be the uncollapsed journal (with full lot detail);+-- the display journal (ajournal) is derived from it according to the lots toggle. uiState :: UIOpts -> Journal -> [Screen] -> Screen -> UIState uiState uopts j prevscrs scr = UIState {-   astartupopts  = uopts-  ,aopts         = uopts-  ,ajournal      = j-  ,aMode         = Normal-  ,aScreen      = scr-  ,aPrevScreens = prevscrs+   astartupopts        = uopts+  ,aopts               = uopts+  ,auncollapsedjournal = j+  ,ajournal            = uiDisplayJournal uopts j+  ,aMode               = Normal+  ,aScreen             = scr+  ,aPrevScreens        = prevscrs+  ,aWarnings           = []+  ,aClickFocus         = Unfocused   } +-- | Derive the display journal (what screens show) from the uncollapsed journal:+-- prepare lot detail for the current options (converted to cost basis when B is on),+-- collapsing it unless the lots toggle (--lots) is on. Mirrors the CLI's+-- maybePrepareLotDetail, so UI and CLI agree (and --ignore-lots is honored).+uiDisplayJournal :: UIOpts -> Journal -> Journal+uiDisplayJournal uopts = journalPrepareLotDetail (_rsReportOpts $ reportspec_ copts) keeplots+  where+    copts = uoCliOpts uopts+    ro = rawopts_ copts+    keeplots = boolopt "lots" ro || boolopt "ignore-lots" ro++-- | Toggle display of lot detail (lot subaccounts and synthetic lot postings), like the+-- CLI's --lots flag. This only flips the option; 'regenerateScreens' then re-derives the+-- display journal from the stored uncollapsed journal, in memory, without reloading from disk.+toggleLots :: UIState -> UIState+toggleLots ui = ui{aopts = uopts'}+  where+    copts  = uoCliOpts $ aopts ui+    ro     = rawopts_ copts+    ro'    = (if boolopt "lots" ro then unsetboolopt "lots" else setboolopt "lots") ro+    uopts' = (aopts ui){uoCliOpts = copts{rawopts_ = ro'}}+ -- | Toggle between showing only unmarked items or all items. toggleUnmarked :: UIState -> UIState toggleUnmarked = over statuses (toggleStatus1 Unmarked)@@ -152,9 +182,10 @@ 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+    toggleCostMode Nothing                     = Just ToCost+    toggleCostMode (Just NoConversionOp)       = Just ToCost+    toggleCostMode (Just ToCost)               = Just NoConversionOp+    toggleCostMode (Just ToTransactedCost)     = Just NoConversionOp     valOff _                             = Nothing  -- | Toggle between showing primary amounts or values (using valuation specified at startup, or a default).@@ -171,19 +202,20 @@     costOff _ = Just NoConversionOp  -- | Set hierarchic account tree mode.+-- Also sets no_elide, which hledger-ui wants in tree mode only (see uiInitialState). setTree :: UIState -> UIState-setTree = set accountlistmode ALTree+setTree = set no_elide True . set accountlistmode ALTree  -- | Set flat account list mode.+-- Also unsets no_elide, which hledger-ui wants in tree mode only (see uiInitialState). setList :: UIState -> UIState-setList = set accountlistmode ALFlat+setList = set no_elide False . 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+toggleTree ui = case ui ^. accountlistmode of+    ALTree -> setList ui+    ALFlat -> setTree ui  -- | Toggle between historical balances and period balances. toggleHistorical :: UIState -> UIState@@ -339,12 +371,17 @@ setMode :: Mode -> UIState -> UIState setMode m ui = ui{aMode=m} +-- | Descend into a new screen, making it active and suspending the current one+-- onto the navigation stack. The canonical way to push the zipper. 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 } +-- | Return to the parent screen, discarding the active one. At the root screen this+-- is a no-op, since the stack always keeps at least one screen. The canonical way to+-- pop the zipper. popScreen :: UIState -> UIState popScreen ui@UIState{aPrevScreens = s : ss} =   dbg1Msg ("popping screen " <> showScreenId (aScreen ui) <> ". " <> showScreenStack "" showScreenId ui1)@@ -356,18 +393,37 @@ -- 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}+resetScreens d ui@UIState{astartupopts=origopts, auncollapsedjournal=jraw, aScreen=s,aPrevScreens=ss} =+  ui{aopts=origopts, ajournal=jdisplay, aPrevScreens=[], aScreen=topscreen', aMode=Normal}   where-    topscreen' = screenUpdate origopts d j $ lastDef s ss+    -- restore the startup lots state too, re-deriving the display journal from the uncollapsed one+    jdisplay   = uiDisplayJournal origopts jraw+    topscreen' = screenUpdate origopts d jdisplay $ 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.+-- | Regenerate the content of all screens in the stack from the ui state's current+-- options and stored journal, 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}+-- This is the single place that establishes the display journal (ajournal) from the+-- stored uncollapsed journal and the current options, so the two journals can never+-- drift out of sync. To change the journal (eg on reload), set auncollapsedjournal and+-- then call this. To change the lots toggle, flip the option (toggleLots) and call this.+--+-- Every screen regenerates from its own stored parameters (plus the options, date and journal),+-- not from any other screen, so the whole stack refreshes uniformly here.+regenerateScreens :: Day -> UIState -> UIState+regenerateScreens d ui@UIState{aopts=opts, auncollapsedjournal=jraw, aScreen=s,aPrevScreens=ss} =+  let -- the display journal, derived here so it always matches the stored journal and options+      jdisplay = uiDisplayJournal opts jraw+      -- Regenerate the active screen and the whole hidden stack strictly, so no+      -- previous-generation screen/list/journal is retained after a reload (#1825).+      s'  = screenUpdate opts d jdisplay s+      ss' = strictMapScreens (screenUpdate opts d jdisplay) ss+  in s' `seq` ss' `seq` ui{ajournal=jdisplay, aScreen=s', aPrevScreens=ss'}++-- | Like @map@ over a screen stack, but strict in the list spine and in each regenerated+-- screen (forced to WHNF), so the lazy-map accumulation of previous-generation screens is+-- collapsed on each reload rather than chaining up over time (#1825).+strictMapScreens :: (Screen -> Screen) -> [Screen] -> [Screen]+strictMapScreens _ []     = []+strictMapScreens f (s:ss) = let s' = f s; ss' = strictMapScreens f ss in s' `seq` ss' `seq` (s' : ss')
Hledger/UI/UITypes.hs view
@@ -37,6 +37,11 @@ {-# LANGUAGE OverloadedStrings  #-} {-# LANGUAGE TemplateHaskell    #-} {-# LANGUAGE EmptyDataDeriving #-}+-- StrictData makes all screen-state and item record fields strict by default, so a future+-- field that captures prior-generation data cannot silently be lazy and reintroduce the+-- --watch reload leak (#1825). Note: this does not reach brick's GenericList.listSelected,+-- so the explicit index forcing in UIScreens/UIState is still required.+{-# LANGUAGE StrictData #-}  module Hledger.UI.UITypes where @@ -44,6 +49,7 @@ -- import GHC.IO (unsafePerformIO) import Data.Text (Text) import Data.Time.Calendar (Day)+import Data.Time.Clock (UTCTime) import Brick.Widgets.List (List) import Brick.Widgets.Edit (Editor) import Lens.Micro.Platform (makeLenses)@@ -68,12 +74,37 @@    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+  ,ajournal      :: Journal   -- ^ the journal being viewed (can change with --watch).+                              --   This is auncollapsedjournal collapsed for display, unless the lots toggle (--lots) is on.+  ,auncollapsedjournal :: Journal  -- ^ the journal as loaded, retaining full lot detail (lot subaccounts and+                                   --   synthetic lot postings). Kept so the lots toggle can re-derive ajournal in memory.+  -- aScreen together with aPrevScreens forms a non-empty navigation zipper: there is+  -- always an active screen, with zero or more suspended ancestor screens behind it.+  -- "At least one screen" is thus guaranteed by the types, and popScreen at the root is+  -- a no-op. aPrevScreens is kept nearest-first, so pushScreen/popScreen are O(1). Change+  -- the stack only through pushScreen/popScreen/resetScreens, not by editing these fields.+  --+  -- Both fields are kept lazy (~) under StrictData: a screen's construction may read back+  -- from the UIState that will contain it (eg --register startup derives a screen parameter+  -- from the ui's options), and forcing them at construction would turn that benign laziness+  -- knot into a <<loop>> (#1825). Reload regeneration forces screens explicitly+  -- (regenerateScreens), so this does not weaken the leak fix.+  ,aScreen      :: ~Screen   -- ^ the currently active screen (the zipper's focus)+  ,aPrevScreens :: ~[Screen] -- ^ suspended ancestor screens, nearest first   ,aMode         :: Mode      -- ^ the currently active mode on the current screen+  ,aWarnings     :: [String]  -- ^ warnings collected during the last journal (re)load, oldest first;+                              --   displayed until the next keypress (see warningOverlay)+  ,aClickFocus   :: ClickFocus  -- ^ tracks the click that brings the terminal window forward, so it can be ignored   } deriving (Show) +-- | Where we are in recognising a window-activating click (see uiHandle in Main).+-- This relies on the terminal's focus reporting; without it, we stay Unfocused.+data ClickFocus =+    Unfocused             -- ^ no recent focus gain, clicks are handled normally+  | FocusGainedAt UTCTime -- ^ the terminal window just gained focus, at this time+  | IgnoringClick         -- ^ ignoring the activating click, until its button release+  deriving (Show,Eq)+ -- | 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.@@ -98,12 +129,13 @@   | TransactionEditor   deriving (Ord, Show, Eq) --- Unique names for screens the user can navigate to from the menu.-data ScreenName =-    Accounts-  | CashScreen-  | Balancesheet-  | Incomestatement+-- The kinds of accounts-like screen, selecting which accounts and balances it shows.+-- Also used as the menu's screen names, since these are the screens reachable from the menu.+data AccountsScreenKind =+    AllAccounts+  | CashAccounts+  | BalancesheetAccounts+  | IncomestatementAccounts   deriving (Ord, Show, Eq)  ----------------------------------------------------------------------------------------------------@@ -163,12 +195,11 @@ -- 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+-- 3. new cases in the uiDraw and uiHandle functions+-- 4. new constructor and updater functions in UIScreens, and a new case in screenUpdate+-- 5. a new module implementing draw and event-handling functions+-- 6. a call from any other screen which enters it (eg the menu screen, a new case in msEnterScreen)+-- 7. 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,@@ -176,42 +207,24 @@ -- (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+  | AS AccountsScreenState  -- ^ the all-accounts, cash, balance sheet and income statement screens; see _assKind   | 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.+-- Used for the all-accounts, cash, balance sheet and income statement screens,+-- which differ only in which accounts and balances they show (selected by _assKind). data AccountsScreenState = ASS {     -- screen parameters:-   _assSelectedAccount :: AccountName                   -- ^ a copy of the account name from the list's selected item (or "")+   _assKind            :: AccountsScreenKind                    -- ^ which accounts-like screen this is+  ,_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)@@ -228,9 +241,10 @@  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+   _tssAccount        :: AccountName                -- ^ the account whose register we entered this screen from+  ,_tssForceInclusive :: Bool                       -- ^ whether the parent register included subaccounts+  ,_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 {@@ -242,7 +256,7 @@ -- | 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+  ,msItemScreen     :: AccountsScreenKind                   -- ^ 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.@@ -278,11 +292,6 @@  ---------------------------------------------------------------------------------------------------- --- | 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)
Hledger/UI/UIUtils.hs view
@@ -11,6 +11,7 @@   ,borderKeysStr'   ,borderPeriodStr   ,borderQueryStr+  ,clickFocusStep   ,defaultLayout   ,helpDialog   ,helpHandle@@ -29,6 +30,9 @@   ,modify'   ,suspend   ,redraw+  ,uiInstallWarningCollector+  ,uiTakeWarnings+  ,journalIsFromStdin   ,reportSpecAddQuery   ,reportSpecSetFutureAndForecast   ,listScrollPushingSelection@@ -42,7 +46,7 @@   ,mapScreens   ,uiNumBlankItems   ,showScreenStack-  ,sendVtyEvents+  ,sendVtyEvents  -- currently unused, kept (and exported, to avoid an unused-binding warning) for future use   ) where @@ -51,19 +55,21 @@ 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 Brick.Widgets.List (List, listSelectedL, listNameL, listItemHeightL, listSelected, listMoveTo, listElements) import Control.Concurrent.STM (atomically, writeTChan)  -- GHC only import Control.Monad.IO.Class import Data.Bifunctor (second)+import Data.IORef (IORef, newIORef, atomicModifyIORef') import Data.List import Data.Text qualified as T-import Data.Time (addDays)+import Data.Time (NominalDiffTime, UTCTime, addDays, diffUTCTime) import Graphics.Vty-  (Event(..),Key(..),Modifier(..),Vty(..),Color,Attr,currentAttr,refresh, displayBounds+  (Event(..),Key(..),Modifier(..),Button(..),Vty(..),Color,Attr,currentAttr,refresh, displayBounds   -- ,Output(displayBounds,mkDisplayContext),DisplayContext(..)   ,Vty (inputIface), InternalEvent (InputEvent), Input (eventChannel)   ) import Lens.Micro.Platform+import System.IO.Unsafe (unsafePerformIO)  import Hledger -- import Hledger.Cli.CliOptions (CliOpts(reportspec_))@@ -71,7 +77,6 @@ -- 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@@ -136,6 +141,23 @@ redraw :: EventM a s () redraw = getVtyHandle >>= liftIO . refresh +-- | Where warnings emitted while the TUI is running are collected, oldest first,+-- so they can be shown in the UI instead of being printed to stderr+-- (which would disrupt the terminal display). See uiInstallWarningCollector.+{-# NOINLINE uiWarningsRef #-}+uiWarningsRef :: IORef [String]+uiWarningsRef = unsafePerformIO $ newIORef []++-- | Make warnIO collect warnings in uiWarningsRef instead of printing them to stderr.+-- Call once, before starting the brick app.+uiInstallWarningCollector :: IO ()+uiInstallWarningCollector = setWarningHandler $ \msg ->+  atomicModifyIORef' uiWarningsRef $ \ws -> (ws ++ [msg], ())++-- | Take any warnings collected since last time, clearing the collection.+uiTakeWarnings :: IO [String]+uiTakeWarnings = atomicModifyIORef' uiWarningsRef $ \ws -> ([], ws)+ -- | Wrap a widget in the default hledger-ui screen layout. defaultLayout :: Widget Name -> Widget Name -> Widget Name -> Widget Name defaultLayout toplabel bottomlabel =@@ -199,11 +221,13 @@                   ,renderKey ("B   ", "show amounts/costs")                   ,renderKey ("E   ", "open editor")                   ,renderKey ("I   ", "toggle balance assertions")+                  ,renderKey ("L   ", "show/hide lot detail")                   ,renderKey ("V   ", "show amounts/market values")                   ,renderKey ("g   ", "reload data")                   ,renderKey ("C-l ", "redraw & recenter")                   ,renderKey ("C-z ", "suspend")                   ,renderKey ("q   ", "quit")+                  ,renderKey ("C-c ", "quit, from anywhere")                 ]              ] --           ,vBox [@@ -381,19 +405,32 @@ --  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+-- middle of the display area. When the selected item is near the end of the+-- list, the viewport is capped so that no blank padding is visible below the+-- last real item, and the last real items stay bottom-aligned (so recentering+-- a near-the-end selection doesn't push those items off screen). numitems is+-- the number of non-blank items in the list.+scrollSelectionToMiddle :: Int -> Brick.Widgets.List.List Name item -> EventM Name UIState ()+scrollSelectionToMiddle numitems list = do   case list^.listSelectedL of     Nothing -> return ()     Just selectedrow -> do-      Vty{outputIface} <- getVtyHandle-      pageheight <- dbg4 "pageheight" . snd <$> liftIO (displayBounds outputIface)+      let name = list^.listNameL+      mvp <- lookupViewport name+      -- Use the list viewport's actual height. Before its first render the+      -- viewport isn't known yet, so fall back to the terminal height.+      pageheight <- dbg4 "pageheight" <$> case mvp of+        Just VP{_vpSize=(_,h)} -> return h+        Nothing -> do+          Vty{outputIface} <- getVtyHandle+          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+        centeredtop  = selectedrow - (itemsperpage `div` 2)+        maxtop       = numitems - itemsperpage+        toprow       = dbg4 "toprow" $ max 0 (min centeredtop maxtop) -- assuming ViewportScroll's row offset is measured in list items not screen rows+      setTop (viewportScroll name) toprow  --                 arrow keys       vi keys               emacs keys                 enter key moveUpEvents    = [EvKey KUp []   , EvKey (KChar 'k') [], EvKey (KChar 'p') [MCtrl]]@@ -429,26 +466,28 @@         ,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+-- Vertically scroll the named list's viewport, which shows the given number of+-- non-blank items, by the given positive or negative number of items (usually 1 or -1).+-- Scrolling stops with the first item at the top or the last item at the bottom,+-- ignoring the blank items that pad the list out to the window height.+-- The selection is pushed along when necessary to keep it within the viewport;+-- without this, brick's list would keep pulling the viewport back to the selection,+-- stopping the scroll as soon as the selection reached the viewport's edge.+-- The (possibly moved) selection is left in the event handler's state.+listScrollPushingSelection :: Name -> Int -> Int -> EventM Name (Brick.Widgets.List.List Name item) ()+listScrollPushingSelection name listheight scrollamt =+  lookupViewport name >>= \case+    Nothing -> return ()     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+      let+        lastitem = listheight - 1+        top    = min (max 0 $ listheight - vpheight) $ max 0 $ _vpTop + scrollamt  -- new first visible item+        bottom = min lastitem $ top + vpheight - 1                                 -- new last visible item+      viewportScroll name `vScrollBy` (top - _vpTop)+      modify $ \list -> case listSelected list of+        Just selidx | selidx < top    -> listMoveTo top list+                    | selidx > bottom -> listMoveTo bottom list+        _ -> 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.@@ -460,6 +499,11 @@ dbguiIO :: String -> IO () dbguiIO = dbg1MsgIO +-- | Was this journal's main file read from standard input ?+-- If so it can't be re-read, edited, or watched for changes.+journalIsFromStdin :: Journal -> Bool+journalIsFromStdin j = journalFilePath j == "-"+ -- | Like dbgui, but convenient to use in EventM handlers. dbguiEv :: String -> EventM Name s () dbguiEv s = dbg1Msg s $ return ()@@ -498,15 +542,20 @@ -- 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+  MS _             -> "M"  -- menu+  AS ASS{_assKind} -> accountsScreenKindId _assKind+  RS _             -> "R"  -- register+  TS _             -> "T"  -- transaction+  ES _             -> "E"  -- error +-- | The compact id letter for an accounts-like screen of the given kind.+accountsScreenKindId :: AccountsScreenKind -> String+accountsScreenKindId = \case+  AllAccounts             -> "A"  -- all accounts+  CashAccounts            -> "C"  -- cash accounts+  BalancesheetAccounts    -> "B"  -- balance sheet accounts+  IncomestatementAccounts -> "I"  -- income statement accounts+ -- Show a screen's compact id, plus for register screens, the transaction descriptions. showScreenRegisterDescriptions :: Screen -> String showScreenRegisterDescriptions scr = case scr of@@ -518,12 +567,9 @@ -- 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+  MS MSS{_mssList}          -> "M" ++ (maybe "" show $ listSelected _mssList)  -- menu+  AS ASS{_assKind,_assList} -> accountsScreenKindId _assKind ++ (maybe "" show $ listSelected _assList)+  RS RSS{_rssList}          -> "R" ++ (maybe "" show $ listSelected _rssList)  -- register   TS _ -> "T"  -- transaction   ES _ -> "E"  -- error @@ -540,3 +586,37 @@ sendVtyEvents evs = do   input <- eventChannel . inputIface <$> getVtyHandle   liftIO $ atomically $ mapM_ (writeTChan input . InputEvent) evs++-- | Recognise the click that brings a background terminal window forward, so that it+-- only activates the window, without also selecting or entering something.+-- With focus reporting on, such a click arrives as a focus gain followed, a moment later,+-- by a left button press; we ignore that press, any repeats of it, and its release.+-- A click made more than 'activatingClickTime' after the window gained focus (eg after switching+-- to it with the keyboard) is handled as usual. Focus events themselves are not passed on.+-- Given the current time, an event and the current state, returns the new state and+-- whether to ignore the event.+clickFocusStep :: UTCTime -> BrickEvent n e -> ClickFocus -> (ClickFocus, Bool)+clickFocusStep now ev cf = case ev of+  VtyEvent EvGainedFocus -> (FocusGainedAt now, True)+  VtyEvent EvLostFocus   -> (Unfocused, True)+  _ | isLeftPress ev -> case cf of+        FocusGainedAt t | diffUTCTime now t < activatingClickTime -> (IgnoringClick, True)+        IgnoringClick -> (IgnoringClick, True)+        _             -> (Unfocused, False)+    | isRelease ev -> (Unfocused, cf == IgnoringClick)+    | otherwise -> (cf, False)+  where+    isLeftPress = \case+      MouseDown _ BLeft _ _                -> True+      VtyEvent (EvMouseDown _ _ BLeft _)   -> True+      _                                    -> False+    isRelease = \case+      MouseUp{}            -> True+      VtyEvent EvMouseUp{} -> True+      _                    -> False++-- | How soon after the window gains focus a left button press is taken to be the+-- activating click. Terminals send the two together, so this needs to be only long enough+-- to absorb event handling delays, and shorter than a deliberate switch-then-click.+activatingClickTime :: NominalDiffTime+activatingClickTime = 0.2
hledger-ui.1 view
@@ -1,5 +1,5 @@ -.TH "HLEDGER\-UI" "1" "August 2026" "hledger-ui-1.52.4 " "hledger User Manuals"+.TH "HLEDGER\-UI" "1" "December 2026" "hledger-ui-2.0 " "hledger User Manuals"   @@ -17,7 +17,7 @@ .PD \f[CR]hledger ui [OPTS] [QUERYARGS]\f[R] .SH DESCRIPTION-This manual is for hledger\(aqs terminal interface, version 1.52.4.+This manual is for hledger\(aqs terminal interface, version 2.0. See also the hledger manual for common concepts and file formats. .PP hledger is a robust, user\-friendly, cross\-platform set of programs for@@ -40,6 +40,12 @@ with a date field. (See hledger(1) \-> Input for details.) .PP+On unix\-like systems, it can also read from standard input+(\f[CR]\-f\-\f[R]).+In that case the data can\(aqt be re\-read or edited, so the+\f[CR]g\f[R], \f[CR]a\f[R], \f[CR]A\f[R] and \f[CR]E\f[R] keys and watch+mode have no effect.+.PP Unlike hledger, hledger\-ui hides all future\-dated transactions by default. They can be revealed, along with any rule\-generated periodic@@ -52,7 +58,8 @@ .EX Flags:   \-w \-\-watch                watch for data and date changes and reload-                            automatically+                            automatically (default)+     \-\-no\-watch             don\(aqt watch; reload only with the g key      \-\-theme=THEME          use this custom display theme (light,                             dark, terminal, greenterm)      \-\-cash                 start in the cash accounts screen@@ -66,14 +73,18 @@   \-t \-\-tree                 show accounts as a tree .EE .PP-and also supports many of hledger\(aqs general options:+hledger\-ui also supports many of hledger\(aqs 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.+General input flags:+  \-f \-\-file=[FMT:]FILE      Use this as the journal file (\- means stdin). If+                            not specified, $LEDGER_FILE or \(ti/.hledger.journal+                            will be used. If specified more than once, the+                            files will be read in order. Each file\(aqs format+                            (journal, csv, timeclock, timedot, rules..) is+                            inferred from the file extension or a FMT: prefix.+                            Some commands (add, import) write to the (first)+                            file, and expect it to be in journal format.      \-\-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.@@ -88,27 +99,30 @@                             will also be applied to these transactions. In                             hledger\-ui, also make future\-dated transactions                             visible at startup.-  \-I \-\-ignore\-assertions    don\(aqt check balance assertions by default-     \-\-txn\-balancing=...    how to check that transactions are balanced:-                            \(aqold\(aq:   use global display precision-                            \(aqexact\(aq: use transaction precision (default)-     \-\-infer\-costs          infer conversion equity postings from costs-     \-\-infer\-equity         infer costs from conversion equity postings+     \-\-ignore\-assertions    don\(aqt check balance assertions by default+     \-\-ignore\-lots          don\(aqt track lots: skip lot checks, inferred cost+                            bases and gain postings+  \-I                        shortcut for \-\-ignore\-assertions \-\-ignore\-lots+     \-\-txn\-tolerance=...    how much imbalance to allow in transactions:+                            \(aqentry\(aq:   \- the entry\(aqs precision (default)+                            \(aqdisplay\(aq: \- display precision (legacy)+     \-\-infer\-costs          infer costs from conversion equity postings+     \-\-infer\-equity         infer conversion equity postings from costs+     \-\-infer\-imbalance      add postings showing tolerated imbalances      \-\-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):+General output flags (affecting 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+  \-D \-\-daily                set report interval: 1 day+  \-W \-\-weekly               set report interval: 1 week+  \-M \-\-monthly              set report interval: 1 month+  \-Q \-\-quarterly            set report interval: 1 quarter+  \-Y \-\-yearly               set report interval: 1 year   \-p \-\-period=PERIODEXP     set begin date, end date, and/or report interval,                             with more flexibility      \-\-today=DATE           override today\(aqs date (affects relative dates)@@ -123,35 +137,56 @@      \-\-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:+  \-B \-\-cost                 convert amounts to their cost basis ({}), or else+                            their cost/sale amount (\(at/\(at\(at)+  \-V \-\-market               valuation mode: show amounts converted to market+                            value at period end(s) in their default valuation+                            commodity. Short for \-\-value=end.+  \-X \-\-exchange=COMM        valuation mode: show amounts converted to market+                            value at period end(s) in the specified commodity.+                            Short for \-\-value=end,COMM.+     \-\-value=WHEN[,COMM]    valuation mode: show amounts converted to market+                            value on the specified date(s) in their default+                            valuation commodity or a specified commodity. WHEN+                            can be:                             \(aqthen\(aq:     value on transaction dates                             \(aqend\(aq:      value at period end(s)                             \(aqnow\(aq:      value today                             YYYY\-MM\-DD: value on given date+                            \(aqcost\(aq:     cost basis, or else transacted cost+                            (same as \-B)+                            \(aqtransacted\(aq: transacted cost/sale amount (\(at/\(at\(at)+                            only+                            COMM may be written in double quotes; \(aq\(dq\(dq\(aq or an+                            empty COMM means the no\-symbol commodity.+     \-\-lots                 show lot subaccounts and other lot details   \-c \-\-commodity\-style=S    Override a commodity\(aqs display style.                             Eg: \-c \(aq.\(aq or \-c \(aq1.000,00 EUR\(aq-     \-\-pretty[=YN]          Use box\-drawing characters in text output? Can be-                            \(aqy\(aq/\(aqyes\(aq or \(aqn\(aq/\(aqno\(aq.-                            If YN is specified, the equals is required.+     \-\-pretty[=YN]          Use box\-drawing characters in text output? The+                            optional \(aqy\(aq/\(aqyes\(aq or \(aqn\(aq/\(aqno\(aq arg requires =.+     \-\-title=T              set or customise a report title+     \-\-subreport\-titles=TS  customise subreport headings in compound reports+                            (|\-separated)+     \-\-period\-titles=OPT    customise headings in periodic reports:+                            \(aqcompact\(aq: readable period names when possible+                            \(aqdates\(aq:   exact dates/date ranges always  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+  \-?                        show the hledger quick reference+  \-h \-\-help                 show this command\(aqs usage help+     \-\-info                 show this command\(aqs manual with info+     \-\-man                  show this command\(aqs manual with man+     \-\-webman               show this command\(aqs manual on the web+     \-\-examples             show examples for this command      \-\-version              show version information+     \-\-write\-lang=LANG      write LANG\(aqs PO file to the config directory, for+                            editing translations, and exit      \-\-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)+     \-\-lang=LANG            select the user interface language:+                            en (default), de, es, fr, ga, haw, it, ja, pt\-BR,+                            ru, uk, zh, or auto .EE .PP With hledger\-ui, the \f[CR]\-\-debug\f[R] option sends debug output to@@ -169,16 +204,24 @@ Click on list items to go deeper .IP \(bu 2 Click on the left margin (column 0) to go back.+.PP+Clicking a background hledger\-ui window just brings it forward, without+also clicking what\(aqs under the pointer.+This needs a terminal that reports focus changes, as most xterm\-like+terminals do (but not, currently, inside tmux or screen). .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:+While it is open, \f[CR]p\f[R], \f[CR]m\f[R] or \f[CR]i\f[R] show this+manual in a pager, man or info. .PP+The following keys work on most screens.+Additional screen\-specific keys are described under SCREENS below.+.SS Navigation keys 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]@@ -193,10 +236,18 @@ faster you may want to adjust it. On a mac, the Karabiner app is one way to do that.) .PP+\f[CR]ESCAPE\f[R] resets the UI state and jumps back to the top screen,+restoring the app\(aqs 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\(aqt be centered, since we+don\(aqt scroll above the top).+.SS Filtering keys \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.+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@@ -214,46 +265,33 @@ 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 \(dqtoday\(dq.-If you are using \f[CR]\-w/\-\-watch\f[R] and viewing a narrowed period+If you are in watch mode (the default) 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.)+(These keys work only with standard 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\(aqs Terminal, the SHIFT\-DOWN and SHIFT\-UP keys must be-configured as follows: in Terminal\(aqs preferences, click Profiles,-select your current profile on the left, click Keyboard on the right,-click + and add this for SHIFT\-DOWN: \f[CR]\(rs033[1;2B\f[R], click +-and add this for SHIFT\-UP: \f[CR]\(rs033[1;2A\f[R].-\ In other terminals (Windows Terminal ?)-you might need to configure SHIFT\-RIGHT and SHIFT\-LEFT to emit-\f[CR]\(rs033[1;2C\f[R] and \f[CR]\(rs033[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\(aqs 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\(aqt be centered, since we-don\(aqt scroll above the top).-.PP+(Tip: shifted arrow keys don\(aqt work out of the box in all terminals.+In Apple\(aqs Terminal, SHIFT\-DOWN and SHIFT\-UP must be added in+Preferences > Profiles > Keyboard, sending \f[CR]\(rs033[1;2B\f[R] and+\f[CR]\(rs033[1;2A\f[R] respectively.+Other terminals may need SHIFT\-RIGHT and SHIFT\-LEFT configured to send+\f[CR]\(rs033[1;2C\f[R] and \f[CR]\(rs033[1;2D\f[R].)+.SS Other keys \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].)+\f[CR]I\f[R] toggles checking of balance assertions and assert rules.+Disabling these checks temporarily can be useful for troubleshooting.+(If hledger\-ui was started with a \f[CR]\-\-pivot\f[R] or+\f[CR]\-\-obfuscate\f[R] option, re\-enabling them 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\(aqs add command, and reloads the updated file.@@ -262,20 +300,20 @@ \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.+\f[CR]$PATH\f[R]. .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.+(\f[CR]emacsclient \-a \(dq\(dq \-nw\f[R], or \f[CR]notepad.exe\f[R] on+Windows) on the journal file.+With some editors, 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\(aqs commodity (see hledger manual > Cost reporting.+cost\(aqs 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).+market value (see hledger manual > Value reporting). More specifically, .IP "1." 3 By default, the \f[CR]V\f[R] key toggles showing end value@@ -295,9 +333,15 @@ \- There\(aqs not yet any visual indicator that cost or value mode is active, other than the amount values. .PP+\f[CR]L\f[R] toggles lot detail (like the \f[CR]\-\-lots\f[R] flag),+showing or hiding lot subaccounts (such as+\f[CR]assets:broker:{2026\-01\-15, $50}\f[R]) and other per\-lot detail.+.PP \f[CR]q\f[R] quits the application.+\f[CR]CTRL\-c\f[R] also quits. .PP-Additional screen\-specific keys are described below.+\f[CR]CTRL\-z\f[R] suspends it, returning to the shell; resume it with+\f[CR]fg\f[R] as usual. .SH SCREENS At startup, hledger\-ui shows a menu screen by default. From here you can navigate to other screens using the cursor keys:@@ -305,9 +349,16 @@ 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],+You can also use a command line flag to specify a different startup+screen (\f[CR]\-\-cash\f[R], \f[CR]\-\-bs\f[R], \f[CR]\-\-is\f[R], \f[CR]\-\-all\f[R], or \f[CR]\-\-register=ACCT\f[R]).+.PP+On the four accounts screens, \f[CR]t\f[R] toggles between tree mode and+list mode, and you can limit the account depth shown: \f[CR]1\f[R] to+\f[CR]9\f[R] set the depth limit, \f[CR]0\f[R] sets it to zero (showing+just a single total), and \f[CR]\-\f[R] and \f[CR]+\f[R] (or+\f[CR]_\f[R] and \f[CR]=\f[R]) decrease and increase it.+\f[CR]DELETE\f[R] resets it, along with any other filters. .SS Menu screen This is the top\-most screen. From here you can navigate to several screens listing accounts of@@ -389,8 +440,7 @@ 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\(aqs print command and journal format-(hledger_journal(5)).+similar to hledger\(aqs print command and journal format. .PP The transaction\(aqs date(s) and any cleared flag, transaction code, description, comments, along with all of its account postings are shown.@@ -416,19 +466,27 @@ 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.)+.PP+Non\-fatal warnings, eg from reading CSV files, don\(aqt interrupt like+this; instead they are shown on the bottom line of the screen, at+startup or after a reload, until the next key press. .SH WATCH MODE-One of hledger\-ui\(aqs 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.+hledger\-ui immediately shows the effect of any file changes, reloading+automatically.+(This is enabled by default since 1.99.5.) .PP-This is very useful when reconciling.+If you don\(aqt want this \- eg because your data is very large or+constantly changing, or because file notifications don\(aqt work well on+your system \- you can disable it with \f[CR]\-\-no\-watch\f[R], and+reload manually with the \f[CR]g\f[R] key instead.+.PP+Watch mode is very useful when reconciling. A good workflow is to have your bank\(aqs 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:+window; and hledger\-ui in a terminal window, eg: .IP .EX-$ hledger\-ui \-\-watch \-\-register checking \-C+$ hledger\-ui \-\-register checking \-C .EE .PP As you mark things cleared in the editor, you can see the effect@@ -436,44 +494,15 @@ 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\(aqt 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\(aqre 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].+.PP+\f[B]HLEDGER_UI_EDITOR\f[R], \f[B]EDITOR\f[R] The editor command run by+the \f[CR]E\f[R] key, in that order of preference.+Default: \f[CR]emacsclient \-a \(dq\(dq \-nw\f[R], or+\f[CR]notepad.exe\f[R] on Windows. .SH BUGS We welcome bug reports in the hledger issue tracker (https://bugs.hledger.org), or on the hledger chat or mail list@@ -481,13 +510,8 @@ .PP Some known issues: .PP-\f[CR]\-f\-\f[R] doesn\(aqt work (hledger\-ui can\(aqt 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.+If reloading large files on a slow computer, there could be a noticeable+pause, during which the UI is unresponsive.   .SH AUTHORS
hledger-ui.cabal view
@@ -5,7 +5,7 @@ -- see: https://github.com/sol/hpack  name:           hledger-ui-version:        1.52.4+version:        2.0 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.@@ -26,7 +26,7 @@ license-file:   LICENSE build-type:     Simple tested-with:-    ghc==9.6.7, ghc==9.8.4, ghc==9.10.2, ghc==9.12.4+    ghc==9.6.7, ghc==9.8.4, ghc==9.10.3, ghc==9.12.4, ghc==9.14.1 extra-source-files:     CHANGES.md     README.md@@ -36,7 +36,7 @@  source-repository head   type: git-  location: https://github.com/simonmichael/hledger+  location: https://github.com/hledgerorg/hledger  flag debug   description: Build with GHC 9.10+ stack traces enabled@@ -47,11 +47,8 @@   exposed-modules:       Hledger.UI       Hledger.UI.AccountsScreen-      Hledger.UI.BalancesheetScreen-      Hledger.UI.CashScreen       Hledger.UI.Editor       Hledger.UI.ErrorScreen-      Hledger.UI.IncomestatementScreen       Hledger.UI.Main       Hledger.UI.MenuScreen       Hledger.UI.RegisterScreen@@ -69,23 +66,22 @@   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.52.4"+  cpp-options: -DVERSION="2.0"   build-depends:       ansi-terminal >=0.9     , async     , base >=4.18 && <4.23-    , brick >=2.1.1 && <2.3.2 || >=2.4 && <3+    , brick >=2.1.1 && <2.3.2 || >=2.4 && <3.2     , cmdargs >=0.8     , containers >=0.5.9     , data-default     , directory-    , doclayout >=0.3 && <0.6+    , doclayout >=0.3 && <0.7     , extra >=1.7.11     , filepath     , fsnotify >=0.4.2.0 && <0.5-    , githash >=0.1.6.2-    , hledger >=1.52.4 && <1.53-    , hledger-lib >=1.52.4 && <1.53+    , hledger ==2.0.*+    , hledger-lib ==2.0.*     , megaparsec >=7.0.0 && <9.8 || >=9.8.1 && <9.9     , microlens >=0.4     , microlens-platform >=0.2.3.1@@ -110,6 +106,7 @@   else     build-depends:         unix+      , vty-unix >=0.2.0.0  executable hledger-ui   main-is: hledger-ui.hs@@ -119,11 +116,45 @@       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 -rtsopts+  cpp-options: -DVERSION="2.0"+  build-depends:+      base >=4.18 && <4.23+    , hledger-ui+  default-language: GHC2021+  if (flag(debug))+    cpp-options: -DDEBUG++test-suite unittest+  type: exitcode-stdio-1.0+  main-is: UITest.hs+  other-modules:+      UITestUtils+      Paths_hledger_ui+  autogen-modules:+      Paths_hledger_ui+  hs-source-dirs:+      test   ghc-options: -Wall -Wno-incomplete-uni-patterns -Wno-missing-signatures -Wno-orphans -Wno-type-defaults -Wno-unused-do-bind -threaded-  cpp-options: -DVERSION="1.52.4"+  cpp-options: -DVERSION="2.0"   build-depends:       base >=4.18 && <4.23+    , brick >=2.1.1 && <2.3.2 || >=2.4 && <3.2+    , cmdargs >=0.8+    , directory+    , filepath+    , hledger ==2.0.*+    , hledger-lib ==2.0.*     , hledger-ui+    , mtl >=2.2.1+    , stm+    , tasty >=1.2.3+    , tasty-hunit >=0.10+    , text >=1.2.4.1+    , time >=1.5+    , vector+    , vty >=6.1+    , vty-crossplatform >=0.4.0.0   default-language: GHC2021   if (flag(debug))     cpp-options: -DDEBUG
hledger-ui.info view
@@ -18,7 +18,7 @@ or 'hledger ui [OPTS] [QUERYARGS]' -   This manual is for hledger's terminal interface, version 1.52.4.  See+   This manual is for hledger's terminal interface, version 2.0.  See also the hledger manual for common concepts and file formats.     hledger is a robust, user-friendly, cross-platform set of programs@@ -39,6 +39,10 @@ It can also read timeclock files, timedot files, or any CSV/SSV/TSV file with a date field.  (See hledger(1) -> Input for details.) +   On unix-like systems, it can also read from standard input ('-f-').+In that case the data can't be re-read or edited, so the 'g', 'a', 'A'+and 'E' keys and watch mode have no effect.+    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@@ -65,7 +69,8 @@  Flags:   -w --watch                watch for data and date changes and reload-                            automatically+                            automatically (default)+     --no-watch             don't watch; reload only with the g key      --theme=THEME          use this custom display theme (light,                             dark, terminal, greenterm)      --cash                 start in the cash accounts screen@@ -78,13 +83,17 @@   -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:+   hledger-ui 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.+General input flags:+  -f --file=[FMT:]FILE      Use this as the journal file (- means stdin). If+                            not specified, $LEDGER_FILE or ~/.hledger.journal+                            will be used. If specified more than once, the+                            files will be read in order. Each file's format+                            (journal, csv, timeclock, timedot, rules..) is+                            inferred from the file extension or a FMT: prefix.+                            Some commands (add, import) write to the (first)+                            file, and expect it to be in journal format.      --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.@@ -99,27 +108,30 @@                             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+     --ignore-assertions    don't check balance assertions by default+     --ignore-lots          don't track lots: skip lot checks, inferred cost+                            bases and gain postings+  -I                        shortcut for --ignore-assertions --ignore-lots+     --txn-tolerance=...    how much imbalance to allow in transactions:+                            'entry':   - the entry's precision (default)+                            'display': - display precision (legacy)+     --infer-costs          infer costs from conversion equity postings+     --infer-equity         infer conversion equity postings from costs+     --infer-imbalance      add postings showing tolerated imbalances      --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):+General output flags (affecting 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+  -D --daily                set report interval: 1 day+  -W --weekly               set report interval: 1 week+  -M --monthly              set report interval: 1 month+  -Q --quarterly            set report interval: 1 quarter+  -Y --yearly               set report interval: 1 year   -p --period=PERIODEXP     set begin date, end date, and/or report interval,                             with more flexibility      --today=DATE           override today's date (affects relative dates)@@ -134,35 +146,56 @@      --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:+  -B --cost                 convert amounts to their cost basis ({}), or else+                            their cost/sale amount (@/@@)+  -V --market               valuation mode: show amounts converted to market+                            value at period end(s) in their default valuation+                            commodity. Short for --value=end.+  -X --exchange=COMM        valuation mode: show amounts converted to market+                            value at period end(s) in the specified commodity.+                            Short for --value=end,COMM.+     --value=WHEN[,COMM]    valuation mode: show amounts converted to market+                            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+                            'cost':     cost basis, or else transacted cost+                            (same as -B)+                            'transacted': transacted cost/sale amount (@/@@)+                            only+                            COMM may be written in double quotes; '""' or an+                            empty COMM means the no-symbol commodity.+     --lots                 show lot subaccounts and other lot details   -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.+     --pretty[=YN]          Use box-drawing characters in text output? The+                            optional 'y'/'yes' or 'n'/'no' arg requires =.+     --title=T              set or customise a report title+     --subreport-titles=TS  customise subreport headings in compound reports+                            (|-separated)+     --period-titles=OPT    customise headings in periodic reports:+                            'compact': readable period names when possible+                            'dates':   exact dates/date ranges always  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+  -?                        show the hledger quick reference+  -h --help                 show this command's usage help+     --info                 show this command's manual with info+     --man                  show this command's manual with man+     --webman               show this command's manual on the web+     --examples             show examples for this command      --version              show version information+     --write-lang=LANG      write LANG's PO file to the config directory, for+                            editing translations, and exit      --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)+     --lang=LANG            select the user interface language:+                            en (default), de, es, fr, ga, haw, it, ja, pt-BR,+                            ru, uk, zh, or auto     With hledger-ui, the '--debug' option sends debug output to a 'hledger-ui.log' file in the current directory.@@ -184,33 +217,66 @@    * Click on list items to go deeper    * Click on the left margin (column 0) to go back. +   Clicking a background hledger-ui window just brings it forward,+without also clicking what's under the pointer.  This needs a terminal+that reports focus changes, as most xterm-like terminals do (but not,+currently, inside tmux or screen).+  File: hledger-ui.info,  Node: KEYS,  Next: SCREENS,  Prev: MOUSE,  Up: Top  3 KEYS ****** -Keyboard gives more control.+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.+While it is open, 'p', 'm' or 'i' show this manual in a pager, man or+info. -   '?' 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 following keys work on most screens.  Additional screen-specific+keys are described under SCREENS below. -   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.  'J'/'K' jump down/up 10 items at a-time.  Emacs-style ('CTRL-p'/'CTRL-n'/'CTRL-f'/'CTRL-b') and VI-style+* Menu:++* Navigation keys::+* Filtering keys::+* Other keys::+++File: hledger-ui.info,  Node: Navigation keys,  Next: Filtering keys,  Up: KEYS++3.1 Navigation keys+===================++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.  'J'/'K' jump down/up 10 items at a time.+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+   '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).+++File: hledger-ui.info,  Node: Filtering keys,  Next: Other keys,  Prev: Navigation keys,  Up: KEYS++3.2 Filtering keys+==================++'/' 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.@@ -224,60 +290,55 @@ '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;+to "today".  If you are in watch mode (the default) 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 standard 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.)+   (Tip: shifted arrow keys don't work out of the box in all terminals.+In Apple's Terminal, SHIFT-DOWN and SHIFT-UP must be added in+Preferences > Profiles > Keyboard, sending '\033[1;2B' and '\033[1;2A'+respectively.  Other terminals may need SHIFT-RIGHT and SHIFT-LEFT+configured to send '\033[1;2C' and '\033[1;2D'.) -   '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.++File: hledger-ui.info,  Node: Other keys,  Prev: Filtering keys,  Up: KEYS -   '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).+3.3 Other keys+============== -   'g' reloads from the data file(s) and updates the current screen and-any previous screens.  (With large files, this could cause a noticeable+'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'.)+   'I' toggles checking of balance assertions and assert rules.+Disabling these checks temporarily can be useful for troubleshooting.+(If hledger-ui was started with a '--pivot' or '--obfuscate' option,+re-enabling them 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.+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.+-a "" -nw', or 'notepad.exe' on Windows) on the journal file.  With some+editors, 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.+commodity (see hledger manual > Cost reporting).     'V' toggles value mode, showing amounts converted to their market-value (see hledger manual > Valuation flag).  More specifically,+value (see hledger manual > Value reporting).  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@@ -293,10 +354,15 @@ any visual indicator that cost or value mode is active, other than the amount values. -   'q' quits the application.+   'L' toggles lot detail (like the '--lots' flag), showing or hiding+lot subaccounts (such as 'assets:broker:{2026-01-15, $50}') and other+per-lot detail. -   Additional screen-specific keys are described below.+   'q' quits the application.  'CTRL-c' also quits. +   'CTRL-z' suspends it, returning to the shell; resume it with 'fg' as+usual.+  File: hledger-ui.info,  Node: SCREENS,  Next: WATCH MODE,  Prev: KEYS,  Up: Top @@ -309,9 +375,15 @@ 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').+   You can also use a command line flag to specify a different startup+screen ('--cash', '--bs', '--is', '--all', or '--register=ACCT'). +   On the four accounts screens, 't' toggles between tree mode and list+mode, and you can limit the account depth shown: '1' to '9' set the+depth limit, '0' sets it to zero (showing just a single total), and '-'+and '+' (or '_' and '=') decrease and increase it.  'DELETE' resets it,+along with any other filters.+ * Menu:  * Menu screen::@@ -434,8 +506,7 @@ ======================  This screen shows a single transaction, as a general journal entry,-similar to hledger's print command and journal format-(hledger_journal(5)).+similar to hledger's print command and journal format.     The transaction's date(s) and any cleared flag, transaction code, description, comments, along with all of its account postings are shown.@@ -466,64 +537,38 @@ again to reload and resume normal operation.  (Or, you can press escape to cancel the reload attempt.) +   Non-fatal warnings, eg from reading CSV files, don't interrupt like+this; instead they are shown on the bottom line of the screen, at+startup or after a reload, until the next key press.+  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.+hledger-ui immediately shows the effect of any file changes, reloading+automatically.  (This is enabled by default since 1.99.5.) -   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:+   If you don't want this - eg because your data is very large or+constantly changing, or because file notifications don't work well on+your system - you can disable it with '--no-watch', and reload manually+with the 'g' key instead. -$ hledger-ui --watch --register checking -C+   Watch mode 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+a terminal window, eg: +$ hledger-ui --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@@ -532,6 +577,10 @@ *LEDGER_FILE* The main journal file to use when not specified with '-f/--file'.  Default: '$HOME/.hledger.journal'. +   *HLEDGER_UI_EDITOR*, *EDITOR* The editor command run by the 'E' key,+in that order of preference.  Default: 'emacsclient -a "" -nw', or+'notepad.exe' on Windows.+  File: hledger-ui.info,  Node: BUGS,  Prev: ENVIRONMENT,  Up: Top @@ -544,33 +593,30 @@     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.+   If reloading large files on a slow computer, there could be a+noticeable pause, during which the UI is unresponsive.   Tag Table: Node: Top221-Node: OPTIONS1869-Node: MOUSE8753-Node: KEYS9085-Node: SCREENS14269-Node: Menu screen15009-Node: Cash accounts screen15325-Node: Balance sheet accounts screen15686-Node: Income statement accounts screen16022-Node: All accounts screen16407-Node: Register screen16770-Node: Transaction screen19213-Node: Error screen20393-Node: WATCH MODE20759-Node: --watch problems21657-Node: ENVIRONMENT22904-Node: BUGS23137+Node: OPTIONS2053+Node: MOUSE10829+Node: KEYS11405+Node: Navigation keys11963+Node: Filtering keys12897+Node: Other keys14820+Node: SCREENS17188+Node: Menu screen18244+Node: Cash accounts screen18560+Node: Balance sheet accounts screen18921+Node: Income statement accounts screen19257+Node: All accounts screen19642+Node: Register screen20005+Node: Transaction screen22448+Node: Error screen23607+Node: WATCH MODE24164+Node: ENVIRONMENT25201+Node: BUGS25600  End Tag Table 
hledger-ui.txt view
@@ -11,37 +11,42 @@      hledger ui [OPTS] [QUERYARGS]  DESCRIPTION-     This  manual is for hledger's terminal interface, version 1.52.4.  See also-     the hledger manual for common concepts and file formats.+     This manual is for hledger's terminal interface, version 2.0.  See also the+     hledger manual for common concepts and file formats. -     hledger is a robust, user-friendly,  cross-platform  set  of  programs  for+     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+     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+     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.jour-+     Like hledger, it reads from (and appends to) a journal  file  specified  by+     the  LEDGER_FILE  environment  variable (defaulting to $HOME/.hledger.jour-      nal); 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+     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+     On  unix-like systems, it can also read from standard input (-f-).  In that+     case the data can't be re-read or edited, so the g, a, A  and  E  keys  and+     watch mode have no effect.++     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".  OPTIONS-     Any  arguments  are  interpreted as a hledger query which filters the data.+     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+                                        automatically (default)+                 --no-watch             don't watch; reload only with the g key                  --theme=THEME          use this custom display theme (light,                                         dark, terminal, greenterm)                  --cash                 start in the cash accounts screen@@ -54,13 +59,17 @@               -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:+     hledger-ui 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.+            General input flags:+              -f --file=[FMT:]FILE      Use this as the journal file (- means stdin). If+                                        not specified, $LEDGER_FILE or ~/.hledger.journal+                                        will be used. If specified more than once, the+                                        files will be read in order. Each file's format+                                        (journal, csv, timeclock, timedot, rules..) is+                                        inferred from the file extension or a FMT: prefix.+                                        Some commands (add, import) write to the (first)+                                        file, and expect it to be in journal format.                  --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.@@ -75,27 +84,30 @@                                         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+                 --ignore-assertions    don't check balance assertions by default+                 --ignore-lots          don't track lots: skip lot checks, inferred cost+                                        bases and gain postings+              -I                        shortcut for --ignore-assertions --ignore-lots+                 --txn-tolerance=...    how much imbalance to allow in transactions:+                                        'entry':   - the entry's precision (default)+                                        'display': - display precision (legacy)+                 --infer-costs          infer costs from conversion equity postings+                 --infer-equity         infer conversion equity postings from costs+                 --infer-imbalance      add postings showing tolerated imbalances                  --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):+            General output flags (affecting 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+              -D --daily                set report interval: 1 day+              -W --weekly               set report interval: 1 week+              -M --monthly              set report interval: 1 month+              -Q --quarterly            set report interval: 1 quarter+              -Y --yearly               set report interval: 1 year               -p --period=PERIODEXP     set begin date, end date, and/or report interval,                                         with more flexibility                  --today=DATE           override today's date (affects relative dates)@@ -110,40 +122,61 @@                  --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:+              -B --cost                 convert amounts to their cost basis ({}), or else+                                        their cost/sale amount (@/@@)+              -V --market               valuation mode: show amounts converted to market+                                        value at period end(s) in their default valuation+                                        commodity. Short for --value=end.+              -X --exchange=COMM        valuation mode: show amounts converted to market+                                        value at period end(s) in the specified commodity.+                                        Short for --value=end,COMM.+                 --value=WHEN[,COMM]    valuation mode: show amounts converted to market+                                        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+                                        'cost':     cost basis, or else transacted cost+                                        (same as -B)+                                        'transacted': transacted cost/sale amount (@/@@)+                                        only+                                        COMM may be written in double quotes; '""' or an+                                        empty COMM means the no-symbol commodity.+                 --lots                 show lot subaccounts and other lot details               -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.+                 --pretty[=YN]          Use box-drawing characters in text output? The+                                        optional 'y'/'yes' or 'n'/'no' arg requires =.+                 --title=T              set or customise a report title+                 --subreport-titles=TS  customise subreport headings in compound reports+                                        (|-separated)+                 --period-titles=OPT    customise headings in periodic reports:+                                        'compact': readable period names when possible+                                        'dates':   exact dates/date ranges always              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+              -?                        show the hledger quick reference+              -h --help                 show this command's usage help+                 --info                 show this command's manual with info+                 --man                  show this command's manual with man+                 --webman               show this command's manual on the web+                 --examples             show examples for this command                  --version              show version information+                 --write-lang=LANG      write LANG's PO file to the config directory, for+                                        editing translations, and exit                  --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)+                 --lang=LANG            select the user interface language:+                                        en (default), de, es, fr, ga, haw, it, ja, pt-BR,+                                        ru, uk, zh, or auto -     With hledger-ui, the --debug option sends debug output to a  hledger-ui.log+     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+     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.  MOUSE@@ -156,89 +189,96 @@       * Click on the left margin (column 0) to go back. +     Clicking  a  background  hledger-ui  window just brings it forward, without+     also clicking what's under the pointer.  This needs a terminal that reports+     focus changes, as most xterm-like terminals do (but not, currently,  inside+     tmux or screen).+ KEYS-     Keyboard gives more control.+     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.  While it is open, p,+     m or i show this manual in a pager, man or info. -     ? 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 following keys work on most screens.  Additional  screen-specific  keys+     are described under SCREENS below. -     The cursor keys navigate: RIGHT or ENTER goes deeper, LEFT returns  to  the+   Navigation keys+     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.-     J/K     jump     down/up    10    items    at    a    time.     Emacs-style+     J/K    jump    down/up    10    items    at    a     time.      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+     (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  ES--     CAPEto  cancel.  There are also keys for quickly adjusting some common fil--     ters like account depth and transaction status (see below).   BACKSPACE  or-     DELETE removes all filters, showing all transactions.+     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. -     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+     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).++   Filtering keys+     /  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  ex--     pands  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 us--     ing -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+     Pressing  SHIFT-DOWN  narrows  the report period, and pressing SHIFT-UP ex-+     pands 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  in+     watch  mode  (the  default) and viewing a narrowed period containing today,+     the view will follow any changes in system date (moving to the period  con-+     taining  the  new  date).   (These  keys  work  only with standard calendar      year/quarter/month/week/day periods; they are not affected by a custom  re-      port 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 re--     spectively.)--     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).+     (Tip: shifted arrow keys don't work out of the box in  all  terminals.   In+     Apple's  Terminal,  SHIFT-DOWN  and SHIFT-UP must be added in Preferences >+     Profiles > Keyboard, sending \033[1;2B and \033[1;2A  respectively.   Other+     terminals  may need SHIFT-RIGHT and SHIFT-LEFT configured to send \033[1;2C+     and \033[1;2D.) +   Other keys      g reloads from the data file(s) and updates the current screen and any pre-      vious screens.  (With large files, this could cause a noticeable pause.) -     I toggles balance assertion checking.  Disabling  balance  assertions  tem--     porarily  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.)+     I toggles checking of balance assertions and assert rules.  Disabling these+     checks temporarily can be useful for troubleshooting.  (If  hledger-ui  was+     started  with  a --pivot or --obfuscate option, re-enabling them with the I+     key also reloads the journal, like g.) -     a  runs  command-line  hledger's add command, and reloads the updated file.+     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  in--     terface.  This key will be available if hledger-iadd is installed in $path.+     A  is like a, but runs the hledger-iadd tool, which provides a terminal in-+     terface.  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 po--     sitioned  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.+     E runs $HLEDGER_UI_EDITOR, or $EDITOR, or a default (emacsclient -a "" -nw,+     or notepad.exe on Windows) on the journal file.   With  some  editors,  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.+     (see hledger manual > Cost reporting).       V toggles value mode, showing amounts converted to their market value  (see-     hledger manual > Valuation flag).  More specifically,+     hledger manual > Value reporting).  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@@ -254,19 +294,27 @@      sual  indicator  that  cost  or value mode is active, other than the amount      values. -     q quits the application.+     L toggles lot detail (like the --lots flag), showing or hiding  lot  subac-+     counts (such as assets:broker:{2026-01-15, $50}) and other per-lot detail. -     Additional screen-specific keys are described below.+     q quits the application.  CTRL-c also quits. +     CTRL-z suspends it, returning to the shell; resume it with fg as usual.+ 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+     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).+     You can also use a command line flag to specify a different startup  screen+     (--cash, --bs, --is, --all, or --register=ACCT). +     On  the  four  accounts screens, t toggles between tree mode and list mode,+     and you can limit the account depth shown: 1 to 9 set the  depth  limit,  0+     sets it to zero (showing just a single total), and - and + (or _ and =) de-+     crease and increase it.  DELETE resets it, along with any other filters.+    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 any-@@ -341,7 +389,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)).+     to hledger's print command and journal format.       The transaction's date(s) and any cleared flag, transaction code,  descrip-      tion,  comments,  along with all of its account postings are shown.  Simple@@ -365,69 +413,48 @@      reload and resume normal operation.  (Or, you can press  escape  to  cancel      the reload attempt.) +     Non-fatal  warnings,  eg from reading CSV files, don't interrupt like this;+     instead they are shown on the bottom line of the screen, at startup or  af-+     ter a reload, until the next key press.+ 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.+     hledger-ui  immediately shows the effect of any file changes, reloading au-+     tomatically.  (This is enabled by default since 1.99.5.) -     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:+     If you don't want this - eg because your data is very large  or  constantly+     changing,  or  because  file notifications don't work well on your system -+     you can disable it with --no-watch, and reload manually with the g key  in-+     stead. -            $ hledger-ui --watch --register checking -C+     Watch  mode  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 a terminal window,+     eg: +            $ hledger-ui --register checking -C+      As  you  mark  things cleared in the editor, you can see the effect immedi-      ately 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:--     * It  may not work at all for you, depending on platform or system configu--       ration.  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 sys--       tem 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. +     HLEDGER_UI_EDITOR,  EDITOR The editor command run by the E key, in that or-+     der of preference.  Default: emacsclient -a "" -nw, or notepad.exe on  Win-+     dows.+ BUGS      We    welcome    bug    reports    in    the    hledger    issue    tracker-     (https://bugs.hledger.org),   or   on   the   hledger  chat  or  mail  list+     (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.+     If  reloading  large  files on a slow computer, there could be a noticeable+     pause, during which the UI is unresponsive.   @@ -447,4 +474,4 @@ SEE ALSO      hledger(1), hledger-ui(1), hledger-web(1), ledger(1) -hledger-ui-1.52.4                  August 2026                     HLEDGER-UI(1)+hledger-ui-2.0                    December 2026                    HLEDGER-UI(1)
+ test/UITest.hs view
@@ -0,0 +1,292 @@+{-# LANGUAGE OverloadedStrings #-}++-- | Proof-of-concept automated tests for hledger-ui, driving the real brick/vty+-- event loop headlessly. See "UITestUtils" for how the harness works and its limits.+-- These exercise the behaviours we most want to protect during refactoring:+-- drill-down, backtracking that preserves each screen's selection, and reload (#1825).++module Main (main) where++import Control.Exception (finally)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.IO qualified as T+import Brick (BrickEvent(VtyEvent))+import Data.List (mapAccumL)+import Data.Time (NominalDiffTime, UTCTime(..), addUTCTime)+import Data.Time.Calendar (fromGregorian)+import Graphics.Vty (Button(BLeft), Event(..))+import System.Directory (getTemporaryDirectory, removeFile)+import System.IO (hClose, openTempFile)+import Test.Tasty (TestTree, defaultMain, testGroup)+import Test.Tasty.HUnit (assertBool, assertFailure, testCase, (@?=))++import Hledger (Journal, readJournalFile')+import Hledger.UI.UIOptions (UIOpts)+import Hledger.UI.UITypes (ClickFocus(Unfocused))+import Hledger.UI.UIUtils (clickFocusStep)+import UITestUtils++main :: IO ()+main = defaultMain tests++tests :: TestTree+tests = testGroup "hledger-ui"+  [ testCase "drill-down builds the expected screen stack" $+      withFixture $ \uopts j -> do+        (states, _) <- driveUI uopts j [keyRight, keyRight]+        -- menu -> accounts -> register -> transaction+        screenPath (last states) @?= "MART"++  , testCase "backtracking preserves the accounts-screen selection" $+      withFixture $ \uopts j -> do+        (states, _) <- driveUI uopts j [keyDown, keyDown, keyRight, keyLeft]+        let afterDowns = states !! 2  -- accounts screen, selection moved down twice+            afterBack  = last states  -- popped back to the accounts screen+        activeScreenTag     afterDowns @?= "A"+        activeScreenTag     afterBack  @?= "A"+        selectedItemAccount afterBack  @?= selectedItemAccount afterDowns+        selectedIndex       afterBack  @?= selectedIndex       afterDowns++  , testCase "reload preserves the accounts-screen selection (#1825)" $+      withFixture $ \uopts j -> do+        --                          down  down   right(reg) g(reload) left(back)+        (states, _) <- driveUI uopts j [keyDown, keyDown, keyRight, key 'g', keyLeft]+        let beforeReload = states !! 2  -- accounts screen before drilling in+            afterReload  = last states  -- back on the accounts screen after a reload+        activeScreenTag     afterReload @?= "A"+        selectedItemAccount afterReload @?= selectedItemAccount beforeReload+        selectedIndex       afterReload @?= selectedIndex       beforeReload++  , testCase "register screen renders descriptions and amounts" $+      withFixture $ \uopts j -> do+        -- down twice selects expenses:food, then right enters its register+        (states, frames) <- driveUI uopts j [keyDown, keyDown, keyRight]+        activeScreenTag (last states) @?= "R"+        -- scope to the register frame itself (the accounts screen also shows balances)+        let reg = renderText region (last frames)+            hasText t = any (T.isInfixOf t) reg+        -- a description, rendered directly from the list ...+        assertBool "the register should show the 'grocery' transaction description"+          (hasText "grocery")+        -- ... and an amount, rendered via the amount-column width calculation+        assertBool "the register should show the $20 amount"+          (hasText "$20")++  , testCase "reload into a parse error shows, and keeps, the error screen" $+      -- Build the initial screens from a good journal, but point the cli options at a broken+      -- file, so reloading reads the broken file. (No mid-run file mutation needed.)+      withJournalFile fixture $ \goodPath ->+        withJournalFile brokenFixture $ \brokenPath -> do+          uopts <- withDay (fromGregorian 2024 6 1) <$> uiOptsForArgs ["-f", brokenPath, "--all"]+          j <- readJournalFile' goodPath+          (states, frames) <- driveUI uopts j [key 'g', key 'g']+          -- first g: uiReload fails on the broken file and pushes the error screen+          activeScreenTag (states !! 1) @?= "E"+          -- second g: the simplified esReload pops, reloads, and re-pushes; stays on the error screen+          activeScreenTag (last states) @?= "E"+          assertBool "the error screen should show its 'Oops' header"+            (any (T.isInfixOf "Oops") (renderText region (last frames)))++  , testCase "transaction screen shows the whole entry despite a cur: query" $+      withJournalFile multicurFixture $ \path -> do+        uopts <- withDay (fromGregorian 2026 6 1) <$> uiOptsForArgs ["-f", path, "--register", "aaa", "cur:USD"]+        j <- readJournalFile' path+        (states, frames) <- driveUI uopts j [keyRight]+        activeScreenTag (last states) @?= "T"+        let hasText t = any (T.isInfixOf t) $ renderText region (last frames)+        -- the register report excludes the EUR amounts per cur:USD, but the+        -- transaction screen should show the original entry in full+        assertBool "the transaction screen should show the matched USD amount"+          (hasText "10 USD")+        assertBool "the transaction screen should also show the EUR amount excluded by cur:USD"+          (hasText "20 EUR")++  , testCase "L toggles lot detail on the accounts screen, reversibly in memory" $+      withJournalFile lotsFixture $ \path -> do+        uopts <- withDay (fromGregorian 2026 6 1) <$> uiOptsForArgs ["-f", path, "--all"]+        -- readJournalFile' finalises the journal (creating lot subaccounts) but does not+        -- apply the CLI lot-collapse, so this is the uncollapsed journal the ui state expects.+        j <- readJournalFile' path+        (_, frames) <- driveUI uopts j [key 'L', key 'L']+        let lotShown = map (\pic -> any (T.isInfixOf "{2026-01-01") (renderText region pic)) frames+        case lotShown of+          [] -> assertFailure "no frames were rendered"+          (initialShown : _) -> do+            -- collapsed by default: the lot subaccount is hidden on the initial accounts screen+            assertBool "lot subaccounts are hidden by default" (not initialShown)+            -- L reveals the lot subaccount (re-derived in memory, no reload) ...+            assertBool "L reveals the lot subaccount" (or lotShown)+            -- ... and L again collapses it, proving the toggle is reversible without re-reading+            assertBool "L again collapses the lot subaccount" (not (last lotShown))+  , testCase "L on a lot subaccount's transaction screen keeps showing the entry" $+      withJournalFile lotsFixture $ \path -> do+        uopts <- withDay (fromGregorian 2026 6 1) <$> uiOptsForArgs ["-f", path, "--all"]+        j <- readJournalFile' path+        -- uncollapse lots, select the lot subaccount, drill into its transaction,+        -- then collapse lots again (making this screen's account vanish)+        (states, frames) <- driveUI uopts j [key 'L', keyDown, keyRight, keyRight, key 'L']+        activeScreenTag (last states) @?= "T"+        let hasText t = any (T.isInfixOf t) $ renderText region (last frames)+        assertBool "the transaction screen should still show the entry, in collapsed form"+          (hasText "10 AAPL")+        assertBool "the transaction screen should not show a blank transaction"+          (not $ hasText "0000-01-01")+  , testCase "after collapsing lots, the lot subaccount's register shows the base account" $+      withJournalFile lotsFixture $ \path -> do+        uopts <- withDay (fromGregorian 2026 6 1) <$> uiOptsForArgs ["-f", path, "--all"]+        j <- readJournalFile' path+        -- as in the previous test, but also return to the register screen: with lot+        -- detail collapsed, it should show the base account's register, not an empty one+        (states, frames) <- driveUI uopts j [key 'L', keyDown, keyRight, keyRight, key 'L', keyLeft]+        activeScreenTag (last states) @?= "R"+        let hasText t = any (T.isInfixOf t) $ renderText region (last frames)+        assertBool "the register title should show the base account, not the lot subaccount"+          (hasText "assets:stocks transactions" && not (hasText "{2026-01-01"))+        assertBool "the register should show the transaction, selected"+          (hasText "buy" && hasText "(1/1)")+  , testCase "B converts a sale from several lots at the lots' cost, with lots collapsed" $+      withJournalFile lotSaleFixture $ \path -> do+        uopts <- withDay (fromGregorian 2026 6 1) <$> uiOptsForArgs ["-f", path, "--all"]+        j <- readJournalFile' path+        (_, frames) <- driveUI uopts j [key 'B']+        let brokerLines = filter (T.isInfixOf "broker") $ renderText region (last frames)+        -- the 5 AAA left cost $100 (the sale's $30 price would give $-150)+        assertBool ("the broker should show its lots' cost, but shows: " <> show brokerLines)+          (any (T.isInfixOf "$100") brokerLines)+  , testCase "B turns cost off after starting with -B and reloading" $+      withJournalFile lotSaleFixture $ \path -> do+        uopts <- withDay (fromGregorian 2026 6 1) <$> uiOptsForArgs ["-f", path, "--all", "-B"]+        j <- readJournalFile' path+        --                                 g(reload) B(cost off)+        (_, frames) <- driveUI uopts j [key 'g', key 'B']+        let brokerLines = filter (T.isInfixOf "broker") $ renderText region (last frames)+        assertBool ("the broker should show its amount as recorded, but shows: " <> show brokerLines)+          (any (T.isInfixOf "5 AAA") brokerLines)+  , testCase "the last screen-selecting flag wins" $+      withJournalFile fixture $ \path -> do+        j <- readJournalFile' path+        let startingscreens args = do+              uopts <- withDay (fromGregorian 2024 6 1) <$> uiOptsForArgs (["-f", path] ++ args)+              (states, _) <- driveUI uopts j []+              return $ screenPath (last states)+        startingscreens ["--bs", "--all"] >>= (@?= "MA")+        startingscreens ["--all", "--bs"] >>= (@?= "MB")+        -- register wins over an earlier accounts flag; checking is a balance sheet account+        startingscreens ["--all", "--register", "checking"] >>= (@?= "MBR")+        -- and an accounts flag wins over an earlier register flag+        startingscreens ["--register", "checking", "--is"] >>= (@?= "MI")++  , testCase "C-c quits with the help or a minibuffer open" $+      -- driveUI's trailing q wouldn't quit from either of these, so it would time out+      withFixture $ \uopts j -> do+        _ <- driveUI uopts j [key '?', ctrlKey 'c']+        _ <- driveUI uopts j [key '/', ctrlKey 'c']+        pure ()++  , testCase "a click on an account enters its register" $+      withFixture $ \uopts j -> do+        (states, _) <- driveUI uopts j (leftClick 2 1)+        screenPath (last states) @?= "MAR"++  , testCase "a click that just brought the window forward is ignored" $+      withFixture $ \uopts j -> do+        (states, _) <- driveUI uopts j (EvGainedFocus : leftClick 2 1)+        screenPath (last states) @?= "MA"++  , testCase "clickFocusStep ignores only the click arriving just after a focus gain" $ do+      -- the ignore flags for a series of events at the given times (seconds)+      let ignored :: [(NominalDiffTime, Event)] -> [Bool]+          ignored = snd . mapAccumL step Unfocused+            where step cf (t, ev) = clickFocusStep (addUTCTime t t0) (VtyEvent ev :: BrickEvent () ()) cf+          t0 = UTCTime (fromGregorian 2024 6 1) 0+          press = EvMouseDown 2 1 BLeft []+          release = EvMouseUp 2 1 (Just BLeft)+      -- the activating click, including a repeated press, is ignored; the next one is not+      ignored [(0, EvGainedFocus), (0.01, press), (0.02, press), (0.1, release), (1, press), (1.1, release)]+        @?= [True, True, True, True, False, False]+      -- a click well after the focus gain (eg after switching windows by keyboard) is handled+      ignored [(0, EvGainedFocus), (1, press), (1.1, release)] @?= [True, False, False]+      -- without a focus gain, clicks are handled+      ignored [(0, press), (0.1, release)] @?= [False, False]+  ]++-- | Run an action with a freshly loaded fixture journal and matching startup+-- options (the all-accounts screen, with a pinned report date for reproducibility).+withFixture :: (UIOpts -> Journal -> IO a) -> IO a+withFixture act =+  withJournalFile fixture $ \path -> do+    uopts <- withDay (fromGregorian 2024 6 1) <$> uiOptsForArgs ["-f", path, "--all"]+    j <- readJournalFile' path+    act uopts j++-- A small date-stable journal: absolute dates, no forecasting.+fixture :: Text+fixture = T.unlines+  [ "2024-01-05 opening"+  , "    assets:checking      $1000"+  , "    equity:opening"+  , ""+  , "2024-02-10 grocery"+  , "    expenses:food          $20"+  , "    assets:checking"+  , ""+  , "2024-03-15 salary"+  , "    assets:checking       $500"+  , "    income:salary"+  ]++-- A journal with a parse error (a bare, non-directive line), so loading it fails.+brokenFixture :: Text+brokenFixture = T.unlines+  [ "2024-01-05 opening"+  , "    assets:checking      $1000"+  , "    equity:opening"+  , ""+  , "this is not a valid journal line"+  ]++-- A journal with a multi-commodity transaction, for testing cur: query filtering.+multicurFixture :: Text+multicurFixture = T.unlines+  [ "2026-01-01 multi"+  , "    aaa    10 USD"+  , "    aaa    20 EUR"+  , "    bbb   -10 USD"+  , "    bbb   -20 EUR"+  ]++-- A journal with a lot-tracked commodity, so accounts have lot subaccounts to show or hide.+lotsFixture :: Text+lotsFixture = T.unlines+  [ "commodity AAPL  ; lots:"+  , ""+  , "2026-01-01 buy"+  , "    assets:stocks    10 AAPL {$50} @ $50"+  , "    assets:cash     $-500"+  ]++-- | Two lots of AAA, and a sale taking from both (FIFO).+lotSaleFixture :: Text+lotSaleFixture = T.unlines+  [ "commodity AAA  ; lots:"+  , ""+  , "2026-01-01 buy"+  , "    assets:broker    10 AAA @ $10"+  , "    assets:cash"+  , ""+  , "2026-02-01 buy"+  , "    assets:broker    10 AAA @ $20"+  , "    assets:cash"+  , ""+  , "2026-03-01 sell"+  , "    assets:broker   -15 AAA @ $30"+  , "    assets:cash      $450"+  ]++withJournalFile :: Text -> (FilePath -> IO a) -> IO a+withJournalFile content act = do+  tmp <- getTemporaryDirectory+  (path, h) <- openTempFile tmp "hledger-ui-test.journal"+  T.hPutStr h content >> hClose h+  act path `finally` removeFile path
+ test/UITestUtils.hs view
@@ -0,0 +1,222 @@+{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}++{- |+A small headless harness for testing hledger-ui (a brick/vty terminal UI)+without a real terminal.++How it works: brick always hands vty a complete 'V.Picture' each frame (vty does+incremental diffing only when writing to a real terminal). So we run the real+'brickApp' event loop against a custom headless 'V.Vty' whose @update@ records the+full picture and whose @nextEvent@ replays a scripted list of events. brick reads+input only via @nextEvent vty@, so scripted events are fed by overriding that one+field. We capture, per event, both a 'UIState' snapshot (for semantic assertions)+and the full picture (converted to text only by tests that want it).++Limitations:++* Don't script the external-process keybindings (@a@ add, @A@ iadd, @E@ editor) or+  anything using @suspendAndResume@ - those shell out / suspend the terminal and are+  not unit-testable. The testable surface is navigation, selection, toggles, filter+  and reload (@g@), which is what we care about.++* Handlers call 'getCurrentDay', so keep fixture journals date-stable (no future or+  relative dates). 'uiOptsForArgs' pins the startup report date for reproducibility,+  but the handler date is still "today"; with a date-stable journal it doesn't matter.++* Every script is automatically terminated with a quit key so the loop halts;+  'driveUI' also wraps the run in a timeout so a mis-scripted test fails fast instead+  of hanging on the blocking @nextEvent@.+-}++module UITestUtils+( -- * Driving the UI+  driveUI+, region+  -- * Building options+, uiOptsForArgs+, withDay+  -- * Event helpers+, key+, ctrlKey+, leftClick+, keyEnter+, keyRight+, keyLeft+, keyDown+, keyUp+  -- * State accessors+, screenPath+, activeScreenTag+, selectedIndex+, selectedAccount+, selectedItemAccount+  -- * Rendering+, renderText+) where++import Control.Concurrent.STM (TChan, atomically, newTChanIO, readTChan, tryReadTChan, writeTChan)+import Control.Monad (void)+import Control.Monad.IO.Class (liftIO)+import Control.Monad.State.Class (get)+import Data.IORef (IORef, modifyIORef', newIORef, readIORef)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Lazy qualified as TL+import Data.Time.Calendar (Day)+import Data.Vector qualified as Vector+import System.Timeout (timeout)++import Brick (App(..), customMain)+import Brick.Widgets.List (listSelected, listSelectedElement)+import Graphics.Vty (Vty(..), Event(..), Key(..), Modifier(..), Button(..), Picture, DisplayRegion)+import Graphics.Vty.Input (Input(..))+import Graphics.Vty.Output.Mock (mockTerminal)+import Graphics.Vty.PictureToSpans (displayOpsForPic)+import Graphics.Vty.Span (SpanOp(..))++import Hledger (AccountName, Journal)+import Hledger.Cli (CliOpts(..), ReportSpec(..), ensureDebugFlagHasVal, process, replaceNumericFlags, usageError)+import Hledger.UI.Main (brickApp, uiHandle, uiInitialState)+import Hledger.UI.UIOptions (UIOpts(..), rawOptsToUIOpts, uimode)+import Hledger.UI.UITypes+import Hledger.UI.UIUtils (showScreenId)++-- | The fixed terminal size used for all headless rendering.+region :: DisplayRegion+region = (80, 40)++-- | Build a 'UIOpts' the way hledger-ui does at startup, but from an explicit+-- argument list instead of the process arguments. Eg @["-f", journalpath]@.+uiOptsForArgs :: [String] -> IO UIOpts+uiOptsForArgs args =+  rawOptsToUIOpts $ either usageError id $ process uimode args'+  where args' = ensureDebugFlagHasVal $ replaceNumericFlags args++-- | Pin the startup report date, so the initial screen state is reproducible.+withDay :: Day -> UIOpts -> UIOpts+withDay d uo = uo{uoCliOpts = copts{reportspec_ = rspec{_rsDay = d}}}+  where+    copts = uoCliOpts uo+    rspec = reportspec_ copts++-- | Build a headless 'Vty': captures every rendered picture, replays scripted+-- events, and stubs out all real terminal I/O. brick only reads input via+-- 'nextEvent' and only queries 'displayBounds' on the output, both satisfied here.+headlessVty :: DisplayRegion -> TChan Event -> IORef [Picture] -> IO Vty+headlessVty r evchan frames = do+  out <- snd <$> mockTerminal r+  stubChan <- newTChanIO  -- never read; brick reads via nextEvent below+  let input = Input+        { eventChannel      = stubChan+        , shutdownInput     = pure ()+        , restoreInputState = pure ()+        , inputLogMsg       = const (pure ())+        }+  pure Vty+    { update               = \pic -> modifyIORef' frames (pic:)+    , nextEvent            = atomically (readTChan evchan)+    , nextEventNonblocking = atomically (tryReadTChan evchan)+    , inputIface           = input+    , outputIface          = out+    , refresh              = pure ()+    , shutdown             = pure ()+    , isShutdown           = pure False+    }++-- | Run the real hledger-ui event loop headlessly over a scripted list of events,+-- returning a 'UIState' snapshot before any event (index 0) and after each scripted+-- event, plus every rendered picture (in chronological order). A quit key is appended+-- automatically to halt the loop; its snapshot/frame are not returned.+driveUI :: UIOpts -> Journal -> [Event] -> IO ([UIState], [Picture])+driveUI uopts j events = do+  let ui0 = uiInitialState uopts j+  snaps  <- newIORef [ui0]+  frames <- newIORef []+  evchan <- newTChanIO+  atomically $ mapM_ (writeTChan evchan) (events ++ [key 'q'])+  vty <- headlessVty region evchan frames+  let snapshot = get >>= \s -> liftIO (modifyIORef' snaps (s:))+      app = (brickApp (uoTheme uopts)){appHandleEvent = \ev -> uiHandle ev >> snapshot}+#if MIN_VERSION_brick(3,1,0)+  mres <- timeout (10 * 1000 * 1000) $ void $ customMain (Just . pure $ vty) Nothing app ui0+#else+  mres <- timeout (10 * 1000 * 1000) $ void $ customMain vty (pure vty) Nothing app ui0+#endif+  case mres of+    Nothing -> ioError $ userError "driveUI: timed out (did the script fail to halt?)"+    Just () -> pure ()+  rawsnaps <- reverse <$> readIORef snaps+  fs       <- reverse <$> readIORef frames+  pure (dropLast rawsnaps, fs)  -- drop the quit-key snapshot+  where dropLast xs = if null xs then xs else init xs++-- Event helpers ------------------------------------------------------------------++key :: Char -> Event+key c = EvKey (KChar c) []++-- | A control key, eg @ctrlKey 'c'@ for C-c.+ctrlKey :: Char -> Event+ctrlKey c = EvKey (KChar c) [MCtrl]++-- | A left-button click (press and release) at the given column and row.+leftClick :: Int -> Int -> [Event]+leftClick x y = [EvMouseDown x y BLeft [], EvMouseUp x y (Just BLeft)]++keyEnter, keyRight, keyLeft, keyDown, keyUp :: Event+keyEnter = EvKey KEnter []+keyRight = EvKey KRight []+keyLeft  = EvKey KLeft  []+keyDown  = EvKey KDown  []+keyUp    = EvKey KUp    []++-- State accessors ----------------------------------------------------------------++-- | The screen-id letters from the root (menu) screen down to the active screen,+-- eg @"MAR"@ for menu -> accounts -> register. Useful for asserting the nav path.+screenPath :: UIState -> String+screenPath ui = concatMap showScreenId $ reverse (aScreen ui : aPrevScreens ui)++-- | The active screen's id letter (eg @"R"@ for a register screen).+activeScreenTag :: UIState -> String+activeScreenTag = showScreenId . aScreen++-- | The selected list index on the active screen (the displayed transaction's+-- position on a transaction screen), if any.+selectedIndex :: UIState -> Maybe Int+selectedIndex ui = case aScreen ui of+  MS s -> listSelected (_mssList s)+  AS s -> listSelected (_assList s)+  RS s -> listSelected (_rssList s)+  TS s -> Just $ fromInteger $ fst (_tssTransaction s)+  ES _ -> Nothing++-- | The accounts-like screen's saved selected-account backup, if any. Note this+-- lags the live selection by one event (the handler saves it /before/ moving), so+-- for assertions about the current selection prefer 'selectedItemAccount'.+selectedAccount :: UIState -> Maybe AccountName+selectedAccount ui = case aScreen ui of+  AS s -> Just (_assSelectedAccount s)+  _    -> Nothing++-- | The account currently selected in the active accounts-like list (read live+-- from the list's selected element), if any.+selectedItemAccount :: UIState -> Maybe AccountName+selectedItemAccount ui = case aScreen ui of+  AS s -> acct (_assList s)+  _    -> Nothing+  where acct l = asItemAccountName . snd <$> listSelectedElement l++-- Rendering ----------------------------------------------------------------------++-- | Render a captured picture to lines of text (one per terminal row), for the+-- given region. Tests can then assert on whatever slice they like - a substring,+-- a specific row, a cropped region - without maintaining full golden screens.+renderText :: DisplayRegion -> Picture -> [Text]+renderText r pic = map rowText . Vector.toList $ displayOpsForPic pic r+  where+    rowText = T.concat . map opText . Vector.toList+    opText (TextSpan _ _ _ t) = TL.toStrict t+    opText (Skip n)           = T.replicate n " "+    opText (RowEnd n)         = T.replicate n " "