hledger 0.16.1 → 2.0
raw patch · 136 files changed
Files
- CHANGES.md +6426/−0
- Hledger/Cli.hs +887/−910
- Hledger/Cli/Add.hs +0/−292
- Hledger/Cli/Anchor.hs +265/−0
- Hledger/Cli/Anon.hs +61/−0
- Hledger/Cli/Balance.hs +0/−180
- Hledger/Cli/Chart.hs +615/−0
- Hledger/Cli/CliOptions.hs +1022/−0
- Hledger/Cli/Commands.hs +940/−0
- Hledger/Cli/Commands/Accounts.hs +158/−0
- Hledger/Cli/Commands/Accounts.txt +74/−0
- Hledger/Cli/Commands/Activity.hs +60/−0
- Hledger/Cli/Commands/Activity.txt +88/−0
- Hledger/Cli/Commands/Add.hs +632/−0
- Hledger/Cli/Commands/Add.txt +101/−0
- Hledger/Cli/Commands/Aregister.hs +359/−0
- Hledger/Cli/Commands/Aregister.txt +151/−0
- Hledger/Cli/Commands/Balance.hs +1297/−0
- Hledger/Cli/Commands/Balance.txt +1249/−0
- Hledger/Cli/Commands/Balance/Internal.hs +393/−0
- Hledger/Cli/Commands/Balancesheet.hs +64/−0
- Hledger/Cli/Commands/Balancesheet.txt +120/−0
- Hledger/Cli/Commands/Balancesheetequity.hs +72/−0
- Hledger/Cli/Commands/Balancesheetequity.txt +128/−0
- Hledger/Cli/Commands/Cashflow.hs +61/−0
- Hledger/Cli/Commands/Cashflow.txt +120/−0
- Hledger/Cli/Commands/Check.hs +144/−0
- Hledger/Cli/Commands/Check.txt +141/−0
- Hledger/Cli/Commands/Close.hs +308/−0
- Hledger/Cli/Commands/Close.txt +265/−0
- Hledger/Cli/Commands/Codes.hs +39/−0
- Hledger/Cli/Commands/Codes.txt +46/−0
- Hledger/Cli/Commands/Commodities.hs +109/−0
- Hledger/Cli/Commands/Commodities.txt +56/−0
- Hledger/Cli/Commands/Descriptions.hs +38/−0
- Hledger/Cli/Commands/Descriptions.txt +19/−0
- Hledger/Cli/Commands/Diff.hs +116/−0
- Hledger/Cli/Commands/Diff.txt +34/−0
- Hledger/Cli/Commands/Files.hs +106/−0
- Hledger/Cli/Commands/Files.txt +80/−0
- Hledger/Cli/Commands/Get.hs +311/−0
- Hledger/Cli/Commands/Get.txt +92/−0
- Hledger/Cli/Commands/Help.hs +124/−0
- Hledger/Cli/Commands/Help.txt +57/−0
- Hledger/Cli/Commands/Holdings.hs +1831/−0
- Hledger/Cli/Commands/Holdings.txt +300/−0
- Hledger/Cli/Commands/Import.hs +143/−0
- Hledger/Cli/Commands/Import.txt +296/−0
- Hledger/Cli/Commands/Incomestatement.hs +81/−0
- Hledger/Cli/Commands/Incomestatement.txt +122/−0
- Hledger/Cli/Commands/Init.hs +331/−0
- Hledger/Cli/Commands/Init.txt +66/−0
- Hledger/Cli/Commands/Notes.hs +39/−0
- Hledger/Cli/Commands/Notes.txt +17/−0
- Hledger/Cli/Commands/Payees.hs +67/−0
- Hledger/Cli/Commands/Payees.txt +35/−0
- Hledger/Cli/Commands/Prices.hs +257/−0
- Hledger/Cli/Commands/Prices.txt +73/−0
- Hledger/Cli/Commands/Print.hs +427/−0
- Hledger/Cli/Commands/Print.txt +326/−0
- Hledger/Cli/Commands/Quickref.hs +67/−0
- Hledger/Cli/Commands/Register.hs +352/−0
- Hledger/Cli/Commands/Register.txt +195/−0
- Hledger/Cli/Commands/Repl.txt +91/−0
- Hledger/Cli/Commands/Rewrite.hs +149/−0
- Hledger/Cli/Commands/Rewrite.txt +185/−0
- Hledger/Cli/Commands/Roi.hs +456/−0
- Hledger/Cli/Commands/Roi.txt +337/−0
- Hledger/Cli/Commands/Run.hs +621/−0
- Hledger/Cli/Commands/Run.txt +113/−0
- Hledger/Cli/Commands/Setup.hs +702/−0
- Hledger/Cli/Commands/Setup.txt +44/−0
- Hledger/Cli/Commands/Stats.hs +205/−0
- Hledger/Cli/Commands/Stats.txt +54/−0
- Hledger/Cli/Commands/Tags.hs +102/−0
- Hledger/Cli/Commands/Tags.txt +54/−0
- Hledger/Cli/Commands/Transactions.hs +41/−0
- Hledger/Cli/Commands/Transactions.txt +24/−0
- Hledger/Cli/CompoundBalanceCommand.hs +561/−0
- Hledger/Cli/Conf.hs +455/−0
- Hledger/Cli/Convert.hs +0/−546
- Hledger/Cli/DocFiles.hs +323/−0
- Hledger/Cli/Format.hs +0/−133
- Hledger/Cli/GitInfo.hs +17/−0
- Hledger/Cli/Histogram.hs +0/−53
- Hledger/Cli/Main.hs +0/−114
- Hledger/Cli/Options.hs +0/−452
- Hledger/Cli/Print.hs +0/−29
- Hledger/Cli/Register.hs +0/−64
- Hledger/Cli/Script.hs +56/−0
- Hledger/Cli/Stats.hs +0/−86
- Hledger/Cli/Tests.hs +0/−58
- Hledger/Cli/Utils.hs +472/−87
- Hledger/Cli/Version.hs +272/−65
- Hledger/Cli/Xirr.hs +61/−0
- LICENSE +4/−4
- README.md +9/−0
- app/hledger-cli.hs +17/−0
- bench/bench.hs +59/−0
- embeddedfiles/file-layouts/default/accounts.journal +43/−0
- embeddedfiles/file-layouts/default/commodities.journal +28/−0
- embeddedfiles/file-layouts/default/data/archive/README.md +1/−0
- embeddedfiles/file-layouts/default/data/bankofireland-checking.csv +3/−0
- embeddedfiles/file-layouts/default/data/getdata +34/−0
- embeddedfiles/file-layouts/default/main.journal +33/−0
- embeddedfiles/file-layouts/default/payees.journal +15/−0
- embeddedfiles/file-layouts/default/prices/getprices +144/−0
- embeddedfiles/file-layouts/default/rules/bankofireland-checking.csv.rules +25/−0
- embeddedfiles/file-layouts/simple/main.journal +79/−0
- embeddedfiles/file-layouts/years/2026.journal +37/−0
- embeddedfiles/file-layouts/years/all.journal +5/−0
- embeddedfiles/hledger-accounts.md +36/−0
- embeddedfiles/hledger-add.md +24/−0
- embeddedfiles/hledger-aregister.md +20/−0
- embeddedfiles/hledger-balance.md +37/−0
- embeddedfiles/hledger-balancesheet.md +33/−0
- embeddedfiles/hledger-import.md +28/−0
- embeddedfiles/hledger-incomestatement.md +21/−0
- embeddedfiles/hledger-print.md +32/−0
- embeddedfiles/hledger-ui.1 +529/−0
- embeddedfiles/hledger-ui.info +626/−0
- embeddedfiles/hledger-ui.md +32/−0
- embeddedfiles/hledger-ui.txt +477/−0
- embeddedfiles/hledger-web.1 +1045/−0
- embeddedfiles/hledger-web.info +1003/−0
- embeddedfiles/hledger-web.md +32/−0
- embeddedfiles/hledger-web.txt +920/−0
- embeddedfiles/hledger.1 +18667/−0
- embeddedfiles/hledger.info +18208/−0
- embeddedfiles/hledger.md +37/−0
- embeddedfiles/hledger.txt +14535/−0
- hledger-cli.hs +0/−6
- hledger.cabal +362/−113
- quickref.txt +24/−0
- shell-completion/hledger-completion.bash +2204/−0
- test/unittest.hs +14/−0
+ CHANGES.md view
@@ -0,0 +1,6426 @@+<!--+ _ _+ ___| (_)+ / __| | |+| (__| | |+ \___|_|_|++-->++User-visible changes in the hledger command line tool and library.++# 2.0 2026-12-01++All changes since hledger 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>.+hledger 2 is the first hledger release developed with AI assistance;+see the <https://hledger.org/relnotes.html> intro and <https://hledger.org/AI.html>.+For more help with upgrading, see <https://hledger.org/upgrading.html>.++## Highlights++The most notable changes since hledger 1.52; each is described in its section below.++- Lot tracking and capital gains: cost basis, lot movements and gains are tracked, checked and inferred;+ and a new `holdings` report shows your investments' performance. (Investments)+- Charts: most reports can be shown as charts in the terminal, or as SVG or HTML, with `--chart`; `--view` opens any report in a viewer. (Reporting)+- Translations: hledger, hledger-ui and hledger-web can be shown in 12 languages, and new languages are easy to add. (Running hledger)+- Assert rules: standing rules about your data, written as queries and checked like balance assertions. (Journal format)+- New queries: `::` (short for `find:`) searches in all fields, and `change:` and `balance:` select report rows by their amounts. (Reporting)+- Easier setup and importing: `init` creates starter files, `get` fetches data and prices, and `import` needs no arguments;+ CSV rules gain `merge`, functions, `ifs` tables and amount expressions. (Getting data in)+- Journal format: amount expressions, commodity aliases, account alias tags, and CSV files included in journals. (Journal format)+- Custom commands, defined in your config file; a reorganised `help`; and an improved `repl` and `run`. (Running hledger)+- Speed: hledger is 2-3x faster than 1.52, and uses up to a third less memory. (Performance)++## Breaking changes++hledger 2 reads hledger 1 data, and most users will need no changes.+But here are the breaking changes you might encounter.+(These are described more fully in the sections below.)++Changes in how files are read:++- Config files can no longer select the command to run with a bare first word in the general section.+ (Now such a word is read as a query argument.) The command must be given on the command line.+ (Config files)++- A repeated commodity declaration now adds to the earlier one instead of replacing it,+ and with several `-f` files the last file's display style is used, not the first's.+ (Journal format)++- Amounts which hledger infers no longer affect commodities' display precision, or the precision used to balance the entry.+ So some reports show fewer decimal places.+ (Journal format)++- `alias` directives are now applied before `apply account`, as in Ledger.+ (Journal format)++- `apply year` is now scoped, as in Ledger: `end apply year` restores the previous default year.+ (Journal format)++- In CSV rules, when a setting like `date-format` or `separator` is declared more than once, the last one now wins (except `skip`).+ And the `source` and `archive` rules now read from and save to a `data/` directory next to the journal.+ (Data import)++- Sales with a cost basis annotation and no gain posting now get an inferred gain posting, to `revenues:gain` by default.+ (Lot tracking)++Changes in commands and output:++- `print` now aligns amounts by their decimal mark. `--layout=hledger1` gives the old layout.++- `register` now hides zero-amount postings unless `-E` is used.++- `activity` now shows transactions per week, as a chart; `activity --postings -D -0` gives the old report.++- `--tldr` is now `--examples`. `stats -1` is now `stats --oneline`. `--txn-balancing=exact|old` is now `--txn-tolerance=entry|display` (the old spelling still works).+ `--verbose-tags` is now an option of `print` and `rewrite` only. `commodities --used` now shows only commodities used in transactions.++- `hledger test` is now `hledger --test`. The `demo` command is removed.+ The hledger-check-fancyassertions add-on is removed, replaced by assert rules.++- `accounts` and `payees` now respect transaction-specific query terms like `date:` or `desc:`,+ which no longer match declared but unused accounts or payees. `any:` and `all:` queries now also work in posting reports.+ New query prefixes (`find:`, `change:`, `balance:`) mean that account names beginning with those need `acct:`.+ (Queries)++- In JSON output, postings' `ptype` field is renamed to `preal`.+ In csv/html output, print's debit column now comes before credit, and aregister's "change" column is now "amount".++New errors you might see:++- With a `decimal-mark` directive (or CSV rule) in effect, a number clearly using the other decimal mark (`1,000.00` when `decimal-mark ,` is declared),+ or using the declared mark more than once (`1.2.34`, previously read as 1234), is now an error.+ ([#1985], [#1904])++- A hyphenated date range like `2026-13` is no longer read as "from 2026 to the 13th of this month"; it is rejected as a mistyped date.+ (Write `2026..13` for that.)++- Account names with an empty part (beginning or ending with `:`, or containing `::`) are now an error.+ And account names whose last part is enclosed in curly braces (`assets:{foo}`) are reserved for lot subaccounts, and must contain a valid lot name.+ (Journal format)++- An unquoted commodity symbol can no longer begin with `(` when written before the number, or with `/` when written after it,+ because of the new amount expressions; eg `(A) 10` or `10 /kg` must now be written `"(A)" 10` or `10 "/kg"`.+ (Journal format)++- In CSV rules files, `*` at the start of a line no longer begins a comment; use `#` or `;`.+ And more than one `source` rule in a rules file (including its included files) is now an error.+ (Data import)++- Ledger-style `assert EXPR` directives, previously ignored, must now use hledger's assert syntax.+ And an `end apply year` with no matching `apply year` is an error.+ (Assert rules, Journal format)++- Cost basis annotations like `{$50}`, which hledger 1 ignored, are now interpreted and checked.+ So entries using them may be rejected, eg if a purchase's `{}` cost basis and `@` cost disagree,+ if a sale takes from a lot which was never acquired, or if a sale's `@` is not the selling price.+ `-I` or `--ignore-lots` disables this.+ (Lot tracking)++## Running hledger++### Command line++- `acc`, `comm`, `desc` are now official short spellings for the `accounts`, `commodities` and `descriptions` commands.+ When an `-O` value looks like a file name, the error suggests `-o`.+ With an unrecognised argument, the error shows it, and the config file it came from, if any ([#2489]).+ hledger no longer duplicates options in the `LESS` environment variable.++- Colour handling is more robust: ANSI colour is no longer used when `TERM=dumb`, eg in an Emacs shell (`--color=yes` overrides);+ colour works in terminals where the background lightness can't be detected (a light background is assumed);+ and in terminals without truecolor support, we downgrade to the nearest xterm 256-colour.++- The built-in unit tests are now run with an option, `hledger --test[=PATTERN]`, not a command.++- Fixed: option handling is more robust: a missing option value gives a clear error (eg `hledger import -f --dry-run` no longer+ uses `--dry-run` as the file name); bad option values are always reported; and a flag belonging to another command gets an accurate error.+ (Kevin F. Konrad, [#2696])++- Fixed: `-o -` now writes to stdout, as documented; with `-o FILE`, an error no longer leaves an empty or truncated file behind;+ `stats -o FILE` writes all of its output to the file; and on Linux, output redirected to a file on a network drive (eg a CIFS mount) is no longer silently truncated.++- Multi-period reports with more than 10000 periods, or a `--forecast` generating more than 100000 transactions, now print a warning,+ so you can cancel. Such numbers usually mean a mistyped date, and could use many gigabytes of memory.+ ([#1683])++- Fixed: command line arguments are now passed to addon commands exactly as typed; apostrophes, empty strings or other special characters+ could be mangled or dropped. (Except on Windows, where addons are still run through the shell.)+ And options written after `--` are passed through to an addon command rather than consumed by hledger.+ (Kevin F. Konrad, Arthur Cinader, [#2696])++- Fixed: on Windows, file paths containing spaces are now quoted properly when running external helpers (info, man, tldr, pager, `$EDITOR`, hledger-iadd).+ ([#2646])++- hledger is now built with GHC runtime system options enabled.+ So eg `hledger +RTS -M2G -RTS ...` caps memory use (an overflow will raise an error rather than consuming all memory),+ and `+RTS -c` uses 20-40% less memory at the cost of speed.++### Config files++- You can now define custom commands (command aliases), by adding `NAME = COMMAND...` to the `[alias]` section of your config file.+ COMMAND can be a builtin command, an addon command, another alias, or a shell command prefixed with `!`, and can be continued on multiple indented lines.+ (Shell commands run only from your user config file, or one specified explicitly with `--conf`.)++- Config files can no longer specify the command to run via a bare first word in the general section;+ with command aliases able to run shell commands, that was too risky.++- Config file errors now use hledger's standard error format, and say how to run without the config file (`-n`).+ `--help`, `--version` and `--test` now work despite config file errors.++- Fixed: a `#` inside quotes is no longer misparsed as a comment start; leading whitespace before a section header,+ and a final line with whitespace and no newline, are accepted; and `--conf`/`--no-conf` flags inside a config file are ignored.++### Help++- `help` has been reorganised, and is now an entry point for all hledger docs:++ - `help` with no arguments (or `hledger` with no command) shows a quick reference card.+ - `help commands` shows the full commands list (`--builtins`, `--addons` and `--aliases` limit it).+ - `help examples [CMD]` shows command examples (like `--examples`, formerly `--tldr`).+ - `help usage [CMD]` shows command options and docs (like `-h`).+ - `help manual [TOPIC]` or `help TOPIC` shows the manual, in several formats, now including the HTML versions at hledger.org+ (`--webman`). Topics are matched by exact match or unique prefix, in the hledger-ui and hledger-web manuals too,+ and `help manual -l` lists them.+ - `help install`/`docs`/`support`/`home`/`sponsor`/`relnotes` open the corresponding hledger.org page in a web browser.+ (Arthur Cinader)++- When `TERM=dumb`, or in Emacs shells that don't support TUIs, `help manual` shows plain text instead of failing to run a viewer.+ `h` is help's official alias, and the `-?` flag also shows the quick reference. The `demo` command, which played asciinema recordings, is removed.++### REPL & run++- The REPL now auto-reloads before each command, detecting changes in input files, the config file, or installed addon commands (`--no-watch` disables this).+ Changes to CSV rules files and their data files are detected too.+ It shows a small startup banner, and the journal's file name in the prompt; `h` and `q` are help and quit;+ `help` and `CMD -h` show the same full, paged output as at the command line, and work even when there's a problem in the journal.++- Most general flags given to `repl` or `run` at startup (such as `-I`, `--strict`, `-b`/`-e`, `--depth`, `--cost`, `--color`)+ now apply to every command in the session or script (and can be overridden per command).+ An `-f` at startup sets the default journal file(s) for all commands, including addons; a nonexistent default journal file is tolerated.++- Quoted arguments in `run`/`repl` command lines and in config files are now tokenised more like the shell:+ quotes can enclose part of an argument, so `date:'1 to 15'` is the single argument `date:1 to 15`.+ Also like the shell, a lone quote within an argument (eg `desc:o'brien`) must now be quoted or avoided. A bad command line gives a proper error.++- `run` scripts are more robust: running an addon command no longer ends the script.++- `run` with `-O html`, `-o FILE.html` or `--view` writes its commands' outputs as one combined html page,+ with a folding section for each command, and links to show just titles, charts, or all data.+ Eg: `hledger run --view -- is -M --chart -- bs -Q --chart`.++### Translations++- hledger, hledger-ui and hledger-web can now be shown in 12 languages:+ English, Brazilian Portuguese, Chinese, French, German, Hawaiian, Irish, Italian, Japanese, Russian, Spanish and Ukrainian.+ The new `--lang=LANG` general option (also usable in config files) selects one, for report titles, headings, month names etc;+ `--lang=auto` chooses based on your system locale.+ Gaps in human translations are filled by machine translations, which are marked for review.+ Native speakers' help is welcome; see <https://hledger.org/TRANSLATING.html>.+ (Arthur Cinader, Daniil Iaitskov (Russian), Diego Depaoli (Italian), Henning Thielemann (German), Chunhui Ouyang (Chinese), Simon Michael, [#2736])++- You can add or override a translation by installing a gettext PO file at `$XDG_CONFIG_HOME/hledger/locale/LANG.po`; no compilation is needed.+ `hledger --write-lang=LANG` writes the current po file for a supported language, or a starter file for a new language, there.++### Error messages++- More error messages use the standard layout, with a position and an excerpt, and are detected correctly by editor addons like+ flycheck-hledger and flymake-hledger (which have been updated). Single-line positions show the line number just once (FILE:5, not FILE:5-5).+ Errors about a posting followed by comment lines now mark the correct line.++- Very long "expecting" lists in parse errors are abbreviated, and errors inside a cost amount are reported more specifically.++- Balance assertion failures show a better troubleshooting command: it ends the register at the assertion (`-e`), shows zero-amount postings (`-E`),+ uses the more precise `--ignore-assertions`, and escapes or quotes special characters properly.++## Getting data in++### Data entry++- `add`'s default amounts are better: they are shown with the journal's commodity display styles; they are not shown+ with ambiguous digit group marks (like `1.000`); and useful defaults are offered after entering a balance assignment.+ It weights similar transactions by their distance from today, not from the journal's latest date, so a future-dated typo doesn't skew the defaults.+ ([#2645], [#2656])++- Fixed: `add` no longer saves an entry which would make the journal unreadable.+ It now runs all enabled journal checks with the new entry (eg lots must be valid, and with `--strict`, the strict checks must pass),+ and if there's a problem, it shows the error and goes back a step, so you can correct the entry.+ Likewise if the entry doesn't balance or fails a balance assertion, it no longer restarts at posting 1.+ ([#2869])++- `add` and `import` now test for faulty filesystems before writing.+ Some filesystems, eg an Android shared filesystem in Termux, overwrite when told to append; `setup` warns about this too.+ ([#2577])++### Data import++- A new `init` command creates starter files for a new hledger setup, in the current or a given directory.+ `--layout` selects from several file layouts: `simple` (one journal file),+ `default` (separate account/commodity/payee declaration files, data/prices/rules directories, starter `get` scripts and csv rules),+ or `years` (a journal file per year, combined by all.journal). `hledger init FILE.journal` writes just one self-contained journal.+ Existing files are never changed, so init can be re-run to restore missing files. `--dry-run` shows what would be created.++- `get` is a new command for fetching transaction data and market prices. It runs two helper scripts which you can customise:+ `data/getdata`, to gather data (eg CSV) files in `data/`, and `prices/getprices`, to download market prices into `prices/`,+ next to the main journal file. `--transactions` or `--prices` runs just one of these. Sample scripts are in the hledger repo's bin/ directory,+ and are installed by `hledger init`. `get` preserves the format of existing prices when merging new ones.++- `import` with no file arguments now reads all the `.rules` files in the `rules/` directory next to the main journal file.+ (Files whose name begins with `.` or `_` are skipped; this is useful for included files.)+ And `import -g/--get` runs `get` first. So a complete import workflow can be: `hledger import -g [--dry-run]`.++- The CSV `source` and `archive` rules now use the journal's `data/` directory by default:+ `source` looks for bare file names and relative paths first in `data/`, then in `~/Downloads`+ (paths beginning with `./` or `../` are still relative to the rules file);+ and `archive` saves to `data/archive/` (previously, a data directory next to the rules file).++- More than one `source` rule in a CSV rules file is now an error, suggesting to+ use one rules file per data file. Previously all but one `source` rule was silently ignored.+ ([#2862])++- Fixed: `import` no longer writes entries which would make the journal unreadable.+ It now runs all enabled journal checks with the new entries (eg balance assertions, valid lot movements,+ and with `--strict` the strict checks), and if there's a problem, it shows the error, writing nothing.+ ([#2869])++- Fixed: `import` with `archive` enabled and multiple downloaded copies of the source file now deletes processed files and always makes progress+ (it could stall, reprocessing the oldest file); it archives only when new transactions were actually imported;+ and `import --dry-run` no longer archives data files when the flag is abbreviated (`--dr`).++- CSV error messages are much improved. They show the CSV file and record position with an excerpt; the record's field values with their numbers and names;+ the rules file, where each field's rule was defined, and any rules it overrode;+ and if an entry converted from CSV is rejected later (eg by balancing), the record it came from.+ `--debug=2` output for CSV reading is clearer, and shows the if rules that matched each record, with their file and line number.++- CSV rules can transform values by calling functions in `%{...}` expressions:+ upper, lower, capitalize, trim, negate, abs, concat, default, replace, substr, join.+ Eg `%{capitalize(%desc)}`, `%{default(%payee, %desc)}`, `%{replace(%desc, "ref#[0-9]+", "")}`, `%{join(", ", %note, %ref)}`.++- In CSV rules, a hledger field's value can now be referenced in field assignments. So you can eg append to a comment, building it up from several if rules.+ And a `%(FIELD)` interpolation syntax with parentheses is accepted, useful when the field name must be delimited from adjacent text+ (`account1 assets:%(type)checking`).++- CSV amount values can be amount expressions, like `amount1 %price + %fee`, as in journal format.+ A value counts as an expression if it contains an operator: a `*`, `/`, or a `+` or `-` which is not a leading or exponent sign.+ Within an expression, parentheses group (so `-(%price + %fee)` is the sum negated).+ If there's no operator, values follow the traditional sign conventions (eg parentheses mean negative).++- CSV rules' `currency` and `currencyN` now set a default commodity, like a `D` directive, instead of prepending text to amounts.+ So amounts which already have a commodity symbol keep it (previously `currency $` with `€7` gave a `$€` commodity).+ The value can be an amount showing the symbol's position and spacing, like `currency 1 USD`;+ its number style (eg `1.000,00 EUR`) is used as the commodity's default display style.+ A value which is not a commodity symbol or amount, like `currency 123`, is now an error.+ Rules that worked before give the same output as before.++- In CSV rules, if tables can use a new `ifs` keyword, which allows aligning their delimiters (`if` still works).+ The header line can have spaces around field names, spaces around values are ignored, and a blank value no longer assigns that field.+ Comment lines and blank lines can be used inside if blocks, and comment lines inside if tables can be indented.+ But `*` at the start of a line no longer begins a comment (previously a matcher line beginning with `*` was silently ignored, disabling the if block).++- A new `merge` rule combines several CSV records into one transaction.+ `merge` (or `merge N`) appends the next record(s) to the current record, naming their fields with a _ROWNUM suffix: `%description_2`, `%4_2`, etc.+ This is useful for banks and brokers which export a currency conversion or stock trade as multiple rows.++- In CSV rules, when a setting like `date-format` or `separator` is declared more than once, the last declaration now wins, as the manual says,+ rather than the first (except for `skip`, where the first still wins).+ So an included rules file's settings can be overridden by declarations after the `include` line;+ if you declared one before an `include` to override the included file, move it below.+ ([#2539])++- CSV rules files' `include` directives are handled more robustly: include cycles and unreadable files are reported properly;+ errors in included files are reported at the right file and line; and included files handle BOMs and CRLF line endings.+ ([#2537])++- In CSV data, characters which journal format can't represent are now replaced, with a warning:+ a semicolon in a description (which would start a comment) becomes `.,`, and a right parenthesis in a transaction code becomes `]`.+ ([#2413])++- A CSV rules file's data-generating command (`source | CMD`) failing no longer aborts the whole run; it warns and continues, as if no data was found.+ So when `import` processes several rules files, one flaky source won't block the rest.+ When a `source` command is run, the message names the rules file responsible.++- Fixed: a CSV rules `source | CMD` command no longer reads hledger's standard input, which could hang or consume input meant for something else.+ A `#` in a `source` rule now always starts a comment, even after `|`. On Windows, `source` paths with a drive letter are recognised as absolute.++- `files` is more useful for tools which need to know a journal's input files:+ `-t/--tree` shows the include hierarchy; it also lists the CSV rules files and data files used;+ `-O json` gives each file's path, depth and parent; and it no longer processes the data, so it works with journals+ that have errors other than syntax errors, and a missing included file gives just a warning.++## Journal format++### Accounts++- Account directives can now declare account aliases with `alias:` tags.+ Eg `account assets:bank:checking ; alias: checking` is like writing an `alias checking = assets:bank:checking` directive at that point.+ A Ledger-style indented `alias NAME` subdirective is also accepted.++- `alias` directives, subdirectives and tags are now applied before `apply account`, as in Ledger,+ so that a file's aliases keep working when it is included under `apply account`.+ If you had `apply account X` and then `alias X:foo = ...`, that alias should now be written `alias foo = ...`.+ `--alias` options still apply last, to the full account names.+ ([#2733])++- Account names with an empty part are now an error: they can no longer begin or end with `:`, or contain `::`.+ Such names caused confusion and wrong reports (eg `bs` omitted an empty top-level account, and `a:b:` was a different account from `a:b`).+ This is checked in journal, timeclock and timedot files, CSV rules, and the add command and hledger-web's add form+ (but not in names produced by aliases or `--pivot`).+ ([ledger#3348](https://github.com/ledger/ledger/issues/3348))++- Fixed: `apply account` ignores a trailing colon, as in Ledger: `apply account Assets:` now gives `Assets:Bank`, not `Assets::Bank`.+ ([#2858])++- Fixed: `end aliases` also cancelled `--alias` options, for the rest of that file and the files it included.++- check accounts (and strict mode) no longer require declaring the accounts that hledger chooses for generated postings.+ `check tags` now also checks commodity directives' tags; `alias` and `lots` are built-in tags.++- Fixed: a subaccount-inclusive balance assignment like `a =* $0` could also change other commodities' balances in subaccounts.+ ([#2772])++- There are three new account types: Gain (`G`), a subtype of Revenue, for capital gains;+ Imbalance (`M`), a subtype of Equity, for `--infer-imbalance`; and UnrealisedGain (`U`), a subtype of Equity, not currently used.+ When several accounts are declared with the Gain or Conversion type, generated postings use the first declared.++- Account names whose final part is enclosed in curly braces, like `assets:{foo}`, are lot subaccounts,+ and must contain a valid lot name (unless `-I`/`--ignore-lots` is used).++### Commodities and amounts++- Numbers can now also use `_` or `'` as digit group marks.+ (Kevin F. Konrad, [#273], [#1489])++- With a `decimal-mark` directive (or CSV rule) in effect, a number using a different decimal mark,+ or using the declared mark more than once, is now an error.+ ([#1985], [#1904])++- Amounts which hledger infers no longer affect display precisions, or entries' balancing precisions.+ So an unseen high-precision balancing amount, eg inferred from a precise `@` cost, no longer makes it harder to balance the entry;+ some reports that used to add unnecessary decimal zeros no longer do so;+ and reports more consistently show amounts smaller than their commodity's display precision as `0`.++- Posting amounts, and costs, can now be written as arithmetic expressions, like `$50.20 + $16.54`, `$800.00 * 1.05`, `($92.00 + $15.00) / 3`+ or `1 GBP @ (1 / 1.14 EUR)`. `+`, `-`, `*`, `/` and parentheses are supported.+ The results of `*` and `/` are rounded to the entry's decimal places (costs are kept exact).+ To avoid clashing with these, an unquoted commodity symbol can no longer begin with `(` when written before the number,+ or with `/` when written after it.+ See Amount expressions in the manual.+ (Martin, [#2648], a bounty funded by James Shubin; [#2856], [#2857])++- Commodity directives can now declare commodity aliases, with `alias:` tags: other symbols (or units) for the same commodity. Eg:++ commodity USD 1.00 ; alias: $, alias: US$, alias: "US dollars"+ commodity h 1.00 ; alias: 60 min++ Amounts written with an alias are converted to the canonical commodity when read (print shows them as written; `print -x` shows them converted),+ so eg `$100` and `100 USD` are the same thing, and can balance each other.+ An alias can have a multiplier, for differently-sized units.+ Aliases are also used as a last resort exchange rate by `-V`, `-X` and `--value`, in all file trees;+ `prices --show-aliases` lists these rates.+ This is useful eg when your journal and your downloaded price data use different symbols for a currency.++- A repeated commodity declaration (in the same file, an included file, or another `-f` file) now adds to the earlier one, instead of replacing it:+ aliases are combined, a display style replaces the earlier one only if given, and later tags take precedence.+ With several `-f` files, the last file's display style is now used (previously the first's); `--debug=1` shows any that differ.++### Transaction balancing++- Transaction balancing errors are clearer, and show the summed amounts.+ When rounded amounts being compared look identical, more decimal places are shown.+ ([#2636])++- `--txn-balancing=exact|old` is now `--txn-tolerance=entry|display`, meaning "balance transactions within+ the entry's precision" (preferred) or "within display precision" (deprecated; lets you postpone fixing old journals).+ The old spelling still works.++- Fixed: an inferred unit cost could be shown with too few decimal places (eg `@ 33.33 B`),+ so `print -x` output could be rejected as unbalanced when read back.+ Now it is shown exactly, or with 8 decimal places if it's a repeating decimal.+ In other cases too, print shows repeating decimals with 8 decimal places, not 255.++- Fixed: in entries with balance assignments, `check balanced` and strict mode didn't catch implicit commodity conversions,+ and `--txn-balancing` had no effect.++- `--infer-imbalance` adds `equity:imbalance` postings to exactly balance entries which are+ balanced only when rounded to the entry's precision (eg because of a rounded `@` cost).+ So totals at cost become exactly zero, and the accumulated imbalance can be seen.+ The new Imbalance (`M`) account type can be used to select a different account.++### Other journal features++- One or more adjacent comment lines directly above a transaction (a "preceding comment") are now considered part of the transaction,+ and are shown when it is printed.++- Journal files can now `include` CSV/SSV/TSV files, or CSV rules files.+ `include FILE.csv` uses a nearby FILE.csv.rules file; for more flexibility, include the rules file and specify the data with a `source` rule.++- `apply year` is now scoped, as in Ledger: `end apply year` restores the previous default year,+ so following year-less dates no longer get the block's year.+ `apply year` blocks can be nested, and one left open lasts until the end of its file.+ An `end apply year` with no matching `apply year` is now an error.+ (Previously `apply year` was a deprecated alias for `Y`, and `end apply year` was ignored.)+ A bare `end` or `end apply`, and an unmatched `end apply account`, give clearer errors.+ ([#2852])++- A `date:` or `date2:` tag with an empty value in a posting comment is now accepted, setting no date. This helps when reading Ledger journals.++### Assert rules++- The new `assert` directive declares rules, written as queries, which hledger checks whenever it reads the journal,+ like balance assertions. Eg:++ assert none daily type:A balance:<0 ; no asset accounts are negative at end of day+ assert some monthly income:salary ; there's a salary transaction every month+ assert none expenses:petty amt:>+500 ; no single petty expense exceeds 500++ Each rule's query is run as `hledger bal -E QUERY` would run it, over the whole journal,+ or in each period of its period expression, and must match no rows (`none`) or at least one row (`some`).+ The new `balance:` and `change:` terms (see Queries) can be used to test the rows' balances and changes;+ otherwise, a rule is about which postings exist.+ A periodic rule can be followed by indented `skip` lines, naming dates or periods to skip checking.+ Assert rules are part of the assertions check: `-I` disables them, `-s` or `check assertions` re-enables them.+ Their scope is the file tree they are declared in.+ When a rule fails, the error shows every period in which it failed, some of the matching balances, changes or postings,+ and a report command to see more.+ ([#1738], [#2719])++- `hledger check` can also check assert rules given as arguments, eg `hledger check 'assert none daily type:A balance:<0'`.+ This is handy for trying out a rule, or for rules you don't want to keep in the journal.++- These replace the hledger-check-fancyassertions add-on script, which is removed.+ Ledger-style `assert EXPR` directives, which hledger used to ignore, are now an error unless adapted to hledger's syntax.++### Time logging++- In timedot files, a line whose first word looks like a date is now always parsed as a date line, with a clear error if the date is invalid+ (instead of being silently treated as a comment or a zero-amount entry).+ Lines with an org heading prefix (eg `** `) are parsed more consistently.++- Fixed: timedot's `mo` and `y` units were 7 times too large; now they are 30 and 365 days, as documented. (Wrong since hledger 1.4.)++- Fixed: timedot and timeclock durations are no longer rounded to 0.01 hours, so totals don't drift,+ and a timeclock session crossing midnight no longer loses a second.++## Investments++### Lot tracking++- hledger can now track investment lots and calculate capital gains.+ It tracks each purchase's cost basis, infers and validates lot movements across transactions and accounts,+ and calculates (or checks) the gain or loss when you sell. In brief:++ - Lot tracking is enabled for a commodity by a `lots:` tag on its commodity directive;+ or lot postings are recognised by a cost basis annotation, or an explicit lot subaccount.+ Lot calculation and checking is done whenever such entries are present; `--ignore-lots` (or `-I`, which now also means this) disables it.++ - Cost basis is written as `{DATE, "LABEL", COST}`, with all parts optional.+ Ledger's `{COST} [DATE] (NOTE)` syntax is also accepted. `{{TOTALCOST}}` is supported.+ Cost basis (`{}`) and transacted cost (`@`) are each inferred from the other, so writing either is often sufficient.+ In an acquisition, if both are written, they must agree.++ - Postings are classified as acquisitions, disposals, transfers or gains.+ Disposals balance at cost basis, with a single realised gain posting, which can be written (and is checked) or left out (and is inferred);+ this is historical cost accounting, preserving the accounting equation.+ Gain accounts are detected by the new Gain (`G`) account type, declared or inferred from names like `revenues:gain` or `income:capital-gains`;+ `revenues:gain` is used by default.++ - Lots are selected for disposal or transfer by a reduction method, set with the `lots:` tag's value, per commodity or per account:+ FIFO, LIFO, HIFO, AVERAGE, or the all-accounts variants FIFOALL, LIFOALL, HIFOALL, AVERAGEALL.+ Or you can select lots explicitly, with a cost basis annotation. `lots: NONE` on an account opts it out (eg for tax-sheltered accounts).++ - Transfers between accounts preserve lots' identity and cost. Many forms are understood: multiple sources or destinations,+ elided amounts, fees (priced or unpriced; a priced fee is split off as a small disposal), and transfers into AVERAGE pools, which are re-averaged.++ - Short positions are supported, as lots in a Liability account, where a negative posting opens a lot and a positive one covers it.+ ([#2756])++ - Internally, each lot has its own subaccount, like `assets:broker:{2026-01-15, $50}`. These are hidden by default;+ the `--lots` flag shows them in any report, and you can also write them explicitly.+ `close --clopen --lots` carries lots between yearly files.++ - `print` shows lot postings with an explicit cost basis, so its output is re-readable; `print --lots` shows the per-lot postings,+ and the new `print -a/--all` shows everything useful for troubleshooting (`--explicit --lots --verbose-tags`).+ `--verbose-tags` shows lot postings' `ptype` tags (acquire, dispose, transfer-from, transfer-to, gain).++ - `-B/--value=cost` converts lot postings at their cost basis, so for lot balances it shows the cost of the units still held, and `bse -B` balances.+ `--value=transacted` gives the old `-B` behaviour (proceeds and net cash invested). `--gain` shows value minus cost basis.+ ([#2751])++ - The `lots` check which validates lot movements, usually run by default, can also be run by `hledger check lots`.+ Lot errors show the entry as written, how hledger interpreted its postings, and eg the lots actually available.+ Balance assertions on lot subaccounts can't be checked reliably, and are ignored when lot detail is hidden; the manual explains.++ See "Lots and capital gains" in the manual, and <https://hledger.org/start-tracking-lots.html>.+ ([#2581], [#2636], [#2649], [#2724], [#2731], [#2839], [#2843], [#2866])++### Holdings++- The new `holdings` report shows your lot-tracked investments' performance, per account and commodity, or per lot (`--lots`),+ with units, unit/average cost, current price, total cost and market value, portfolio weight, unrealised and realised gains (UGain, RGain), age,+ and XIRR annualised return. Multiple cost and value commodities are shown separately, or converted to one with `-X COMM`.++ - In tree mode, accounts with subaccounts or several commodities are heading rows showing their subtree's totals.+ (Arthur Cinader, [#2779])+ - With a report interval (eg `-M`), it shows the totals at each period end, up to today, titled eg "Monthly holdings";+ `--change`, `--cumulative` or `-H` select whether the gain columns show gains during each period, since the report start,+ or since acquisition (the default).+ - When the report period has a start date (`-b`, `-p`, `date:`), the gain columns show the gains during the report period.+ Eg `hledger holdings -p today` shows today's gains.+ - When some holdings have no market price, the totals show the others' value and gains, and a note names the ones excluded.+ - When closed positions (fully disposed commodities or accounts) are hidden, as they are without `-E`,+ a note says how many, since the RGain and XIRR totals include them.+ - `balance:` and `change:` queries can select holdings by units, value, or (with `-B`) cost, eg `holdings balance:'>$1000'`.+ - `-S/--sort-amount` sorts holdings by Total value, largest first, with unpriced holdings last (or with `-B`, by Total cost).+ - With colour, gains are green and losses red.+ - It has csv, tsv, html, fods and json output, and can show charts.++## Reporting++### Queries++- A new "find anywhere" query, written `find:PATTERN` or `::PATTERN`, matches a regular expression in any of a transaction's fields+ (code, description, comment, tags including hidden and inherited ones, account name, or amount);+ and if PATTERN is a period expression, it also matches dates in that period.+ This allows many queries to be written more briefly, especially when you're not sure where some text might be.+ Eg `::2025 ::food` matches things in 2025 (or mentioning "2025") and mentioning "food".++- `amt:` can now include a commodity symbol, to compare only amounts in that commodity: `amt:'>$100'`, `amt:'<200 EUR'`.+ This is easier than adding a `cur:` term, which needs regular expression escaping (`cur:'\$' amt:'>100'`).+ The manual is also corrected: `amt:` without a commodity symbol matches multi-commodity postings if any of its amounts match.++- `any:` and `all:` queries now also work in posting-oriented reports like register, balance and aregister;+ previously they had an effect only in commands which show whole transactions, like print.+ So those reports can now select postings based on their siblings: eg `hledger balance expenses any:cash` shows expenses which were paid with cash.++- Queries like `desc:` or `::`, with an empty pattern, now match anything. (Previously they gave an error.)+ `date:` query parse errors now show the actual error.++- `accounts` now respects transaction-specific query terms such as `date:`, `status:`, `desc:`; these no longer match a declared but unused account.+ (Only `acct:`, `depth:`, `type:` or `tag:` can match one.)+ `payees` likewise; and `payee:` now matches declared payees.++- New `change:` and `balance:` query types match report rows by their summed amounts,+ unlike `amt:` which matches individual posting amounts.+ `change:` tests a row's change (the sum of its postings);+ `balance:` tests its historical balance at the end of its period.+ Eg:++ hledger bal expenses change:'>+100' # expense accounts where more than 100 was spent+ hledger bal assets balance:'<0' # asset accounts with a negative balance+ hledger reg gifts -M change:'>100' # months with more than 100 in gifts+ hledger areg checking balance:'<0' # transactions after which checking was overdrawn+ hledger print not:change:0 # entries with a tolerated imbalance or unbalanced virtual postings++ As with `amt:`, a commodity symbol (`change:'>$100'`, `balance:'<0 EUR'`) compares just that commodity.+ And an unsigned number tests the magnitude, ignoring sign (so `change:'>100'` also matches a change of -150),+ while a signed number (or 0) does a signed comparison (eg `change:'>+100'`, `balance:'<-500'`).+ Amounts are tested with their real sign, as shown by `balance` (not the adjusted sign shown by `--invert` or `bs`/`cf`/`is`).+ `balance:` always means the historical balance, ie calculated from the start of the journal (with or without `-H`).+ In balance reports, non-matching accounts are left out, as with an account query, so parent balances and totals include just the matching accounts.++### Reports++- A new `transactions` (`tx`) command lists transactions on one line each. It's like print, but better for a quick overview.++- `register` with no report interval now hides zero-amount postings unless `-E` (or `--average`) is used,+ like register with a report interval, or aregister.+ ([#2836])++- `balance` has a new `--full-names` flag, which in tree mode shows full account names;+ `--no-elide` now also works in list mode, adding the parents of the posted-to accounts;+ and a new `barewide` layout shows bare numbers with a column for each commodity.+ (Henning Thielemann, [#2429], [#2661])++- `aregister` now supports `-A/--average`, showing the running average change per transaction instead of the running balance;+ and a new `--matched` flag, which shows the matched account(s) in each row instead of the other account(s) (the opposite of `-r/--related`).+ (Caleb Maclennan, Simon Michael, [#2540])++- Report titles can be customised: `--title=TITLE` sets a title for most reports (in txt, html or fods output),+ `--subreport-titles='TITLE1|TITLE2|...'` sets the section titles of compound reports like `balancesheet` (eg `--subreport-titles='Aktiva|Passiva'`),+ and `--period-titles=compact|dates` selects abbreviated or full ISO dates as column headings in periodic reports.+ ([#2578])++- HTML output is improved: with `--base-url`, every balance report amount links to the corresponding register view, so you can click to see+ where an amount comes from; CSS classes are used instead of inline styles, with classes for negative amounts, amounts, dates, and tree depth;+ dates and amounts don't wrap; a `hledger.css` file now overrides the builtin styles (an example is provided);+ register, aregister and holdings show a title too; and there are newlines between elements, for readability.+ (Arthur Cinader, Simon Michael, [#2326])++- The `commodities`, `tags` and `payees` commands have a `--directives` flag, which shows directives ready to paste into a journal.+ (Use it with `--undeclared` to generate directives satisfying strict mode.)++- `commodities --used` now shows only commodities used in transactions; a new `--priced` flag shows commodities used in P directives.+ `commodities` now supports `date:` queries (and report period options) with these, and `tag:` queries.++- `prices` has a new `--summary` mode; a `--locations` flag, showing where each price came from;+ `--show-aliases`, showing the rates implied by commodity aliases; and it can be filtered by `find:` queries.++- Repeating the `--transpose` flag now toggles it. In `--pivot`'s value, `account` is accepted as a synonym for `acct`.+ A two-year interval's report title now says "Biennial", not "Biannual" (Arthur Cinader).++- Fixed, in balance: multi-period reports using `--tree` and `--transpose` together now show only the leaf accounts ([#1941], JoeJoeflyn);+ in single-period csv/tsv/html/fods output, `--drop` no longer truncates the "Total:" heading ([#2688]);+ single-period HTML/FODS reports respect the commodity display style (Simon Michael, Henning Thielemann, [#2584], [#2588]);+ FODS multi-period and compound reports have the correct number of header columns (Henning Thielemann);+ and in single-period text reports, account names stay aligned when amounts are wide (Adam Sardo, [#1148]).++- Fixed, in register: with a report interval, account-specific depth limits (`--depth REGEXP=N`) now work correctly ([#2423]);+ with multiple files, the transaction indexes in csv/tsv/fods/html/json output continue across files instead of restarting;+ and postings whose amount couldn't be inferred are omitted ([#2571]).++- Fixed, in aregister: with historical balances, a `date2:` start date in the query is now honoured (Arthur Cinader).++- Fixed: `balance --budget` reports no longer lose their goals when the command includes transaction or posting filters,+ such as `status:`, `desc:` or `--cleared`. Only the attributes that meaningfully select goals (account, account type, depth, date, commodity) affect them.+ So `bal --budget --cleared` compares cleared spending against the full goals.+ ([#2545])++- Fixed: `--count` reports showed counts in the journal's no-symbol commodity style (eg 1.00), rounded their averages to whole numbers,+ and bs/bse/is showed negative counts in some sections. Now counts are whole numbers, averages have one decimal place,+ and bs/bse/is show positive counts in every section, with their sum as the net total.++- Fixed: `--value=WHEN,` with nothing after the comma now values in the no-symbol commodity (previously it was read as `--value=WHEN`).+ `-X` and `--value` also accept a double-quoted commodity symbol, so `""` also selects the no-symbol commodity.+ And `-X`/`--value` with a commodity to which no conversion price can be found now prints a warning, instead of silently having no effect.+ ([#2844])++- Fixed, in stats: the elapsed time and txns/s figures once again cover the whole run (since 1.51 they covered only the journal-reading phase).+ `--oneline` (formerly `-1`) has a `-q` short spelling, and it and `-1`/`--depth 1` now work independently.+ stats is faster on large journals, and shows a base currency inferred for the journal, eg `$ (USD)`.++- Fixed: roi's TWR is now computed from the investment's value at the end of each day, exactly, at daily granularity.+ The previous method assumed an exact valuation was available around each cash flow, and its solving could fail.+ Results change for most journals with cash flows between valuations; if you record valuations only occasionally+ (eg with `--pnl` transactions), record one around large deposits and withdrawals.+ Also, cash flows are now measured from the investment's perspective (other postings in the transaction, eg fees, no longer affect them),+ a holding without a market price is valued at the price of its latest purchase or sale, the value at the end of a period uses the prices of its last day,+ and `--cashflow` shows each cash flow and the TWR steps, for checking the results. These can change IRR results too. See the roi docs.+ (Dmitry Astapov, [#2420], [#2824], [#2825])++- Fixed: in roi, a failed IRR or TWR now shows "error" in its own cell, with the rest of the report still shown,+ and the reasons shown as a warning after the report (with exit status 0).+ Some special cases now have an answer instead of an error: when money is put in and nothing comes back (eg a write-off), IRR is -100%,+ and same-day cash flows that add up to zero have an IRR of 0%.+ And omitting `--pnl` now selects no postings, as documented; previously it selected all postings.+ (Dmitry Astapov, Arthur Cinader, [#2670], [#2845])++### Charts++- hledger now has easy charting built in. Most reports can be shown as charts, with `--chart`.+ In the terminal, these are bar charts, using colour and Unicode block characters when supported.+ Charts adapt to the report options and data, showing subperiods, stacked bars, end balances,+ contra amounts hatched, largest amounts prioritised, totals/averages, etc. Each commodity gets its own chart.+ If csv, tsv or json output is selected, the chart's data is shown instead.++- When colour is available, accounts are coloured by type: assets blue, liabilities amber, equity violet, revenues green, expenses red,+ with each account of a type in a different shade. Accounts of unknown type get distinct colours.++- `--view` opens a report in the system's default viewer for its format.+ It writes an output file if you didn't specify one (in hledger's cache directory), choosing html format if you didn't specify that.+ Eg `hledger is -M --chart --view`, or `hledger is -M -o is.fods --view`.++- Charts can also be SVG images, with tooltips and light/dark variants, selected by the new svg output format (`-O svg` or `-o FILE.svg`).+ Or, SVG charts can be added to html reports (`-o FILE.html --chart`).+ (Simon Michael, Arthur Cinader)++- In compound reports like bs and is, all accounts are stacked in one bar per period, on opposite sides of the axis (the diverging layout);+ `--chart=grouped` shows each section's accounts in a bar of their own, side by side, as `balance --chart=grouped` does for each account type.+ `--chart=net` also draws the net total. `--chart=SCALE` (eg `--chart=5000`) draws charts at a fixed scale,+ so that separate charts can be compared. These can be combined, eg `--chart=grouped,net,5000`.++- `holdings` has a chart, showing a horizontal bar per holding (or lot) with its cost basis, unrealised gain or loss, and gain percentage;+ or with a report interval, the cost basis and value per period (or with `--change` or `--cumulative`, the gains).+ `activity` now shows a chart of transactions per week, using the new chart engine; `--postings` counts postings, per account.+ It now supports `-w/--width`, `-S`, `-T`, `-A`, and svg, html, csv, tsv and json output.++### print, exporting++- `print` now aligns posting amounts at their decimal marks. The target column is 53; it is increased when needed.+ Balance assertions' operators and amounts are aligned too.+ A new `--layout` option (also supported by `add`, `close`, `import`, `rewrite`) customises this:+ `--layout=COL` sets a different target column, and `--layout=hledger1` gives hledger 1's layout.++- In `print`'s csv/tsv/html/fods/sql output, the debit column now appears before the credit column, following convention.+ In `aregister`'s csv/tsv/html output, the "change" column is renamed "amount", matching print's, for easier re-importing.++- `print --export` reproduces the whole journal losslessly, preserving directives, comment lines and blank lines,+ for easier reformatting or exporting. Included files are inlined.+ With `--forecast` and/or `--auto`, the generated transactions and postings are exported instead of their rules.++- `print` has a new `ledger` output format (`-O ledger` or `-o FILE.ledger`), which uses Ledger's lot syntax,+ and with `--export`, comments out directives which Ledger does not support. Its default format is now called "journal" ("txt" is still accepted).++- `print`'s beancount output is improved. With `--export`, it generates the directives Beancount needs (options, commodity, open, prices),+ and accounts whose top-level name is not one of Beancount's are prefixed with one based on their account type, if known.+ It converts single-letter commodity symbols, the no-symbol commodity, top-level "revenue(s)" accounts, balance assignments and market prices;+ it sets booking methods from accounts' `lots` tags, and shows cost basis before transacted cost;+ underscores in account names become dashes rather than being hex-encoded ([#2596]); and non-ASCII letters in tag names are encoded ([#2576]).++- `rewrite --diff` output can now be applied by `patch` or `git apply`: each source file is diffed as a whole, with three lines of context.+ And changed transactions which have no journal entry to patch (eg ones read from CSV) are left out of the diff and reported on stderr.+ ([#2548])++### Other commands++- `setup` detects terminal colour support and explains its verdict; warns if the filesystem does not support appending ([#2577]);+ checks for Gain accounts; no longer reports unused commodity aliases as undeclared; and no longer shows an error message on Windows.++- `check`: an unknown check name is now reported right away, instead of after reading the journal.+ `check ordereddates` with `--forecast` now ignores forecast transactions.++- `accounts --show-aliases` shows each account's aliases, as a comment, and makes account name queries also match aliases.+ `accounts --locations` now also shows where undeclared accounts were first used, and shows locations as FILE:LINE.+ When `check accounts` finds an undeclared account name which is an account alias not in effect there, the error explains alias scope.++- `close` no longer generates a spurious zero posting for some emptied accounts.++## Performance++- hledger has been optimised, and this is the fastest and most memory-efficient version yet.+ On medium and large journals, `balance` is 2-3x faster than 1.52, and uses a third less memory.+ Unnecessary work is avoided, so you pay only for the features you are using.+ Detailed stats, performance tips, and a new set of benchmarks comparing the plain text accounting apps, are at <https://hledger.org/PERFORMANCE.html>.++- Interval reports no longer slow down quadratically with the number of periods (a daily register over 100 years spent 2.5s in that alone),+ and register and `--forecast` use constant memory however many periods there are.+ ([#1683])++- Regex replacement no longer takes quadratic time in the length of the text; long texts (eg regex aliases on 2000-character account names) are much faster.+ check accounts, check payees and check tags are faster with many declarations (eg 0.63s -> 0.20s with 10k transactions and 10k declared accounts).+ Journals with many balance assertions or quoted commodity symbols are parsed faster, journals with lots are processed faster,+ and tables with many-line cells (eg register with a many-commodity running balance) are rendered faster (Dmitry Astapov).++- hledger no longer searches PATH for add-ons when the command is a builtin command, for faster startup (eg `hledger --version` takes 23ms instead of 32ms).++- hledger release binaries are built with megaparsec 9.8.3, which contains our fix for a performance regression in megaparsec 9.3 to 9.8.2,+ making hledger about 10% faster. Packagers who want the speedup should use megaparsec 9.8.3+.++- `--debug=1` now prints a timing line for each phase of hledger's work, with its run time and allocation,+ and shows how much of the journal was parsed by the new fast-path parser.++## Other++### Packaging and API++- hledger now requires aeson 2.2.5.1 or newer, avoiding a bug where certain data could trigger memory/CPU exhaustion+ (<https://haskell.github.io/security-advisories/advisory/HSEC-2026-0007.html>).+ megaparsec 9.8.0 is excluded, to avoid a position marker bug in error messages ([megaparsec#572](https://github.com/mrkkrp/megaparsec/issues/572)).+ hledger no longer depends on lucid; blaze-html is used for HTML output (Arthur Cinader, [#2737]).++- hledger's source tarball no longer ships the benchmark suite's 1.6MB journal.++- Haskell API changes in the hledger package: Hledger.Cli.Anchor gains LinkOpts and link builders;+ Balance exports its report specs, spreadsheet parts and titles, with shared functions in Balance.Internal;+ balanceReportAsText returns Text; setDisplayCommodityBare's parameters are swapped;+ Hledger.Cli.Xirr is the IRR solver shared by roi and holdings.+ (Henning Thielemann, Arthur Cinader, Dmitry Astapov)++### Examples++- examples/file-layouts (formerly examples/templates) has simple, default, years and year-dirs layouts; `hledger init` writes the first three.+- examples/lots/ has lot tracking examples: lots.journal, irr.journal (comparing roi and holdings XIRR),+ and investments-5y.py, which generates a large investment journal.+- examples/csv/ has new rules for PayPal (json), Kraken (demonstrating `merge`), SimpleFIN, Unify Federal Credit Union and GitHub sponsorships.+- examples/home-page-example.journal is the example from the hledger.org home page.+- hledger.conf.sample is updated, with command-listing helpers and a custom `watch` command.+- bcexample's beancount prices are converted to P directives, so `-V` works.+- examples/hbcexample.journal is a copy of bcexample.journal with current dates and valid hledger 2 lot entries.++### Scripts/addons++- `getdata` and `getprices` are sample scripts for the `get` command; `krakencsv` helps convert Kraken CSV.+- `git-pre-commit-hook` is an example git hook which runs `hledger check` on your journal when its files are being committed.+- `hledger-bar` allows its flags anywhere among the arguments, and sets the scale with a new `-s` option.+- hledger-check-fancyassertions is removed, replaced by assert rules. The hledger-example* scripts are renamed and updated.+- bashrc: holdings and tx aliases.++### Docs++- The hledger manual is reorganised, with more getting started info at the start; Options and Config files consolidated;+ COMMANDS moved before DATA FORMATS, and grouped like the commands list; detailed command line tips moved to PART 5;+ and a shorter, better grouped topic list in the website sidebar.+- New sections include: Lots and capital gains (with Recording disposals, Troubleshooting lots and more), Charts, Languages,+ Amount expressions, Commodity aliases, the assert directive, Transaction balancing, Report titles, print layout, Built-in tests,+ and hledger 1 and hledger 2 (on migrating and interoperating).+- The CSV docs are reorganised, with clearer explanations of reading the data, finding the data, CSV vs hledger fields, if rules and ifs tables,+ and rules examples moved into Working with CSV.+- Directives, the alias directive, account aliases, directive scopes and combining file trees are explained more clearly; timedot is rewritten;+ Tags, Boolean queries, the two-space delimiter, decimal marks and period expressions are clarified.+ ([#1640], [#1950], [#2664], [#2665], [#2714])+- The "added in VERSION" and "experimental" labels are dropped throughout the manuals.++[#273]: https://github.com/hledgerorg/hledger/issues/273+[#1148]: https://github.com/hledgerorg/hledger/issues/1148+[#1489]: https://github.com/hledgerorg/hledger/issues/1489+[#1640]: https://github.com/hledgerorg/hledger/issues/1640+[#1683]: https://github.com/hledgerorg/hledger/issues/1683+[#1738]: https://github.com/hledgerorg/hledger/issues/1738+[#1904]: https://github.com/hledgerorg/hledger/issues/1904+[#1941]: https://github.com/hledgerorg/hledger/issues/1941+[#1950]: https://github.com/hledgerorg/hledger/issues/1950+[#1985]: https://github.com/hledgerorg/hledger/issues/1985+[#2326]: https://github.com/hledgerorg/hledger/issues/2326+[#2413]: https://github.com/hledgerorg/hledger/issues/2413+[#2420]: https://github.com/hledgerorg/hledger/issues/2420+[#2423]: https://github.com/hledgerorg/hledger/issues/2423+[#2429]: https://github.com/hledgerorg/hledger/issues/2429+[#2489]: https://github.com/hledgerorg/hledger/issues/2489+[#2537]: https://github.com/hledgerorg/hledger/issues/2537+[#2539]: https://github.com/hledgerorg/hledger/issues/2539+[#2540]: https://github.com/hledgerorg/hledger/issues/2540+[#2545]: https://github.com/hledgerorg/hledger/issues/2545+[#2548]: https://github.com/hledgerorg/hledger/issues/2548+[#2571]: https://github.com/hledgerorg/hledger/issues/2571+[#2576]: https://github.com/hledgerorg/hledger/issues/2576+[#2577]: https://github.com/hledgerorg/hledger/issues/2577+[#2578]: https://github.com/hledgerorg/hledger/issues/2578+[#2581]: https://github.com/hledgerorg/hledger/issues/2581+[#2584]: https://github.com/hledgerorg/hledger/issues/2584+[#2588]: https://github.com/hledgerorg/hledger/issues/2588+[#2596]: https://github.com/hledgerorg/hledger/issues/2596+[#2636]: https://github.com/hledgerorg/hledger/issues/2636+[#2645]: https://github.com/hledgerorg/hledger/issues/2645+[#2646]: https://github.com/hledgerorg/hledger/issues/2646+[#2648]: https://github.com/hledgerorg/hledger/issues/2648+[#2649]: https://github.com/hledgerorg/hledger/issues/2649+[#2656]: https://github.com/hledgerorg/hledger/issues/2656+[#2661]: https://github.com/hledgerorg/hledger/issues/2661+[#2664]: https://github.com/hledgerorg/hledger/issues/2664+[#2665]: https://github.com/hledgerorg/hledger/issues/2665+[#2670]: https://github.com/hledgerorg/hledger/issues/2670+[#2688]: https://github.com/hledgerorg/hledger/issues/2688+[#2696]: https://github.com/hledgerorg/hledger/issues/2696+[#2714]: https://github.com/hledgerorg/hledger/issues/2714+[#2719]: https://github.com/hledgerorg/hledger/issues/2719+[#2724]: https://github.com/hledgerorg/hledger/issues/2724+[#2731]: https://github.com/hledgerorg/hledger/issues/2731+[#2733]: https://github.com/hledgerorg/hledger/issues/2733+[#2736]: https://github.com/hledgerorg/hledger/issues/2736+[#2737]: https://github.com/hledgerorg/hledger/issues/2737+[#2751]: https://github.com/hledgerorg/hledger/issues/2751+[#2756]: https://github.com/hledgerorg/hledger/issues/2756+[#2772]: https://github.com/hledgerorg/hledger/issues/2772+[#2779]: https://github.com/hledgerorg/hledger/issues/2779+[#2824]: https://github.com/hledgerorg/hledger/issues/2824+[#2825]: https://github.com/hledgerorg/hledger/issues/2825+[#2836]: https://github.com/hledgerorg/hledger/issues/2836+[#2839]: https://github.com/hledgerorg/hledger/issues/2839+[#2843]: https://github.com/hledgerorg/hledger/issues/2843+[#2844]: https://github.com/hledgerorg/hledger/issues/2844+[#2845]: https://github.com/hledgerorg/hledger/issues/2845+[#2852]: https://github.com/hledgerorg/hledger/issues/2852+[#2856]: https://github.com/hledgerorg/hledger/issues/2856+[#2857]: https://github.com/hledgerorg/hledger/issues/2857+[#2858]: https://github.com/hledgerorg/hledger/issues/2858+[#2862]: https://github.com/hledgerorg/hledger/issues/2862+[#2866]: https://github.com/hledgerorg/hledger/issues/2866+[#2869]: https://github.com/hledgerorg/hledger/issues/2869+++# 1.52.4 2026-09-10++Improvements++- Allow megaparsec 9.8.1+ (but not 9.8.0, because of [megaparsec#572](https://github.com/mrkkrp/megaparsec/issues/572)).++Docs++- csv: the manual now correctly documents that most top-level rules are evaluated first-wins, not last-wins as previously stated. + (Accepting the status quo, unlike hledger 2.x where they are changed to last-wins.) [#2539]++[#2539]: https://github.com/hledgerorg/hledger/issues/2539++# 1.52.3 2026-08-27++# 1.52.2 2026-08-24++# 1.52.1 2026-04-28++Breaking changes++- The `Gain` (`G`) account type is no longer auto-detected from account names like+ `revenue:gains` or `income:capital gains`; it must now be declared explicitly with `; type: G`.+ Also, the `UnrealisedGain` (`U`) account type, a subtype of Equity, has been added+ (spellings `U`, `UnrealisedGain`, and `UnrealizedGain` are all accepted).+ These improve compatibility between hledger 1 and 2.++Docs++- The "Cost basis / lot syntax" section has been renamed to "Cost basis",+ and updated to mention hledger 2.++# 1.52 2026-03-20++Features++- `aregister` and `register` now support `--drop` for trimming leading account name components,+ like the `balance` command.+ (Caleb Maclennan)++- `print` now preserves and reproduces Ledger-style lot syntax (cost basis annotations) in text and json output,+ and (converted to Beancount syntax) in beancount output.++- Tags can now be declared on commodities, and you can query for postings by their commodity's tags.++- A new `Gain` (`G`) account type has been added, as a subtype of Revenue.+ Account names matched by `^(income|revenue)s?:(capital[- ]?)?(gains?|loss(es)?)(:|$)`+ are auto-detected as Gain type.+ (Some examples: revenue:gains, income:capital-gains, income:losses.)+ This provides a language-independent way of matching capital gain/loss accounts specifically.+ (It is used more in hledger 2.)+ (g. nicholas d'andrea) [#2522]++Fixes++- The `add` and `import` commands once again read all `-f` files, not just the first. + This fixes a regression in 1.51.2 which broke autocompletion in `add`,+ and multi-file reading in `import`, when multiple `-f` options were given.+ [#2553]++- In balance reports, accounts revealed by `--empty --declared` now respect account display order, instead of being shown last.+ (Juliano Solanho) [#2564]++- `balance --budget`'s csv/tsv output now properly suppresses digit group marks (eg thousands separators),+ preserving valid CSV structure.+ [#2555]++- The `run` command now properly returns a non-zero exit code if there's an error while commands are being provided on standard input.+ (Previously it always returned exit code 0 in this mode.)+ [#2557]++- Options requiring a value (like `--round` or `-f`) now give a clear error if the value is missing+ (rather than trying to consume a following flag).+ [#2556]++- Postings generated by `--infer-equity` no longer inherit the source posting's tags, comment, or real/virtual type.+ (The posting's date and status are still inherited.)+ [#2535]++Improvements++- When converting to value, price lookups are now optimised with pre-built indexes. + This replaces O(n log n) re-sorting on every valuation date with O(log n) indexed lookups,+ significantly improving performance for `--value=end,COMM` with daily reports+ over long periods and large price databases.+ (Oleg Bulatov) [#2511]++- `date:` queries can now include a report interval, eg `date:weekly` or `date:'weekly from last month'`,+ like the `-p/--period` option.++- Smart dates now understand `last|this|next WEEKDAY` and `last|this|next MONTHNAME`.++- When `add` or `import` are autocreating a requested journal file that did not exist,+ they will also create any required parent directories.++- The less pager is now invoked more robustly; we catch and report more kinds of failure clearly,+ and/or fall back to unpaged output with a warning.+ [#2544]++- The `--quit-at-eof` flag is no longer added when running the less pager (and our less flags are better documented).++- Improvements to the `setup` command:+ - improve top info's layout+ - show the OS version, architecture, and compiler version+ - show if hledger is wrongly built without OS thread support+ - show the value of $LESS more accurately+ - test that it runs with the configured options+ - print a warning before making a http request+ - show more compact output if the http request fails++Docs++- Account tags: new separate section+- COMMON TASKS: Setting LEDGER_FILE: updates+- Cost basis / lot syntax: new section and edits+- Costs: rewrite+- csv: if: field matchers: clarify+- Inferring equity conversion postings: note account tags limitation+- journal: code: mention valid characters, recommend tags [#2563]+- Regular expressions: note no lazy quantifiers+- Tag names: clarify --verbose-tags++Examples++- csv: Fidelity, Open Collective updates+- csv: Interactive Brokers example CSV rules files [#2508] (Ilja Kocken)+- csv/cctax: notes and sample files related to exporting to cryptocurrency tax calculators+- debconf: DebConf ledger files 2017-2025, adapted for hledger+- investing/export-lots-workflow: doc and examples for exporting to Beancount, Ledger or rustledger for lots/gains calculation++Scripts/addons++- bashrc: drop clashy month aliases; fix LEDGER_FILE typo; cleanup.+- fix compilation errors in bin/ scripts (Dmitry Astapov) [#2497]+- `hledger-smooth`: accept ACCTPAT, matching case-insensitively as infix (like `aregister`).+- `hledger-fancyassertions`: use `showMixedAmount` for properly formatted output. (Joshua Chapman)+- `ledgereval`: evaluate Ledger value expressions at the command line++[#2508]: https://github.com/hledgerorg/hledger/issues/2508+[#2511]: https://github.com/hledgerorg/hledger/issues/2511+[#2522]: https://github.com/hledgerorg/hledger/issues/2522+[#2535]: https://github.com/hledgerorg/hledger/issues/2535+[#2544]: https://github.com/hledgerorg/hledger/issues/2544+[#2553]: https://github.com/hledgerorg/hledger/issues/2553+[#2555]: https://github.com/hledgerorg/hledger/issues/2555+[#2556]: https://github.com/hledgerorg/hledger/issues/2556+[#2557]: https://github.com/hledgerorg/hledger/issues/2557+[#2563]: https://github.com/hledgerorg/hledger/issues/2563+[#2564]: https://github.com/hledgerorg/hledger/issues/2564++# 1.51.2 2026-01-08++Fixes++- The `add` and `import` commands now once again auto-create the journal file+ if it does not exist yet, fixing a regression in 1.50.3.+ Also they now create it lazily, only when they have data to write,+ not unconditionally at the start.+ [#2514]++- The `roi` command has some more sanity checks, and some error messages+ have been clarified.+ (Dmitry Astapov, [#2505])++Improvements++- The `-f` option now reports an error if you give it a glob pattern+ (a path containing `[`, `{`, `*`, or `?`) that matches nothing.+ This makes it consistent with `LEDGER_FILE`.++- Journal format's `include` directive no longer unnecessarily reads+ the attributes of all files in a directory. This works better with+ build tools like tup which detect filesystem operations.++- Journal format's `include` directive has been optimised,+ repairing a slight slowdown introduced in 1.50.3.+ It no longer calls `canonicalizePath` unnecessarily.+ This might be noticeable with many includes on a slow filesystem.++- Allow base 4.22 / ghc 9.14.++API++- Hledger.Cli.Utils:+ withPossibleJournal++[#2505]: https://github.com/hledgerorg/hledger/issues/2505+[#2514]: https://github.com/hledgerorg/hledger/issues/2514++# 1.51.1 2025-12-08++Fixes++- Relative includes from a symbolically-linked journal file now work again.+ This was fallout from 1.50.4's fixes.+ [#2503]++- When journal's include directive has an IO error, like trying to+ include an existing but unreadable file, or failing to find a home+ directory when expanding ~, it now shows the problematic include+ directive (previously the line number was off by one).++- `aregister`: respect the order of -f options when showing same-day transactions from multiple files.+ If transactions on the same date are coming from two files specified+ with -f options, we expect them to be displayed in parse order, ie+ respecting the order of the -f options. This wasn't always the case,+ now it is.++- `aregister`: show "ACCTPAT matches no account" error on just one line.++- Fix build failures with the scripts in bin/.+ (Dmitry Astapov, [#2497])++[#2503]: https://github.com/hledgerorg/hledger/issues/2503+[#2497]: https://github.com/hledgerorg/hledger/issues/2497++# 1.50.5 2025-12-08++Fixes++- Relative includes from a symlinked file work again, fixing some fallout from 1.50.4's fixes.+ [#2503]++[#2503]: https://github.com/hledgerorg/hledger/issues/2503++# 1.51 2025-12-05++Breaking changes++Fixes++- HTML output no longer contains invalid nested tables (Joschua Kesper). This may cause some visual changes, hopefully all for the better.+- `stats`: `-o` now redirects all output, including the performance stats.++Features++- `commodities`, `payees` and `tags` commands now have a `--find` mode for finding the best match (like the `accounts` command).+- `stats`: A new `-1` flag prints a single line of output in machine-friendly tab-separated format, including the program version, journal file name, and performance stats.++Improvements++- In journal format, an empty `{}` pair is now allowed (and ignored) in amounts, slightly improving Ledger/Beancount compatibility.+- `accounts` in `--tree` mode, when showing a subset of accounts, now shows parent accounts for context, like the `balance` command.+ (Sam Almahri, [#2427])+- `accounts --types` no longer shows value-less type tags; untyped accounts are shown without a `type` tag.+- When pivoting on account type with `--pivot=type`, account types will be normalised to their short spelling (`A` instead of `Assets`, etc).+- `accounts`: the `--positions` flag has been renamed to `--locations`.+- `print`: the `--location` flag has been renamed to `--locations`.+- `setup`: tidier output for missing LEDGER_FILE or default file; wording improvements++Docs++- Account names: rewrite, emphasise the two space delimiter+- accounts: improve/sync options order+- add: balance assertions/assignments: clarify, fix [#2494]+- aregister: clarify arguments+- argument files: corrections+- check: drop obsolete note about transaction balancing+- close: customisation: clarify [#2492]+- commodity directive: add info about the -c command line option (Ooker)+- COMMON TASKS: demote subheadings+- csv: "CSV fields and hledger fields"; "Regular expressions in CSV rules"; link the `if`-specific `skip` and `end` rules more clearly+- depth: rewrite, note combining issue+- Editor configuration -> Editors+- print: clarify amount styling; note more parseability breakers+- Setting LEDGER_FILE: rewrite, new windows procedures+- Special characters: rewrite (Simon Michael, Caleb Maclennan, [#2468])+- Tags: rewrite [hledger_site#141]+- Value reporting: more advice, examples for COMM, warn about -V/emphasise -X++Examples++- Organise/rename examples/csv/ as the [CSV rules library](https://github.com/hledgerorg/hledger/tree/master/examples/csv)++Scripts/addons++- `hledger-check-buynothing`: check Buy Nothing Day compliance+- `hledgerj1`: example of a wrapper for reading a custom data format+- `sortandmergepostings`: Overhaul for more robust determinism (Caleb Maclennan)+ - Avoids non-deterministic flip-flopping when the alphabetical account sort has multiple commodities+ - Sorts postings commodities so commodities are in the same order across transactions+ - Sorts postings with matching commodity by posting amount++API++- Hledger.Cli.Utils:+ - stop exporting pivotByOpts, anonymiseByOpts+ - renamed withJournalDo -> withJournal. The old name is still available but deprecated.++# 1.50.4 2025-12-04++Fixes++- An `include` directive with no argument now gives consistent error messages.++- journal format's `include` directive no longer excludes paths containing dotted directories/files.+ 1.50-1.50.3 contained an overzealous workaround that sometimes wrongly excluded paths containing a dot dir or dot file.+ Now the pre-1.50 behaviour is restored+ (`*` and `**` generally avoid dot files and dot directories, except `**` will search non-top-level dot directories).+ [#2498]++- Symbolic links found by `include` directives are once again shown as-is, not dereferenced.+ (1.50-1.50.3 showed them dereferenced, eg in `hledger files` output.)++ There is some related new behaviour: each time an include directive is parsed,+ all the parent file paths and the new include file path(s) are re-canonicalised.+ Previous hledger versions did not do this; it's expected to be unnoticeable,+ but if you notice any slowdown caused by having many include directives and a slow filesystem,+ please report it.++[#2498]: https://github.com/hledgerorg/hledger/issues/2498++# 1.50.3 2025-11-18++Fixes++- hledger versions 1.50-1.50.2 ran much slower than normal (depending on the speed of your hard drive).+ This 1.50.3 release fixes that; so please upgrade, and avoid those older 1.50 releases.+ [#2493]++- A regression in 1.50, where very large dates could produce wrong reports, has been fixed.+ (Affecting dates outside the range -25252734927764696-04-22..25252734927768413-06-12+ on 64 bit machines, or -5877752-05-08..5881469-05-27 on 32 bit machines.)+ [#2479]++- If the `LEDGER_FILE` environment variable is set to a nonexistent file, we now report an error+ rather than silently falling back on a default file path, which was confusing.+ Also, we no longer support the legacy `LEDGER` environment variable as a fallback.+ [#2485]++- `setup` now shows tidier output when a LEDGER_FILE or default file is not found,++- `add` now checks balance assertions more robustly, with awareness of how everything is ordered in the journal.+ Also, it now allows adding balance assignments.+ [#2478]++- `check accounts` no longer garbles non-ascii account names in its output.+ [#2469]++- We now escape special characters properly when passing arguments to addons+ (with just one level of quoting/escaping, not two).+ And related docs have been improved.+ (Caleb Maclennan, Simon Michael, [#2468])++- Internal report code which could produce certain date-related errors has been made robust again.+ (Stephen Morgan)++- The old "threaded" build flag, which cabal could turn off, has been dropped.+ This will hopefully prevent wrong builds like Debian's #1120833.+ [#2495]++- Docs updated: add, areg, argument files, check, close, csv, depth, print, print, Special characters, Value reporting++# 1.50.2 2025-09-26++Fixes++- The CSV `encoding` rule is now respected when using the rules file as input file. This was a regression in 1.50.+ Also, the text decoding error message has been clarified; it now mentions a possible CSV encoding.+ [#2465]++- The doc for `--depth` has been clarified, and now mentions the use of quotes.+ (Lý Minh Nhật, Simon Michael, [hledger_site#140])++- A typo was fixed in the --depth example in `register`'s doc.+ ([hledger_site#140], reported by Lý Minh Nhật)++- Our package bounds now avoid hashtables 1.3.x, which fails to build with some gcc versions+ (see https://github.com/gregorycollins/hashtables/issues/97)).+ (hseg, [#2463])++[#2463]: https://github.com/hledgerorg/hledger/issues/2463+[#2465]: https://github.com/hledgerorg/hledger/issues/2465++# 1.50.1 2025-09-16++Fixes++- Balance commands now show an empty report instead of an error when+ no transactions are matched, fixing a regression in 1.50.+ (Stephen Morgan, [#2452])++- The `print` command's help no longer shows an unused --show-costs flag.+ And the command-specific flags are now mostly ordered alphabetically.++- Whitespace in the `setup` command's "undeclared commodities" output has been fixed.++Doc updates++- Text encoding+- bin/README: paypal\*, simplefin\* usage examples, doc link++API++- Hledger.Cli.Utils:+ add withJournal alias for withJournalDo,+ pivotByOpts -> maybePivot,+ anonymiseByOpts -> maybeWarnAboutAnon,+ stop exporting pivotByOpts, anonymiseByOpts++- Hledger.UI.ErrorScreen:+ uiReloadJournal -> uiReload,+ uiReloadJournalIfChanged -> uiReloadIfFileChanged++[#2452]: https://github.com/hledgerorg/hledger/issues/2452++# 1.50 2025-09-03++## Breaking changes++- Transaction balancing is now done in a more robust way, using local precisions only (like Ledger) [#2402].+ Until now, a transaction was required to balance using its commodities's global display precisions.+ Small imbalances were tolerated by configuring display precisions for the whole journal (with `commodity` directives).++ Now, a transaction is required to balance using the precisions in its journal entry only.+ This means each entry can use the precision it needs, and balancing precision and display precision are independent.+ (So eg, increasing the display precision with `-c` no longer breaks the journal.)++ In practice this requires journal entries to be more accurate, and you will probably need to fix some old entries.+ There are three main ways to fix an entry:+ - reduce the amounts' precision (use fewer decimal digits, so a lower balancing precision is inferred)+ - make the amounts more accurate (use better decimal digits, so the amounts sum to zero more closely)+ - or (easiest) add an amountless "expenses:rounding" posting (this is not a cheat, it's a more accurate record of what your bank/broker is doing).++ You can also keep the old transaction-balancing behaviour with `--txn-balancing=old`, for now.+ But updating your entries is recommended. ++ The old behaviour could allow small remainders to accumulate over time, + in accounts that often have an inexact posting amount or cost amount and are never reconciled -+ typically equity, revenues, and expenses.+ You can check for this in your old journals with a command like++ hledger bal cur:\\$ -c '$1.000000000000' | grep -E '\...0*[1-9]'++ (show $ account balances, with many decimals, which have a non-zero decimal in the 3rd place or beyond)+ +- Timeclock format has had various changes:+ - Timeclock syntax and parsing is now more robust (when not using --old-timeclock):+ - Semicolon always starts a comment (and timeclock account names may not include semicolons).+ - Trailing spaces are ignored.+ - Clock-ins now require an account name.+ - Clock-outs now can have a comment and tags.+ - Timeclock entries are processed in parse order.+ - Some order-related bugs in 1.43 have been fixed.+ - Concurrent/overlapping sessions are now fully supported, even if they have the same account name.+ - The timeclock doc has been rewritten.+ - The --old-timeclock hidden flag has been renamed, documented, and now also affects included files.+ [#2141], [#2365], [#2400], [#2417]++- The `import` command now shows info messages (such as the dry run "; would import .." message)+ on stderr, not stdout.+ Also the "no new transactions" output is more compact, showing file names not file paths;+ and it no longer prints an extra newline.++- Some edge cases in balance report behaviour were changed for internal consistency:+ - --declared now treats parent accounts consistently.+ - --flat --empty now ensures that implied accounts with no postings are not displayed,+ but accounts with zero balance and actual postings are.+ (Stephen Morgan, [#2360], [#2395])++- hledger now requires at least GHC 9.6 (and base 4.18), to ease maintenance.++## Fixes++- Paging long output no longer gives an error when `LESS` is undefined and+ `less` does not have mouse support (as on some FreeBSD systems).++- The `all:` query now requires at least one posting to match.+ (Previously, matching no postings at all was also considered a success.)++- When using journal format's `include` directive, several kinds of+ error (read failure, cyclic include..) could show an off-by-one line+ number or excerpt, confusingly. This has been fixed.+ Also, attempting to include a rules file now gives a better error message.++- In CSV `if` rules, match group references like `\1` no longer get confused+ by differing case.+ (Jay Neubrand, [#2419])++- `add`, `commodities`, and `diff` now support the --conf and -n/--no-conf flags,+ like other commands.+ [#2446]++- On Windows machines, the `add` command now properly shows green prompts instead of ANSI codes.+ [#2410]++- Balance reports now properly show the historical balance even when the report period is empty.+ [#2403]++- Balance reports' csv output, and the `balance --budget` report, now respect the --summary-only flag.+ (Stephen Morgan, [#2411], [#2443])++- The `demo` command no longer mentions `-- ASCIINEMAOPTS` in help.+ Also it shows a better error message when asciinema is not installed.++- `hledger help -m TOPIC` or `hledger help -i TOPIC` now show the help for TOPIC, as intended.+ [#2399]++- Since hledger 1.32.1, the `import` command, when importing multiple files at once,+ would write an empty .latest file for data files with no new transactions+ (causing all transactions in those data files to appear new on next import).+ This is now fixed.+ [#2444]++## Features++- CSV rules files can now run a shell command to clean the data:++ # read the latest foo*.csv file, and replace "USD" with "$"+ source foo*.csv | sed -e 's/USD/$/g'++ or to generate the data:++ # fetch JSON from simplefin.org, then transform it to CSV+ source | simplefinjson | simplefincsv++ Whenever hledger runs one of these commands, it will echo the command on stderr.++- The `import` command can now automatically archive imported CSV data files,+ saving a dated copy in a `data/` directory. This can be useful for troubleshooting,+ or for regenerating entries later with improved rules.+ To enable it, add `archive` to the rules file.++ This and the previous feature can simplify file management and reduce the need for support scripts.++## Improvements++- In command line help, flag group headings have been simplified.+ And the help for -f/--file, `add`, and `import` is now clearer.++- When given both an unknown command and an unknown flag, hledger now gives+ a clearer error message (about the command, not the flag).+ [#2388]++- A long standing awkwardness with addon commands has been solved:+ you can now use addon options freely in a hledger command line;+ you don't need to write a `--` argument first.+ [#458]+ +- In smart dates and period expressions, quarter syntax like `2025q1` or `Q2` is now fully supported.++- In end-value reports where the end date is unspecified, market prices+ in the future can no longer influence the report end date and valuation date.+ (Market prices on or before today, still can.)+ [#2445]++- A `tag:` query with the `accounts` command now only matches account tags, not posting tags.+ Eg, `hledger accounts tag:t` now lists only account a from this journal:++ account a ; t:++ 2025-01-01+ a 1+ b -1 ; t:++- Journal format's `include` directive now has more robust and convenient glob patterns:+ - `**` can match both directories and filenames+ - `**` now automatically ignores anything under dotted directories, like .git/, foo/.secret/, etc.+ (If you do want it to search dotted directories, + you can use the --old-glob flag for now to restore the old behaviour. See also Glob#49.)+ - Glob patterns with wildcards now automatically exclude the current file.+ Eg `include **.journal` will include all other .journal files in this directory and below.++- `include`'s error messages and debug messages have been improved.+ Eg, the including file paths are also shown.++- Journal format's auto posting rules can now use `%account` to insert the account name+ from the matched posting.+ (Stephen Morgan, [#1975], [#2412])++- The `aregister` command no longer abbreviates account names+ when producing `csv`, `html`, or `fods` output.+ (savanto, [#1995], [#2416])++- The `commodities`, `payees` and `tags` commands now have --used/--declared/--undeclared/--unused flags, like `accounts`.+ And there has been a general cleanup of options and help across these four commands.++- The `setup` command's output has been improved.+ Lack of a pager is now reported as info, not warning (there's no default pager on Windows).+ Shell completions are ignored for now.++## Docs++- add: clarify that add is for journal format only+- addon commands: edits, drop `--` argument from all examples [#458]+- areg: clarification+- bin: README updates+- COMMANDS: mention general options+- completions: README updates+- config files: no longer experimental+- csv: date-format: mention lack of support for local time formats [#1874]+- csv: source, archive: rewrite, add examples+- Depth: fix typo+- github release docs: simplify install commands+- import: use windows-compatible quotes in watchexec example+- include directive: update docs; clarify effect, glob limitations+- note fish LEDGER_FILE setup+- options: mention that flag+value can't combine with other flags [#2059]+- print: improve --location help+- smart dates: fix typo++## Examples++- CSV rules for Eternl cryptocurrency wallet+- VAT example++## Scripts/addons++- renamed paypaljson2csv to paypaljson+- simplefinjson, simplefincsv: new helpers for downloading/converting data from simplefin.org bank aggregator++# 1.43.2 2025-06-13++- hledger no longer shows an error message or exits with error status+ when its output is truncated in a piped command. (This broke in 1.43.) [#2405]++- The `add` command's doc now describes how it interacts with balance assertions+ and balance assignments. [#2406]++- `aregister` now consistently rounds amounts to display precision again.+ (This broke in 1.32.) [#2407]++- Changelog, release notes: mention improved decoding errors [#73];+ add missing issue numbers++# 1.43.1 2025-06-04++Fixes++- `cur:` in posting-based reports like `balance` and `register` once again+ filters multicommodity amounts as it should. [#2396]+- More error messages were made consistent, hiding call stack etc. [#2367]++Docs++- Query types: clarify that amt: filters postings [#2396]+- More text encoding corrections/cleanups [#2394]++# 1.43 2025-06-01++## Breaking changes++- Timeclock format now supports multiple simultaneous clocked-in sessions.+ A clockout entry can reference the account name of the clockin it is ending,+ otherwise it will end the most recent clockin.++ This is a potentially breaking change, because we previously ignored+ the description on clockout entries. For now, you can restore the+ old behaviour by adding the `--timeclock-old` flag. This may be+ removed later, so if you needed it, please let us know!+ (Michael Rees, [#2141])++## Fixes++- For a long time, hledger docs stated that hledger's input and output had to be UTF-8 encoded.+ In fact this was wrong; hledger has always used the system locale's encoding for both.+ Docs like [Install: Text encoding](install.md#text-encoding)+ and [hledger: Text encoding](hledger.md#text-encoding)+ have been updated.+ [#2394]++- Some boolean queries involving `amt:` or `cur:` did not match correctly; now they do.+ (Simon Michael, Stephen Morgan, [#2371], [#2373], [#2387])++- The `roi` command has fixed a bug with PnL attributed to the wrong period.+ (Dmitry Astapov, [#2391])++- CLI error messages now have consistent format independent of the GHC+ version hledger was compiled with. [#2367]++## Features++- A new `setup` command checks your hledger installation and shows information+ useful for troubleshooting. It will do more in future.+ For now, `setup` should be reliable and accurate;+ please test it on all your machines and share the results with us.+ Experimental.++ When you run this command, hledger attempts one HTTP request, with a 10s timeout,+ to hledger.org, to detect the current release version.++- New `any:"BOOLEANQUERY"` and `all:"BOOLEANQUERY"` queries can be+ used with transaction-matching commands like `print` and `import`.++ Unlike `expr:"BOOLEANQUERY"`, where the parts of the boolean query+ are allowed to match different postings in the transaction,+ with `any:` and `all:` the entire boolean query must match a single posting.+ `any:` matches the transaction if any posting is matched,+ `all:` matches the transaction if all postings are matched.++- The `add` command now allows balance assertions to be added, after an amount.+ Also, whenever you enter an amount, it now checks the journal's balance assertions+ and will not allow adding an amount that would cause assertion failure+ (unless you use the `-I/--ignore-assertions` flag).+ (Michael Rees, [#2355], [#2356])++- The hledger-print-location script, which shows transactions' file positions, + is now built in to `print` as the `--location` flag.+ (Sam Almahri, [#2368])++## Improvements++- Core data types are now more strict, which in some cases reduces memory and time usage by up to 15%.+ (Stephen Morgan, [#2381], [#2385], [#2387])++- Config files (and maybe timedot files) no longer require a final newline.++- In journal format, `include` directives can now have same-line comments.++- CSV `if` rules now produce more `--debug=2` output, useful for troubleshooting.++- CSV debug output now displays records as the `if` matchers see them.+ (Comma separated and with quotes and outer whitespace removed.)++- A number of error messages have been updated to show a consistent format.+ (reading a nonexistent data file,+ reading an unsafe dotted file name on Windows,+ demo not found,+ demo asciinema error,+ diff bad arguments,+ print --match with no match,+ register --match with no match,+ roi with no investment transactions).+ [#2367]++- When unicode/non-ascii text can't be decoded by the system locale's text encoding,+ we now show a consistent informative error message explaining it. [#73]++- Support GHC 9.12.++## Docs++- Account types: rewrite+- Assertions and multiple files: edits+- Balance assertions and multiple files+- balance: edits+- Beancount output: edits+- check: edits+- Config file: drop the s+- CSV: clarify that CSV means delimiter-separated values, link to wikipedia DSV page+- CSV:description field: fix link [hledger_site#133]+- Fix broken hledger-iadd link+- Fix various broken "Commodity display style" links (JB Rainsberger, Simon Michael, [hledger_site/#132])+- How CSV rules are evaluated: clarify+- Journal: cheatsheet edits+- print: simplify [#2368]+- Queries: discuss transaction vs posting queries; cleanups+- Queries: fix the explanation of boolean queries and space-separated terms++## Examples++- examples/csv/nps.csv.sh updated (Pranesh Prakash)+- examples/forecast-budget* -> examples/goal-budget*+- examples/i18n/\*.journal: top level account declarations in several languages.+- examples/quickstart.journal: the quickstart journal from the home page++## Scripts/addons++- bin/balance-as-budget-multi.hs (Dmitry Astapov)+- bin/bashrc: command alias updates+- bin/hledger-sankeymatic++## API++- Hledger.Cli.Conf: make getConf total, add getConf'+- Hledger.Cli.Version: add more version helpers, rename HledgerBinaryInfo++# 1.42.2 2025-05-16++Fixes++- The test command can pass options to tasty again (this broke in 1.42).+ Also, any arguments before -- are now passed to tasty as test-selecting -p options.+ [#2386]++- Require extra >= 1.7.11, fixing the stack8.10.yaml build. (Thomas Miedema)++Docs++- CSV encoding: fix inaccurate list of encoding names. [#2354]+- Fix broken links to "Commodity display style". (Simon Michael, J.B. Rainsberger [hledger_site#132])+- Misc. edits/fixes: beancount output, commands list, balance command, hledger-iadd link, csv tutorial link++# 1.42.1 2025-03-12++Fixes++- Fix a regression in the parsing of single ampersands (&) in csv rules.+ (Thomas Miedema, [#2352])++- The run and repl commands no longer cache data wrongly when using the --forecast option.+ (Dmitry Astapov, [#2345])++- The run and repl commands no longer miss a caching opportunity when using --forecast with a period argument.+ (Stephen Morgan)++Docs++- run, repl: doc fixes (Pranesh Prakash, Simon Michael)++# 1.42 2025-03-07++Fixes++- hledger's default options for the `less` pager no longer include --use-color,+ which caused older less versions (eg 551) to break. [#2335]++- In balance --budget reports, costs no longer prevent display of percentages. [#2327]++- In the balance command's HTML output, -H/--historical now suppresses the total heading.++- print --help now shows the correct default for --round. [#2318]++- close --infer-costs no longer implies the -x/--explicit flag. [#1826]++- add: Account names provided on the command line are no longer ignored. [#2305]++- bs/bse/cf/is no longer show the unsupported --budget option in their help. [#2302]++- The print command now ignores --depth entirely. Previously, a depth+ limit caused it to show only transactions referencing accounts as+ deep or deeper than that.++- Week periods beginning in the previous year are now shown correctly.+ Eg the week beginning 2024-12-30 (which is week 1 of 2025 because the+ thursday falls in 2025) was previously shown as 2024-W01, and is now shown as 2025-W01.+ [#2304]++Features++- `run` and `repl` are new commands which run multiple commands+ without re-parsing data files, so they run faster.+ `run` runs a sequence of commands from files or command line arguments,+ and `repl` provides an interactive prompt with readline-style history.+ (Dmitry Astapov, Simon Michael, [#2323], [#2328])++- `commands` is a new explicit command for showing the commands list; it's useful in the REPL.+ With --builtin, it shows only the builtin commands.++- hledger can now read CSV/SSV/TSV data in encodings other than UTF8,+ using the new `encoding` CSV rule. (Joschua Kesper, [#2319])++- `if` matchers in CSV rules can now be combined on the same line,+ separated by `&&` (AND) or `&& !` (AND NOT). This makes `if` tables more expressive.+ Examples:++ if %description amazon && %date 2025-02-22+ account2 expenses:books++ if,account2+ %description amazon && %date 2025-02-22, expenses:books++ The next-line `&` operator also may now be written as `&&`, for consistency.+ (Thomas Miedema, [#2333])++Improvements++- Terminal width is now detected more robustly, using the POSIX API.+ This means that register commands will more reliably use the proper terminal width,+ eg when $TERM or $COLUMNS do not have a correct value, and on Windows.+ hledger no longer uses $COLUMNS.+ (gesh, [#2332], [#2340])++- Error messages (first line) in the terminal are now shown in red (and bold),+ and warning messages are shown in yellow,+ when ANSI codes are supported and permitted.++- --pivot can now also pivot on amount quantity (`amt`),+ amount cost (`cost`), and/or commodity symbol (`comm` or `cur`).++- The close command's --migrate flag has been renamed to `--clopen`.+ The start: tag has been renamed to `clopen:`,+ and its default value now excludes the new file's extension.+ And close --assign's tag has been renamed to `assign:`.++- The print command now supports the --invert flag. [#2314]++- The roi command is now faster:+ it no longer checks every day with P directive,+ and the "one period per report interval" case has been optimised.+ (Dmitry Astapov)++- Two more file extensions are now recognised as possible hledger addon+ commands: `.osh` and `.ysh`.++Docs++- aregister: Drop an inconsistent newline from options help.+- balance: improve --layout option help.+- close: doc rewrites+- shell completions: mention zsh; cleanups+- cost/lot notations: clarify+- cost, value reporting: edits+- Directive effects: fix account types link [#126]+- commodity styles: fix typo [hledger_site#123]+- commodity directive: clarify+- close: mention the balance assertions+- pager: mention --pager=no+- Aliases and account types: better troubleshooting command+- Beancount output: mention limitations: P and balance assignments+- Balance report output: drop outdated note about --tree and HTML [#1846]+- new/updated: ACHIEVEMENTS, CREDITS, FINANCE, MOCKUPS, REGRESSIONS, RELEASING, Scripts+- examples/csv: pooltool-rewards.csv.rule cleanup+- examples: some sample hledger run scripts+- examples: test files for CSV encoding [#2319]++Scripts/addons++- hledger-balance-as-budget properly applies commodity styles now. (Dmitry Astapov)++- hledger-git now runs pass-through git commands in the right repo.++- hledger-git now checks for a git repo more robustly. (Lars Kellogg-Stedman)++- hledger-jj is another easy CLI for keeping hledger files in version control,+ using newer tech (jujutsu and oil shell's ysh).++- hledger-script-example.hs has had some cleanup.++# 1.41 2024-12-09++Breaking changes++- Accounts named "equity:conversion", "equity:trading", or "equity:trade(s)",+ which are detected as type `V`/`Conversion`, will now revert to type `E`/`Equity` instead+ if any other account has been declared as type `V`/`Conversion`.++- When built with ghc 9.10.1, hledger shows two extra newlines after any error message.++Fixes++- A somewhat severe, though hopefully rare, valuation bug has been fixed.+ In certain circumstances, values could be calculated inaccurately,+ because of display-rounding occurring inappropriately during calculations. [#2254]++ Specifically:+ when there was no direct P price for the target commodity,+ so that hledger had to convert via a chain of prices,+ and if all of those price amounts had too few decimal places,+ then the result could be inaccurate.+ An example:++ P 2000-01-01 A 10.5 B+ P 2000-01-01 B 100.5 C++ 2000-01-01+ (a) 100 A+ + $ hledger-1.40 print -X C+ 2000-01-01+ (a) 105520 C ; wrong++ $ hledger-1.41 print -X C+ 2000-01-01+ (a) 105525 C ; right+ +- `bs`/`bse`/`cf`/`is`'s HTML output no longer includes excess heading cells,+ and `bs`/`bse`'s HTML output no longer shows an inappropriate Total heading with `-T`.+ (`balancesheet` does not support `-T`.)+ (Henning Thielemann)++- Balance commands' HTML, CSV and FODS output now show tree mode properly indented+ (using no-break spaces).+ (Henning Thielemann)++- In the HTML output of `bs`/`bse`/`cf`/`is` reports, Net amounts in the Net row are now formatted like the others.+ (Bas van Dijk)++- In `bs`/`bse`/`cf`/`is` HTML output, some unnecessary TH cells have been fixed.+ [#2225] (Henning Thielemann)++- The `print` command now ignores a depth limit entirely.+ Previously, a depth limit caused it to show only transactions referencing accounts as deep or deeper than that.++- In the `roi` command, a division by zero error (when all assets were sold) has been fixed.+ [#2281] (Dmitry Astapov) ++- In a multi-line comment generated by CSV rules, tags on all lines now work (ie, can be matched).+ Posting dates in comments generated from CSV also now [work](https://hledger.org/hledger.html#comment-field).+ [#2241]++- hledger's bash shell completions are now up to date with the latest CLI.+ [#986]++- When showing output with a pager, if `$PAGER` is set to something not found in PATH,+ we now ignore it instead of raising an error.++- `hledger --color=yes | less -R` now shows bold headings as you'd expect.++Features++- The `print`, `register` and `aregister` commands now support HTML and FODS output,+ and the `bs`/`bse`/`cf`/`is` commands now support FODS output.+ This means all of the "STANDARD REPORTS" commands, and the `balance` command, now support text, HTML, CSV, TSV, or FODS output.+ (Henning Thielemann)++- When generating HTML output with the register or balance commands,+ the `--base-url` option will add hyperlinks to hledger-web,+ allowing you to view the detailed transactions if you have hledger-web running.+ (Henning Thielemann)++- Reports can now specify different display depths for certain accounts,+ rather than showing all accounts with the same depth limit.+ Multiple `--depth=ACCTREGEX=DEPTH` options (or `depth:ACCTREGEX=DEPTH` arguments can be used.+ For example, this will clip all accounts matching "assets" to depth 3,+ all accounts matching "expenses" to depth 2, and all other accounts to depth 1:+ `--depth assets=3 --depth expenses=2 --depth 1`+ (Stephen Morgan, #2292)++- In unix-like environments, hledger now uses a pager (`$PAGER`, `less`, or `more`)+ for all large terminal output, not just for help.+ You can override this with the new `--pager` option.+ The pager is expected to handle hledger's ANSI colour output (unless you disable that).+ If `less` is used, it will be configured automatically,+ or you can override this by setting options in a `HLEDGER_LESS` environment variable.++- The `print` command's `beancount` output is now much more Beancount-compatible [#2295].+ Other than using `--alias` to provide the top-level account names Beancount requires,+ you should rarely have to do anything special to produce a journal that `bean-check` accepts.+ hledger will automatically adjust problematic names, encode unsupported characters, and so on.+ See [hledger: Beancount output](https://hledger.org/dev/hledger.html#beancount-output) for the full details.++ This supersedes the `ledger2beancount` tool, and makes using Beancount tools,+ especially Fava, practical for hledger users. In many cases this should just work:+ ```+ hledger [ALIASES] print -o tmp.beancount; fava tmp.beancount+ ```++Improvements++- `if` blocks in CSV rules now allow `& !` (AND NOT) on the same line.++- When reading `.latest` files, whitespace is now ignored, and any date parse failure+ is reported with the file and line number.++- In journal format, P directives now require a space after the first symbol,+ preventing surprises like `P 2024-10-31 a0 1` parsed as `P 2024-10-31 a 01`.+ [#2280]++- `aregister` has a new `--heading=YN` option, for disabling the report heading. (Henning Thielemann)++- `aregister` now supports the `--invert` and `--cumulative` flags, like the `register` command. (Henning Thielemann)++- The balance commands' HTML and FODS output now shows table borders consistently.+ (Henning Thielemann)++- In the balance commands' HTML output, row headings now span multiple rows when appropriate, rather than being repeated.+ (Henning Thielemann)++- Balance commands now support `--transpose` when generating HTML output.+ (Henning Thielemann)++- The `balance` command's `--layout=tidy` now affects HTML and FODS output at least to some extent (not just CSV output).+ And it always disables the totals row. (Henning Thielemann)++- The `balance` command's FODS output now picks a report title based on the report mode:+ "Balance Report", "Multi-period Balance Report", or "Budget Report". (Henning Thielemann)++- `balance` and `aregister`'s HTML output will now use a hledger.css file if present, like `bs`/`bse`/`cf`/`is`.++- `bs`/`bse`/`cf`/`is` now support the `--count` (postings count) report type, like `balance`.++- The balance commands' options help has had some cleanup.++- The error messages from `check accounts` and `check recentassertions` are now clearer.++- The `check commodities` command now also checks commodities used in P directives. [#2280]++- The `commodities` command now also list commodities mentioned in P directives. [#2280]++- All of hledger's internal hidden (but searchable) tags can now be made visible + by `print --verbose-tags`, which is useful for troubleshooting `--infer-equity`,+ `--infer-costs`, and the detection of redundant costs and conversion postings.+ Also,++ - Some hidden tags have been renamed for clarity:+ `_modified` is now `_modified-transaction`,+ `_cost-matched` is now `_cost-posting`,+ `_conversion-matched` is now `_conversion-posting`.+ - The `generated-posting:` tag added by `--infer-equity` is now valueless.+ - The `modified-transaction:` tag added by `--auto` now appears on its own line.++- Using the `-NUM` shortcut (for `--depth NUM`) in a config file now works.++- Setting the `--color` option in a config file now works+ (except it does not affect `--debug` output, currently).++- The `--color` option's suggested values are now `yes`/`y`, `no`/`n`, or `auto`/`a`.+ `always` and `never` are no longer documented, though still supported.++- More compact and informative `--debug=2` output during valuation.+ Market prices are now shown using one line each, the known prices+ are listed, and the status of `--infer-market-prices` is shown.+ [#2287]++- More informative `--debug=7` output from CSV rules.++- The hledger packages have a new `debug` build flag. Builds made with ghc 9.10+ and this flag+ will show some kind of stack trace if the program exits with an error.+ (These will improve in future ghc versions.)++- Disabled the unused `ghcdebug` build flag and ghc-debug support, for now.++- Allow megaparsec 9.7.++- ghc 9.10 / base 4.20 are now supported.++Docs++- Windows: added tips for setting `LEDGER_FILE` (Amadeusz Wieczorek, hledger_site#119)+- csv: if blocks: explain matchers and field names better [#2289]+- import: rewrite; rename "date skipping" to "overlap detection"+- import: added tips for first import+- assertions: mention their behaviour with posting status+- journal: rewrite the Tags section+- pager: note that `help -p TOPIC` uses less; link to less FAQ+- query types: updates, add headings, mention tag:'s infix matching+- Regular expressions: note possible RTL/bidi limitation (?)+- Special characters: rewrite, more precision, mention some Windows differences+- Output formats: expand, document beancount and FODS output+- Text output: expand/consolidate terminal topics+- FODS output: describe the advantages over CSV (Henning Thielemann)+- Debug output: note that the --debug option doesn't work in config files.+- bal: improve --layout doc+- bal: also mention hledger.css and text encoding in balance doc+- html: note safari text encoding issue+- timedot: mention the common journal+timedot file setup [#2238]+- Install, manual: new shell completions doc. [#986]+- Config files: rewrite [#2231]+- examples/csv: an example of YNAB 4 data, and RTL text, with a workaround+- examples: hledger2beancount.conf++Scripts/addons++- bin/*: remove obsolete _FLAGS markers from --help+- examples/csv/csv-hledger-1.py: a python-based CSV converter script++API++- Hledger.Utils.IO's ansi color helpers now respect the --color option.+- Hledger.Utils.IO.rgb' now takes Float arguments instead of Word8.+- Hledger.Cli.Commands.Balance: export budgetReportAs* functions, for use in scripts.+ (Dmitry Astapov)++# 1.40 2024-09-09++Fixes++- Account tags (and type declarations) declared in multiple files are now combined correctly. [#2202]++- Several kinds of report interval now choose a better start date:+ - `every Nth day of month from DATE` with periodic transactions [#2218]+ - `every M/D from DATE`+ - `every Nth WEEKDAY from DATE`++- The balance commands' HTML output no longer repeats the "Total" and+ "Net" headings when the totals row has multiple lines.+ And the layout has been improved and made more consistent with the+ text output.++- The `--tldr` flag now also works with the `tealdeer` tldr client.+ +- `hledger check tags` no longer warns about the internal `_price-matched` tag+ being undeclared (and that tag has been renamed to `_cost-matched`).+ [#2247]++- `hledger check accounts` no longer warns about the special `equity:conversion` account+ being undeclared (the default account used by `--infer-equity`).++Features++- You can now save command line options in a [config file](https://hledger.org/hledger.html#config-file),+ to be added to your hledger commands either on demand or automatically.+ (This supersedes the older arguments files feature.)++ This much-requested new feature has pros and cons, and is experimental;+ your testing and feedback is welcome.+ It changes the nature of hledger somewhat, which I have marked by+ giving this release a more memorable version number (1.40).++- The balance commands can now output in FODS format, an XML spreadsheet+ file format readable by LibreOffice. (Henning Thielemann)++- The `register` report can now be sorted by date, account, amount,+ absolute amount, description, or a combination of these. (Michael Rees, [#2211])++Improvements++- All the balance-like commands now support FODS output, not just `balance`.+ (Henning Thielemann)++- Config files can now also provide the command name.+ If the first thing in a config file's general section is a non-flag argument,+ that will be used as the command name argument,+ taking precedence over any command line arguments.+ This makes config files strictly more powerful than the older argument files.++- Improved debug output for command line and config file processing.++- The print command's beancount output is now better at producing Beancount-ready data,+ converting hledger account names and commodity names to Beancount-compatible ones.++- Command line processing has been overhauled and should be more robust+ in certain cases, with tweaked error messages and debug output.+ Command-specific flags can now optionally appear before the command name.+ (Though writing them afterward is usually more readable.+ Addon-specific flags must still come last, after `--`.)++- The `--rules-file` option has been renamed to `--rules`.+ The old spelling is still supported as a hidden option.++- Weekly reports' week headings are now more compact, especially in+ single-year balance reports. ([#2204], Victor Mihalache)++- The `balance` command with no report interval, and also `balance --budget`,+ now support html output. (Henning Thielemann)++- In balance commands' html and csv output, "Total:" and "Net:" headings+ are now capitalised consistently.++- `bs`/`cf`/`is` reports now show the report interval in their title.++- The balance commands' text output with the `--pretty` flag now shows+ an outer table border and inter-column borders.++- The `check recentassertions` error message is now more readable.++- Timedot format now allows comment lines to be indented.++- When running the `tldr-node-client` client, auto-update of the tldr+ database is now suppressed.++- When running a tldr client fails, the warning now mentions the required+ `--render` flag. [#2201]++- The error message for unsupported regular expressions like `(?:foo)` has+ been improved.++- `--debug` has moved to "General help flags", making it available in+ more situations.++- Some verbose debug output from command line processing has been demoted to level 2.++- Parsing timedot files now gives debug output at level 9.++- Allow doclayout 0.5.++Docs++- The hledger/hledger-ui/hledger-web manuals now list all command options as shown by `--help`.+- Added an example config file, `hledger.conf.sample`.+- The `diff` and `prices` commands' help layout has been improved.+- `add`'s doc described the effect of `D` wrongly, now fixed.+- Date adjustments: rewrites and corrections+- Period headings: added+- Input: clarify that multiple -f options are allowed+- Scripts and add-ons: edits, list add-ons again+- Timeclock: edits, fix `ti`/`to` scripts+- Fixed "hledger and Ledger" links [hledger_site#112]+- examples/csv: Monzo CSV rules added+- examples/csv: Tiller CSV rules added+- examples/csv: Nordea CSV rules added (Arto Jonsson)++Scripts/addons++- `bin/bashrc` updates; add years, eachyear scripts+- `bin/hledger-simplebal`: ignore config files+- `bin/hledger-script-example`: explain shebang commands better+- `bin/hledger-register-max`: update/fix++# 1.34 2024-06-01++Breaking changes++- `check ordereddates` no longer supports `--date2`.+ Also (not a breaking change): `--date2` and secondary dates are now officially+ [deprecated](https://hledger.org/1.34/hledger.html#secondary-dates) in hledger,+ though kept for compatibility.++Features++- You can now get a quick list of example command lines for hledger or+ its most useful subcommands by adding the `--tldr` flag (or just+ `--tl`). For best appearance you should install the [`tldr`][tldr] client,+ though it's not required.++ These short "tldr pages" are a great counterbalance to verbose PTA docs.+ You can also use `tldr` without hledger to view the latest versions, or translations:\+ `tldr hledger[-COMMAND]`.+ Or you can [browse tldr pages online](https://tldr.inbrowser.app/search?query=hledger+).+ Consider contributing translations!+ More tips at <https://github.com/hledgerorg/hledger/tree/master/doc/tldr>.++[tldr]: https://tldr.sh++Improvements++- The `hledger` commands list has been reorganised,+ with commands listed roughly in the order you'll need them.++- The general flags descriptions in `--help` have been updated and grouped.++- Correctness checks now run in a documented order. `commodities` are+ now checked before `accounts`, and `tags` before `recentassertions`.+ When both `ordereddates` and `assertions` checks are enabled,+ `ordereddates` now runs first, giving more useful error messages.++- `-I`/`--ignore-assertions` is now overridden by `-s`/`--strict`+ (or `check assertions`), enabling more flexible workflows.+ Eg you can `alias hl="hledger -I"` to delay balance assertions+ checking until you add `-s` to commands.++- `--color` and `--pretty` now also accept `y` or `n` as argument.++- When built with the `ghcdebug` flag and started with `--debug=-1`,+ hledger can be controlled by [ghc-debug] clients like+ ghc-debug-brick or a ghc-debug query script, for analysing+ memory/profile info.++[ghc-debug]: https://gitlab.haskell.org/ghc/ghc-debug++Fixes++- `hledger COMMAND --man` and `hledger help TOPIC --man` now properly scroll+ the man page to the TOPIC or COMMAND heading.+ The exact/prefix matching behaviour has been clarified in `help --help`.++- In journal files, `include` directives with trailing whitespace are now parsed correctly.++- The help command's help flags are now consistent with other commands+ (and it has `--debug` as a hidden flag).++- Build errors with GHC 8.10 have been fixed. [#2198]++Docs++- The tables of contents on hledger.org pages now just list top-level headings,+ (and the hledger manual structure has been adjusted for this).+ This makes the hledger manual on hledger.org more scannable and less scary.+- add: drop lengthy transcript, add simpler example commands (from tldr)+- Amount formatting: move down, it's not the best first topic+- balance: mention the `--summary-only` flag+- check: expand check descriptions+- examples: CSV rules: vanguard, fidelity, paypal updates+- Generating data: rewrite+- JSON output: link to OpenAPI spec+- manuals: synopsis, options cleanup/consistency+- Options: correction, NO_COLOR does not override --color+- PART 4: COMMANDS: reorganise into groups, like the CLI commands list.+- Period expressions: mention last day of month adjusting [#2005]+- Secondary dates: expand, and declare them deprecated.+- Time periods cleanup, simplify markup+- Unicode characters: mention UTF-8 on windows++Scripts/addons++- Added `hledger-pricehist`, an alias for the `pricehist` market price+ fetcher so that it can appear in hledger's commands list.++[#2005]: https://github.com/hledgerorg/hledger/issues/2005+[#2198]: https://github.com/hledgerorg/hledger/issues/2198++# 1.33.1 2024-05-02++- process >=1.6.19.0 seems not strictly needed and is no longer required,+ improving installability.+ [#2149]++- `print` and `close` now show a trailing decimal mark on cost amounts also,+ when needed to disambiguate a digit group mark.++- The balance commands' HTML output now includes digit group marks when+ appropriate (fixes a regression in 1.25).+ [#2196]++- The add command no longer shows ANSI escape codes in terminals that+ don't support them.++- Doc updates:+ - import: Skipping -> Date skipping, discuss commodity styles more+ - csv: Amount decimal places: expand, note import behaviour++[#2149]: https://github.com/hledgerorg/hledger/issues/2149+[#2196]: https://github.com/hledgerorg/hledger/issues/2196++# 1.33 2024-04-18++Breaking changes++- `expr:` boolean queries, introduced in hledger 1.30 (2023),+ no longer allow `date:` to be used within an `OR` expression,+ avoiding unclear semantics which confuse our reports.+ If you'd like to improve this, see #2178. [#2177] [#2178]++- Some error messages (date parse errors, balance assertion failures) have changed,+ which might affect error-parsing add-ons like flycheck-hledger.++Fixes++- `add`, `import`, `web`:+ On MS Windows, don't allow writing to files whose name ends with a period,+ since it can cause data loss; raise an error instead.+ I made this change in hledger 1.15 (2019), but it never worked; now it does.+ [#1056]++- `balance --budget`:+ The budget report in tree mode was omitting parent accounts with no actual or goal amounts+ and a single child, instead of showing them as a prefix of the child's name.+ Now it always shows them, on a line of their own (a bit like `--no-elide`).+ It's not a perfect fix, but the budget report code is twisty.+ [#2071]++- `check tags`:+ The special `date` and `date2` tags,+ and the `modified` and `_modified` tags generated by `--auto`,+ are now also implicitly declared.+ [#2148], [#2119]++- Regular expression match group references in CSV `if` rules,+ added in hledger 1.32, did not work right when multiple if conditions matched a CSV record.+ This is now fixed; match group references are now scoped to their local `if` block.+ [#2158] (Jonathan Dowland)++- `roi` now correctly interacts with `--value`.+ [#2190] (Dmitry Astapov)++- hledger now requires process-1.6.19.0+ to avoid any vulnerabilities on Windows from+ [HSEC-2024-0003](https://haskell.github.io/security-advisories/advisory/HSEC-2024-0003.html).++Features++- `close` has had some enhancements for usability ([#2151]):++ - It now excludes equity accounts by default; and always excludes the balancing account.++ - It has new `--assert` and `--assign` modes, for generating transactions which+ make balance assertions or balance assignments.+ There is also a `--assertion-type` option for changing the assertion/assignment type.++ - It adds a tag to generated transactions, named `start`, `assert` or `retain`+ depending on the mode.++ - The `start` tag's value will be a guess of the new file's name,+ inferred by incrementing a year number in the current file name.+ Eg, `hledger close --migrate` on `2024.journal` will add the tag+ `start:2025.journal` to both transactions.+ Tags like this can be helpful when reading multiple files,+ for excluding closing and opening balances transactions+ (eg with `not:tag:start=2025`).++ - You can set different tag values by writing the mode option with an argument.+ Eg: `hledger close --migrate=NEWFILENAME`.++ - `close` now supports `--round` for controlling display of decimal places, like `print`.++ - `examples/multi-year/` is examples/tutorial for managing multiple files with the `close` command.++Improvements++- `stats` has had some improvements:++ - It now also shows some information about memory usage, when hledger is built or is running+ with the GHC Run Time System available. (Try `hledger stats +RTS -T`.)++ - The default output is now more private, hiding file paths and commodity symbols.+ Those can be added by the new `-v/--verbose` flag.++ - Output is now more compact and more likely to fit in 80-character lines.++ - When generating multiple outputs with a report interval, reports are now+ separated by an empty line.++- Several more kinds of Unicode space are allowed for separating digit groups in numbers.+ We now support (my guess of the ones that might show up in real world CSV files):+ space,+ no-break space,+ en space,+ em space,+ punctuation space,+ thin space,+ narrow no-break space,+ medium mathematical space.++- Glob patterns in `$LEDGER_FILE` are now respected.+ Eg, setting it to `*.journal` or `2???.journal` now works as expected.++- When hledger is reading a symbolically-linked journal file,+ relative paths in include directives are now evaluated+ relative to the directory of the real linked file,+ not the directory containing the symbolic link.++- Date parse errors are now simpler and clearer.+ They no longer try to repeat (a reconstruction of) the problem date,+ since the actual problem date is already visible in the highlighted file excerpt.++- Balance assertion error messages are clearer,+ and show the difference between expected and actual balance again.+ With --debug=2 they also show costs.++- `tsv:` and `ssv:` file name prefixes are now supported in addition to `csv:`.+ They force the file to be read as a .tsv (tab separated values) or .ssv (semicolon-separated values) file.+ [#2164] (Michael Rees)++- In CSV rules files, commented lines are now allowed within "if tables". (Dmitry Astapov)++- `balance --budget`'s CSV and TSV output now shows zeroes instead of nothing when there's no amount.++- `bs`,`bse`,`cf`,`is`:+ Report sections which are empty now show zero as their subtotal. (aragaer)++- `print` and `close` add a trailing decimal mark when needed to disambiguate a single digit group mark.+ They now also do this for balance assertion and balance assignment amounts.+ [#2176]++- hledger can now be built with GHC 9.8.++- hledger now requires safe >=0.3.20.++Docs++- add version annotations for features added in 1.32 (hamzashezad)+- add Text encoding section, mention UTF-8 BOM support [#2189]+- journal: note that `payee` and `tag` directives can't have tags in comments, unlike `account`.+- journal: clarify how auto postings work.+- journal: list built-in special tag names+- journal: description/payee/note: clarify+- journal: amounts/commodities/numbers: cleanups+- journal: move intro before cheatsheet+- journal: transactions: explain transaction balancing [#2135]+- journal: transactions: mention debits, credits and sign+- journal: commodity directive: clarify & fix scope of effects [#2135]+- journal: D directive: clarify scope [#2191]+- journal: split Decimal marks, Digit group marks+- journal: move complex commodity styles, lot notation topics later+- journal: drop redundant/wrong Querying with cost or value section+- journal: cheatsheet: cleanups+- journal: assertions and ordering/commodities/subaccounts: cleanups+- csv: matchers: clarify, mention !/& limitation [#2088]+- csv: if tables: explain comments and order of application (Dmitry Astapov)+- add: document the effect of D default commodity directive [#815]+- balance: cleanups+- balance: budget report: moved "Budgets and subaccounts" to the Cookbook.+- bs,bse,cf,is: update sample output+- bse: note requirements for checking the accounting equation+- close: rewrite, give a better technique for excluding opening/closing balance txns [#2151]+- import: rename "deduplication" to "skipping", and rewrite+- examples: expand READMEs, clarify status for examples+- examples: invoicing: cleanups, renames+- examples: invoicing: pandoc-make-invoice: don't write to $LEDGER_FILE; remove the REMOVE THIS LINE line+- examples: csv: daedalus-transactions: update for current daedalus [#2171]+- examples: shared-finances/++Scripts/addons++- hledger-bar, hledger-simplebal: shellcheck fixes, cleanups (Colin Dean)++- hledger-bar: Fix an error when NO_COLOR is not defined [#2159].+ Also, it's now more compliant with the no-color.org spec:++ Command-line software which adds ANSI color to its output by default+ should check for a NO_COLOR environment variable that, when present+ and not an empty string (regardless of its value), prevents the+ addition of ANSI color.++ so one can now temporarily override $NO_COLOR=1 in the environment by+ setting it empty: NO_COLOR= hledger ...++- hledger-txnsbycat: added++API++- move readFileStrictly to hledger-lib:Hledger.Utils.IO++[#815]: https://github.com/hledgerorg/hledger/issues/815+[#1056]: https://github.com/hledgerorg/hledger/issues/1056+[#2071]: https://github.com/hledgerorg/hledger/issues/2071+[#2088]: https://github.com/hledgerorg/hledger/issues/2088+[#2119]: https://github.com/hledgerorg/hledger/issues/2119+[#2135]: https://github.com/hledgerorg/hledger/issues/2135+[#2135]: https://github.com/hledgerorg/hledger/issues/2135+[#2148]: https://github.com/hledgerorg/hledger/issues/2148+[#2151]: https://github.com/hledgerorg/hledger/issues/2151+[#2151]: https://github.com/hledgerorg/hledger/issues/2151+[#2158]: https://github.com/hledgerorg/hledger/issues/2158+[#2159]: https://github.com/hledgerorg/hledger/issues/2159+[#2164]: https://github.com/hledgerorg/hledger/issues/2164+[#2171]: https://github.com/hledgerorg/hledger/issues/2171+[#2176]: https://github.com/hledgerorg/hledger/issues/2176+[#2177]: https://github.com/hledgerorg/hledger/issues/2177+[#2178]: https://github.com/hledgerorg/hledger/issues/2178+[#2189]: https://github.com/hledgerorg/hledger/issues/2189+[#2190]: https://github.com/hledgerorg/hledger/issues/2190+[#2191]: https://github.com/hledgerorg/hledger/issues/2191++# 1.32.3 2024-01-28++Fixes++- A performance slowdown since 1.29, especially noticeable with many+ accounts and transactions, has been fixed. [#2153]++- Balance assertions involving mixed-cost balances are checked correctly again+ (a regression in 1.30). [#2072], [#2137], [#2150]++- import --catchup works again (a regression in 1.32). [#2156]++- --anon is now a deprecated hidden flag that raises an error,+ but is still usable as --obfuscate (also hidden). [#2133]++- Balance assertion error messages are clearer, and show the diff again.++[#2156]: https://github.com/hledgerorg/hledger/issues/2156++# 1.32.2 2023-12-31++Fixes++- In CSV field assignments, %FIELD interpolation and `\n` can be used together again. [#2134]++- In timedot data, numbers beginning with a decimal point are accepted again. [#2130]++- In a `balance --budget` report, `--layout=tall` no longer hides commodity symbols.++- Value reports seeing a pathological price chain with 1000 or more+ steps now write their warning to the console, not a debug log file.++Improvements++- Allow megaparsec 9.6++Docs++- Updated: + Queries,+ Periodic transactions,+ Auto postings,+ Assertions and costs,+ Budget report++# 1.32.1 2023-12-07++- Fixed: `import` with multiple files now updates .latest files correctly. (#2125)++- Fixed: `print --round=hard` now properly pads/rounds amounts with inferred costs. (#2123)++- CSV matcher syntax: mention that ! and & can't be used in the same line yet. (#2088)++- Drop the "a difference of ..." line from balance assertion failure output.+ I feel it made the message harder to read and isn't really necessary.++- Declaring the empty payee name with `payee ""` now works,+ to let `hledger check payees` accept payee-less transactions.+ (#2119)++- Built-in tags with special meaning like `type:` and `t:` are now implicitly declared,+ so using type: in account declarations or generating t: with timedot letters + won't cause `hledger check tags` to fail.+ (#2119)++# 1.32 2023-12-01++Breaking changes++- Display styles and display precision are now managed more carefully+ during calculations and output, fixing a number of issues (#2111,+ "Precisiongeddon"). In brief:++ - Cost and value reports, such as `print -V`, now (1) consistently+ apply commodity display styles, and (2) do not add or discard+ decimal digits unnecessarily. (#2105)+ + - When "infinite decimals" arise during calculations (eg in value+ reports, or in `prices` or `roi` output), these are now shown+ limited to 8 decimal digits rather than 255.+ + - Non-print-like reports no longer add trailing decimal marks to+ disambiguate digit group marks (this was an unintended regression+ in 1.31). (#2115)+ + - We now document number formatting adjustments made in certain+ reports and output formats (hledger manual > REPORTING CONCEPTS >+ Amount formatting, parseability).++Features++- Timedot format supports a new letters syntax for easier tagged time logging.+ (#2116)++- `print` has a new `beancount` output format for exporting to Beancount.+ This prints journal output more likely (though not guaranteed) to+ be readable by Beancount.++- In CSV rules, matchers using regular expressions can now interpolate+ their matched texts into the values they assign to fields (field+ assignment values can reference match groups).+ (#2009) (Jonathan Dowland)+ +- In CSV rules, matchers can be negated by prepending `!`.+ (#2088) (bobobo1618)++- Multi-column balance reports (from `bal`, `bs`, `is` etc.) can use+ the new `--summary-only` flag (`--summary` also works) to display+ just the Total and Average columns (if enabled by `--row-total` and+ `-A/--average`) and hide the rest.+ (#1012) (Stephen Morgan)++- All commands that suport csv output now also support `tsv`+ (tab-separated values) output. The data is identical, but the fields+ are separated by tab characters and there is no quoting or+ escaping. Tab, carriage return, and newline characters in data are+ converted to spaces (this should rarely if ever happen in practice).+ (#869) (Peter Sagerson).++Improvements++- Journal format no longer fails to parse Ledger-style lot costs with spaces+ after the `{`, improving Ledger compatibility.++- `import` now does not update any .latest files until it has run+ without error (no failing strict checks, no failure while writing+ the journal file). This makes it more idempotent, so you can run it+ again after fixing problems.++- `print` now shows zeros with a commodity symbol and decimal digits+ when possible, preserving more information.++- `print` has a new option for controlling amount rounding (#2085):+ + - `--round=none` - show amounts with original precisions (default;+ like 1.31; avoids implying less or more precision than was+ recorded)++ - `--round=soft` - add/remove decimal zeros in non-cost amounts+ (like 1.30 but also affects balance assertion amounts)++ - `--round=hard` - round non-cost amounts (can hide significant digits)++ - `--round=all` - round all amounts and costs++ For the record:+ `print` shows four kinds of amount: posting amounts,+ balance assertion amounts, and costs for each of those.+ Past hledger versions styled and rounded these inconsistently.+ Since 1.31 they are all styled, and since 1.32 they are rounded as follows:+ + | hledger-1.32 print | amt | cost | bal | balcost |+ |--------------------|------|------|------|---------|+ | (default) | none | none | none | none |+ | --round=soft | soft | none | soft | none |+ | --round=hard | hard | none | hard | none |+ | --round=all | hard | hard | hard | hard |++- The `prices` command has had a number of fixes and improvements (#2111):++ - It now more accurately lists the prices that hledger would use+ when calculating value reports (similar to what you'd see with+ `hledger bal -V --debug=2`).+ + - The --infer-reverse-prices flag was confusing, since we always+ infer and use reverse prices; it has been renamed to `--show-reverse`.+ + - `--show-reverse` and `--infer-market-prices` flags now combine properly.+ + - `--show-reverse` now ignores zero prices rather than giving an error.+ + - Price amounts are now shown styled.+ + - Price amounts are now shown with all their decimal digits; or with+ 8 decimal digits if they appear to be infinite decimals (which can+ arise with reverse prices).+ + - Filtering prices with `cur:` or `amt:` now works properly.+ ++Fixes++- `print` now styles balance assertion costs consistently, like other+ amounts.++- `import` now works with `-s/--strict`.+ And more generally, when reading multiple input files, eg with+ multiple `-f` options, strict checks are done only for the overall+ combined journal (not for each individual file).+ (#2113)++- `tag:` queries now work when reading CSV files. (#2114)++- Using a `.json` or `.sql` file extension with `-o`/`--outputfile`+ now properly selects those output formats.++- Auto postings no longer break redundant equity/cost detection and+ transaction balancing. (#2110)+ +- Amounts set by balance assignment now affect commodity styles again.+ (#2091, a regression in 1.30)++- Timedot quantities with units are parsed more accurately.+ Eg a quantity like "15m" was evaluated as 0.249999999 not 0.25,+ and since hledger 1.21, it was printed that way also.+ Now we round such quantities to two places during parsing to get+ exact quarter-hour amounts. (#2096)++- The `demo` command no longer triggers a JSON decode error in asciinema+ 2.3.0. It now also shows a better error message if asciinema fails+ (#2094).++- Failing balance assertions with a cost now show correct markers in+ the error message. (#2083)++Docs++- New:+ + - Amount formatting, parseability+ - Started new code docs for developers, based in the Hledger module's haddock++- Updated:+ + - aregister+ - commodity directive+ - Commodity display style+ - if table+ - Decimal marks, digit group marks+ - Regular expressions+ - Timedot++ +# 1.31 2023-09-03++Features++- Multi-pivot: the --pivot option now accepts multiple arguments,+ colon-delimited, to construct account names from multiple fields.+ (#2050, Eric Mertens)++Improvements++- The `print` command now more closely replicates the original journal+ amount styles, which is helpful when round-tripping / cleaning up+ journal files:++ - Amounts in conversion transactions could be displayed rounded to a+ lower precision; this no longer happens.+ (#2079)++ - Amounts could be displayed with extra zeros after the decimal mark;+ this no longer happens.++ - Amounts could display with a different precision if the journal+ included a timedot file; this no longer happens.++ - Costs in balance assertions were not displayed with standard+ styles like other amounts; now they are.++ - Zero amounts were always shown as just "0"; now they are shown+ with their original commodity symbol and style. (And if an+ inferred amount has multiple zeros in different commodities, a+ posting is displayed for each of these.)+ +- `print` no longer displays numbers with a single digit group mark+ and no decimal mark, which are ambiguous and hard to re-parse. Now+ if a number has digit group marks the decimal mark will always be+ shown also. Eg `1,000` (where the comma is a thousands separator)+ is now shown as `1,000.`.++- The check command's + `balancedwithautoconversion` and `balancednoautoconversion` checks+ have been renamed to `autobalanced` and `balanced`.++- `hledger check recentassertions` now reports failures at the first+ posting that's more than 7 days later than the latest balance+ assertion (rather than at the balance assertion). This is the thing+ actually triggering the error, and it is more likely to be visible+ or at least closer when you are working at the end of a journal+ file.++ Also, the suggested sample balance assertion now uses the same+ commodity symbol as in the failing posting (the first, if there are+ more than one); and, no longer includes a cleared mark.++- The import command now shows the file path being imported to.++- With --pivot, `desc` is now the preferred spelling for pivoting on+ description.++- The demo command now ignores an invalid journal file, like the other+ HELP commands.++- Debug output for equity conversion postings has been improved,+ making troubleshooting easier.++- Allow aeson 2.2, megaparsec 9.5.++Fixes++- In journal files, valid multicommodity transactions where the+ matching non-equity postings can't be auto-detected are no longer+ considered an error (as they were in hledger 1.29 and 1.30). Now,+ such transactions are accepted, and --infer-cost has no effect on+ them. This is similar to the behaviour of --cost, --infer-equity,+ and --infer-market-prices. (#2045)++- In journal files, equity conversion postings are now detected more+ tolerantly, using the same precision as the conversion posting's+ amount (#2041). Eg, the following transaction is now accepted:++ 2023-01-01+ Assets -8401USD @ 2.495 GEL+ ; ^ 209.60495 GEL, recognised as a match for the 209.60 below+ Equity:Conversion 84.01 USD+ Equity:Conversion -209.60 GEL+ Assets 209.60 GEL++- The roi command now reports TWR per period and overall TWR for+ multi-period reports.+ (#2068, Dmitry Astapov)++- The commands list no longer shows bar when hledger-bar is not installed (#2065),+ and had a few other cleanups.++# 1.30.1 2023-06-02++Fixes++- Add missing files to Hackage release, making it buildable.++Docs++- Replace note about repeated options.++# 1.30 2023-06-01++Breaking changes++- The CSV reader now properly skips all empty lines, as specified by docs.+ Previously, inner empty lines were not being skipped automatically.+ You might need to adjust the `skip` count in some CSV rules files.+ (#2024)++- Timedot format now generates a single multi-posting transaction per+ date line, and supports comments and tags on all lines.+ (#1754)++- Timeclock format now supports comments and tags.+ Descriptions can no longer contain semicolons.+ (#1220)++Features++- CSV rules files can now be read directly, as in+ `hledger -f foo.csv.rules CMD`. By default this will read data+ from foo.csv in the same directory.+ +- CSV rules files can use a new `source FILE` rule to specify the data file,+ with some convenience features:++ - If the data file does not exist, it is treated as empty, not an+ error.++ - If FILE is a relative path, it is relative to the rules file's+ directory. If it is just a file name with no path, it is relative+ to `~/Downloads/`.++ - If FILE is a glob pattern, the most recently modified matched file+ is used.++ This helps remove some of the busywork of managing CSV downloads.+ Most of your financial institutions's default CSV filenames are+ different and can be recognised by a glob pattern. So you can put a+ rule like `source Checking1*.csv` in foo-checking.csv.rules,+ periodically download CSV from Foo's website accepting your browser's+ defaults, and then run `hledger import checking.csv.rules` to import+ any new transactions. The next time, if you have done no cleanup, your+ browser will probably save it as something like Checking1-2.csv, and+ hledger will still see that because of the * wild card. You can choose+ whether to delete CSVs after import, or keep them for a while as+ temporary backups, or archive them somewhere.+ (Experimental)++- The balance command has a new --count report type+ which reports posting counts instead of amounts.++- Full boolean queries, allowing arbitrary use of AND, OR, NOT+ (case insensitive) and parentheses for grouping, are now supported.+ For backward compatibility, these require an `expr:` prefix.+ Existing queries work as before, and you can mix and match the+ old and new styles if you like.+ (Chris Lemaire)+ +- demo: This new command plays brief asciinema screencasts explaining+ various features and use cases. We will add more of these over time.+ (Experimental)++Improvements++- Add-on commands can now have `.js`, `.lua`, or `.php` file extensions.++- Generated and modified transactions and postings have the same hidden+ tags (beginning with underscore) as before, but no longer have visible+ tags added by default. Use `--verbose-tags` if you want them added.++- We now try harder to ensure `less` (and its `more` mode) show our+ ANSI formatting properly in help output.+ If you use some other $PAGER, you may have to configure it yourself+ to show ANSI (or disable ANSI entirely, eg by setting NO_COLOR=1).+ This is now documented in hledger manual > Paging.+ (#2015)++- The print command's `--match` mode has been refined.+ Previously, similarity completely outweighed recency, so a+ slightly-more-similar transaction would always be selected no matter+ how old it was. Now similarity and recency are more balanced,+ and it should produce the desired transaction more often.+ There is also new debug output (at debug level 1) for troubleshooting.++- Miscellaneous commands list updates.+ Help has been added for all published add-on commands (like hledger-lots).++- The help command's documentation now mentions an issue caused by+ a too-old `info` program, as on mac.+ (#1770)++Fixes++- Unbalanced virtual postings with no amount always infer a zero amount.+ This is fixing and clarifying the status quo; they always did this,+ but print always showed them with no amount, even with -x, and+ the behaviour was undocumented.++- On windows systems with multiple drive letters, the commands list+ could fail to show all installed add-ons.+ (#2040)++- Balancing a transaction with a balance assignment now properly respects costs.+ (#2039)++- The commands list no longer lists non-installed addons.+ (#2034)++- Since hledger 1.25, "every Nth day of month" period rules with N > 28 could+ be calculated wrongly by a couple of days when given certain forecast start dates.+ Eg `~ every 31st day of month` with `--forecast='2023-03-30..'`.+ This is now fixed.+ (#2032)++- Postings are now processed in correct date order when inferring balance assignments.+ (#2025)++- Posting comment lines no longer disrupt the underline position in error messages.+ (#1927)++- Debug output is now formatted to fit the terminal width.++Docs++- Miscellaneous manual cleanups.++- Rewrite introductory sections,+ Date adjustment,+ Directives,+ Forecasting,+ etc.++- Add Paging section.++- Remove archaic mentions of `setenv`.++API++- Renamed: Hledger.Cli.Commands: findCommand -> findBuiltinCommand++# 1.29.2 2023-04-07++Breaking changes++- 1.29's cleanup of the `close` command has been continued.+ Here are all the changes to `close` since hledger 1.28:++ - The default behaviour is now to print only one transaction: a closing transaction.++ - To print both closing and opening transactions as before,+ use the new `--migrate` flag.++ - The accounts closed by default are now just the ALE accounts+ (accounts declared or inferred as type `Asset`, `Liability`, or `Equity`).+ If you don't have account types configured, or+ to close some other set of accounts, provide query arguments that match them.+ To close all accounts as before, use a `.` argument to match them all.++ - To print a retain earnings transaction for RX accounts (accounts+ of type `Revenue` or `Expense`), use the new `--retain` flag.++ - The `equity` command alias, removed in 1.29, has been restored.++ - The `--open-acct` option, removed in 1.29, has been restored.++ - The `--closing` and `--opening` flags have been renamed to `--close` and `--open`.+ (`--close` had been removed in 1.29 and is now restored.)++ - The docs have been rewritten. Also the 1.29 release notes now mention+ the breaking change.++ - The command is marked experimental again.++ (#2020)++Fixes++- `type:` queries now "see through" account aliases and pivots,+ as they did in hledger <1.27, and as `acct:` queries do.+ (#2018)++- The corruption in 1.29's info manual is fixed. (#2023)++- The 1.29 release notes for periodic reports'/periodic transactions' start dates+ have been improved. Also the hledger manual's "Date adjustment" section+ has been corrected and clarified.++# 1.29.1 2023-03-16++Improvements++- Hledger.Cli.Script now also exports++ Control.Applicative+ Control.Concurrent+ Data.Char+ Data.Functor+ System.IO+ System.IO.Error++ and new string helpers++ strip1Char+ stripBy+ strip1By++- Allow building with GHC 9.6.1 (#2011)++Fixes++- The stats report no longer displays "Exact" in front of dates. (#2012)++Docs++- remove duplicate in `hledger close` docs (Yehoshua Pesach Wallach)++# 1.29 2023-03-11++Breaking changes++- Periodic reports will now start exactly at the start date you have specified,+ rather than being adjusted to a natural period boundary; see below.++- The `close` command's CLI and default behaviour was changed; see below+ (and fixes in hledger 1.29.2+).++Features++- Periodic transactions and periodic reports can now start on any date.+ Eg, `hledger reg -M -b 1/15` now starts exactly on jan 15th, and a periodic rule+ like `~ monthly from 2023-01-15` now works as you'd expect instead of raising an error.+ This also improves our ability to read Ledger files.+ Inferred start/end dates, eg obtained from the journal instead of the command line,+ are still automatically adjusted to period boundaries, as before.++ Upgrade notes: in report commands which specify a start date, you might need to+ adjust that date to see the same periods as before. Eg:+ + - `-p 'weekly from 202304'` (equivalent to `-p 'weekly from 20230401'`)+ now gives periods like `2023-04-01..2023-04-07`.+ Change it to start on a monday (eg `-p 'weekly from 20230403`) to restore+ simple week periods like `2023-04-03W14`.++ - `-M -b 2023/1/15` now gives periods like `2023-01-15..2023-02-14 2023-02-15..2023-03-14`.+ Change it to start on a first of month (eg `-M -b 2023/1`) to restore+ simple month periods like `Jan Feb Mar`.++ (#1982)++- You can now freely combine @/@@ notation and conversion postings+ in a single transaction. This can help readability, and also allows+ more flexibility when recording cost. hledger will check that the+ two notations are in agreement, and ignore the redundancy if they are.+ (Conversion postings are postings to accounts with type `V`/`Conversion`+ or name `equity:conversion`/`equity:trade`/`equity:trading`,+ or subaccounts of these. See also COST.)++- In journal format there is now a `tag` directive for declaring tag names,+ and the check command now has a `tags` check to enforce use of declared tag names.++Improvements++- hledger's commands list has been reorganised for clarity.+ More add-on commands are now recognised and categorised,+ and unrecognised add-on commands are listed in a more compact+ multi-column layout.+ (Simon Michael, Michael Grünewald)++- hledger's commands list and command line help now use ANSI (bold+ headings) when supported.+ +- hledger's commands list and command line help now use a pager+ (respecting $PAGER) for long output except on MS Windows.++- hledger's `--version` output no longer shows `+` for dev builds made+ in dirty repos (it was buggy).++- The add command's Description completions now also include payee names+ (declared with `payee` or recorded in transactions with `|`),+ not just full descriptions.++- aregister now supports HTML output.+ (#1996) (Jonathan Dowland)++- aregister now shows a " (matching query)" hint in report title + when extra query args (other than date: or depth:) are used,+ to reduce confusion.++- The `close` command's CLI and default behaviour were changed,+ attempting to make it easier to understand and use. Some of its+ legacy flags and aliases were also dropped, without sufficient+ warning. For the full details, including subsequent cleanups,+ see hledger 1.29.2's change notes.++- register-match is now the `--match` mode of the register command.+ (This command was used by ledger-autosync at one point; if you still+ need it, hopefully `register --match` works similarly.)++- print-unique has been dropped, because it doesn't+ support print's options, it disorders same-day transactions, I don't+ know of any users or use cases, and it could easily be recreated as+ an addon script.++- print's JSON output now also includes source positions for `--forecast` transactions.+ (Chris Lemaire)++- Journal format now allows the empty commodity symbol to be written+ as `""`, so it's now possible to declare market prices for it:+ `P 2022-01-01 "" $100`. This can be useful for timedot data.++- Inferring costs from equity now happens after transaction balancing,+ not before. As a result, `--infer-costs` now works in transactions+ where an amount is left blank.++- `account` declarations now reject parenthesised account names,+ reducing confusion.+ (Chris Lemaire)++- Our journal reader now accepts more Ledger syntax, improving Ledger+ file compatibility (#1962). We now test our ability to at least+ read the sample journals from Ledger's baseline functional tests,+ and our success rate has improved from 80% to 90% since 1.28.+ + - `since` is accepted as synonym of `from` in period expressions+ - `apply year` and `year` are accepted as synonyms of `Y`+ - `(lot notes)` in amounts and `((valuation expressions))` after amounts are now ignored+ - directives + `A`, `assert`, `bucket`, `capture`, `check`, `define`,+ `expr`, `eval`, `python`, `value`,+ `apply fixed`, `apply tag`,+ `end apply fixed`, `end apply tag`, `end apply year`+ are now ignored+ - subdirectives of `payee`, `tag`, and `commodity` (other than `format`) are now ignored+ - `pop` directive is no longer supported++- When reading CSV, we now check that assigned account names are valid (parseable).+ (#1978)++Fixes++- aregister now handles an extra account query correctly. (#2007)++- balance's `--help` now mentions `--layout=tidy`++- Balance commands with `--layout=bare` now generate proper table+ layout in HTML output.++- register's `-w`/`--width` option no longer gives ugly parse error messages.++- stats's `--help` no longer wrongly claims to support -O/--output-format.++- Balance assignments with a cost now generate a correct balance assertion. (#1965)++- The CSV reader now properly skips header lines before attempting to parse records. (#1967)++Scripts/addons++- Scripts can now use Hledger.Cli.Script, a convenient new prelude which+ helps reduce import boilerplate. It currently re-exports:++ Control.Monad+ Data.Either+ Data.List+ Data.Maybe+ Data.Ord+ Data.Time+ Text.Printf hiding (formatString)+ Data.Text (Text, pack, unpack)+ Safe hiding (at)+ System.Directory+ System.Environment+ System.Exit+ System.FilePath+ System.Process+ Hledger+ Hledger.Cli+ Hledger.Cli.Main (argsToCliOpts)++ (Not much of Data.Text/Data.Text.IO because those need to be qualified.)++Docs++- chunk the hledger manual into parts, rename and rearrange sections for better structure/flow+- add a cheatsheet demonstrating all the main journal features that I recommend+- move a number of my not-so-recommended journal features into a less visible "Other syntax" section+- add: payees/descriptions completion+- areg: more advice on account-matching+- bal: --budget: clarify use of print --forecast+- bal: budget: compare with forecasting; add some tips+- balance cleanups/reorder+- check: adjacentconversionpostings was dropped+- cli: balance: fix link to Budgeting page+- cli: fix all links to Journal > Tags / Commands > tags+- codes: improve example suggested by Rob Nielsen+- csv, timeclock, timedot: clarify comment lines (#1953)+- csv: add new coinbase example+- csv: clarify amount-in/amount-out docs (#1970)+- csv: clarify skip/valid csv semantics (#1967)+- csv: clarify valid CSV requirements and issues (fix #1966)+- csv: cleanup, reorder, CSV rules tips -> Working with CSV+- csv: fix wrong if tables doc; rewrite several sections (#1977)+- csv: flatten, clean up CSV sections+- csv: improve Amount field / Setting amounts+- csv: note -in and -out are used together for one posting (#1970)+- csv: rules factoring tips+- csv: try to clarify how CSV fields and hledger fields work+- document --infer-market-prices with signed costs (#1870)+- fix duplicate market prices heading breaking info navigation+- import: note a pitfall with multifile import+- improve Directives summaries+- introduction/input/output improvements+- journal: cheatsheet: clarify date tag+- journal: rewrite Account names, mention brackets/parentheses (#1915)+- mention pivoting on a tag with multiple values (#1950)+- more cost notation docs; describe Ledger and Beancount cost notation+- more mention of posting order effect on inferring cost (#1959)+- period expressions doc updates+- Removed redundant paragraph in documentation. (J. B. Rainsberger)+- rename directive sections, fix many links+- reorganise commands list, like the CLI+- reorganise bin/README & the Scripts page, add entries for recent scripts+- replace "transaction prices" terminology with "costs"+- tags: discuss multi-values/overriding (#1950)+- update market price inference docs per sol+- Updated section on pivoting. Used synonyms for "member" in cases where there could be confusion with the tag named "member." (Robert Nielsen)+- use more standard and consistent boilerplate in hledger, ui, web man pages+- virtual postings: improve wording per Robert Nielsen++# 1.28 2022-12-01++Features++- The `accounts` command has new flags: `--undeclared` (show accounts used but not declared), `--unused` (show accounts declared but not used), and `--find` (find the first account matched by the first command argument, a convenience for scripts). Also `-u` and `-d` short flags have been added for `--used` and `--declared`.++- A new CSV rule `intra-day-reversed` helps generate transactions in correct order with CSVs where records are reversed within each day.++- CSV rules can now correctly convert CSV date-times with a implicit or explicit timezone to dates in your local timezone. Previously, CSV date-times with a different time zone from yours could convert to off-by-one+ dates, because the CSV's timezone was ignored.+ Now,++ 1. When a CSV has date-times with an implicit timezone different from yours, you can use the `timezone` rule to declare it.++ 2. CSV date-times with a known timezone (either declared by `timezone` or parsed with `%Z`) will be localised to the system timezone+ (or to the timezone set with the `TZ` environment variable).++ (#1936)+ +Improvements++- print --match now respects -o and -O.++- print --match now returns a non-zero exit code when there is no acceptable match.++- Support megaparsec 9.3. (Felix Yan)++- Support GHC 9.4.++Fixes++- In CSV rules, when assigning a parenthesised account name to `accountN`, extra whitespace is now ignored, allowing unbalanced postings to be detected correctly.++Scripts/addons++- bin/hledger-move helps record transfers involving subaccounts and costs,+ eg when withdrawing some or all of an investment balance containing many lots and costs.++- bin/hledger-git no longer uses the non-existent git record command.+ (#1942) (Patrick Fiaux)++- bin/watchaccounts is a small shell script for watching the account tree as you make changes.++# 1.27.1 2022-09-18++Fixes++- Balance commands using `-T -O html` no longer fail with an error+ when there is no data to report.+ (#1933)++# 1.27 2022-09-01++Features++- `hledger check recentassertions` (and flycheck-hledger in Emacs if+ you enable this check) requires that all balance-asserted accounts+ have a balance assertion within 7 days before their latest posting.++ This helps remind you to not only record transactions, but also to+ regularly check account balances against the real world, to catch+ errors sooner and avoid a time-consuming hunt.++- The --infer-costs general flag has been added, as the inverse+ operation to --infer-equity. --infer-costs detects commodity+ conversion transactions which have been written with equity+ conversion postings (the traditional accounting notation) and adds+ PTA cost notation (@@) to them (allowing cost reporting).+ See https://hledger.org/hledger.html#equity-conversion-postings .+ (Stephen Morgan)++Improvements++- Many error messages have been improved. Most error messages now use+ a consistent, more informative format. + (#1436)++- The accounts command has a new --directives flag which makes it+ show valid account directives which you can paste into a journal.++- The accounts command has a new --positions flag which shows where+ accounts were declared, useful for troubleshooting.+ (#1909)++- Bump lower bounds for Diff and githash. (Andrew Lelechenko)++- GHC 8.6 and 8.8 are no longer supported. Building hledger now+ requires GHC 8.10 or greater.++Fixes++- Account display order is now calculated correctly even when accounts+ are declared in multiple files.+ (#1909)++- At --debug 5 and up, account declarations info is logged.+ (#1909)++- hledger aregister and hledger-ui now show transactions correctly+ when there is a type: query.+ (#1905)++- bal: Allow cumulative gain and valuechange reports.+ Previously, --cumulative with --gain or --valuechange would produce an+ empty report. This fixes this issue to produce a reasonable report.+ (Stephen Morgan)++- bal: budget goal amounts now respect -c styles (fixes #1907)++- bal: budget goals now respect -H (#1879)++- bal: budget goals were ignoring rule-specified start date++- cf/bs/is: Fixed non-display of child accounts when there is an+ intervening account of another type.+ (#1921) (Stephen Morgan)++- roi: make sure empty cashflows are skipped when determining first cashflow (Charlotte Van Petegem)+ Empty cashflows are added when the begin date of the report is before the first+ transaction.++Scripts/addons++- https://hledger.org/scripts.html - an overview of scripts and addons in bin/.++- paypaljson, paypaljson2csv - download txns from paypal API++- hledger-check-postable.hs - check that no postings are made to accounts with a postable:(n|no) tag++- hledger-addon-example.hs - script template++# 1.26.1 2022-07-11++- require safe 0.3.19+ to avoid deprecation warning++# 1.26 2022-06-04++Improvements++- `register` and `aregister` have been made faster, by ++ - considering only the first 1000 items for choosing column+ widths. You can restore the old behaviour (guaranteed alignment+ across all items) with the new `--align-all` flag.+ ([#1839](https://github.com/hledgerorg/hledger/issues/1839), Stephen Morgan)++ - discarding cost data more aggressively, giving big speedups for+ large journals with many costs.+ ([#1828](https://github.com/hledgerorg/hledger/issues/1828), Stephen Morgan)++- Most error messages from the journal reader and the `check` command now use+ a consistent layout, with an "Error:" prefix, line and column numbers,+ and an excerpt highlighting the problem. Work in progress.+ ([#1436](https://github.com/hledgerorg/hledger/issues/1436)) (Simon Michael, Stephen Morgan)++- `hledger check ordereddates` now always checks all transactions+ (previously it could be restricted by query arguments).++- The `--pivot` option now supports a `status` argument, to pivot on transaction status.++- Update bash completions (Jakob Schöttl)++Fixes++- Value reports with `--date2` and a report interval (like `hledger bal -VM --date2`)+ were failing with a "expected all spans to have an end date" error since 1.22;+ this is now fixed.+ ([#1851](https://github.com/hledgerorg/hledger/issues/1851), Stephen Morgan)++- In CSV rules, interpolation of a non-existent field like `%999` or `%nosuchfield`+ is now ignored (previously it inserted that literal text).+ Note this means such an error will not be reported; + Simon chose this as the more convenient behaviour when converting CSV.+ Experimental.+ ([#1803](https://github.com/hledgerorg/hledger/issues/1803), [#1814](https://github.com/hledgerorg/hledger/issues/1814)) (Stephen Morgan)++- `--infer-market-price` was inferring a negative price when selling.+ ([#1813](https://github.com/hledgerorg/hledger/issues/1813), Stephen Morgan)++- Allow an escaped forward slash in regular expression account aliases.+ ([#982](https://github.com/hledgerorg/hledger/issues/982), Stephen Morgan)++- The `tags` command now also lists tags from unused account declarations.+ It also has improved command-line help layout.+ ([#1857](https://github.com/hledgerorg/hledger/issues/1857))++- `hledger accounts` now shows its debug output at a more appropriate level (4).++# 1.25 2022-03-04++Breaking changes++- Journal format's `account NAME TYPECODE` syntax, deprecated in 1.13, has been dropped.+ Please use `account NAME ; type:TYPECODE` instead.+ (Stephen Morgan)++- The rule for auto-detecting "cash" (liquid asset) accounts in the `cashflow` report + has changed: it's now "all accounts under a top-level `asset` account, with + `cash`, `bank`, `checking` or `saving` in their name" (case insensitive, variations allowed). + So if you see a change in your `cashflow` reports, you might need to add+ `account` directives with `type:C` tags, declaring your top-most cash accounts.++Features++- The new `type:TYPECODES` query matches accounts by their accounting type.+ Account types are declared with a `type:` tag in account directives,+ or inferred from common english account names, or inherited from parent accounts,+ as described at [Declaring accounts > Account types].+ This generalises the account type detection of `balancesheet`, `incomestatement` etc.,+ so you can now select accounts by type without needing fragile account name regexps.+ Also, the `accounts` command has a new `--types` flag to show account types.+ Eg:++ hledger bal type:AL # balance report showing assets and liabilities+ hledger reg type:x # register of all expenses+ hledger acc --types # list accounts and their types++ ([#1820](https://github.com/hledgerorg/hledger/issues/1820), + [#1822](https://github.com/hledgerorg/hledger/issues/1822)) + (Simon Michael, Stephen Morgan)++- The `tag:` query can now also match account tags, as defined in account directives.+ Subaccounts inherit tags from their parents.+ Accounts, postings and transactions can be filtered by account tag.+ ([#1817](https://github.com/hledgerorg/hledger/issues/1817))++- The new `--infer-equity` flag replaces the `@`/`@@` price notation in commodity+ conversion transactions with more correct equity postings (when not using `-B/--cost`).+ This makes these transactions fully balanced, and preserves the accounting equation.+ For example:++ 2000-01-01+ a 1 AAA @@ 2 BBB+ b -2 BBB++ $ hledger print --infer-equity+ 2000-01-01+ a 1 AAA+ equity:conversion:AAA-BBB:AAA -1 AAA+ equity:conversion:AAA-BBB:BBB 2 BBB+ b -2 BBB++ + `equity:conversion` is the account used by default. To use a different account,+ declare it with an account directive and the new `V` (`Conversion`) account type.+ Eg:+ + account Equity:Trading ; type:V++ ([#1554](https://github.com/hledgerorg/hledger/issues/1554)) (Stephen Morgan, Simon Michael)++- Balance commands (`bal`, `bs` etc.) can now generate easy-to-process "tidy" CSV data + with `-O csv --layout tidy`.+ In tidy data, every variable is a column and each row represents a single data point + (cf <https://vita.had.co.nz/papers/tidy-data.html>).+ ([#1768](https://github.com/hledgerorg/hledger/issues/1768), + [#1773](https://github.com/hledgerorg/hledger/issues/1773), + [#1775](https://github.com/hledgerorg/hledger/issues/1775)) + (Stephen Morgan)++Improvements++- Strict mode (`-s/--strict`) now also checks periodic transactions (`--forecast`) + and auto postings (`--auto`). + ([#1810](https://github.com/hledgerorg/hledger/issues/1810)) (Stephen Morgan)++- `hledger check commodities` now always accepts zero amounts which have no commodity symbol. + ([#1767](https://github.com/hledgerorg/hledger/issues/1767)) (Stephen Morgan)++- Relative [smart dates](hledger.html#smart-dates) may now specify an arbitrary number of some period into the future or past).+ Some examples:+ - `in 5 days`+ - `in -6 months`+ - `5 weeks ahead`+ - `2 quarters ago`+ + (Stephen Morgan)++- CSV output now always disables digit group marks (eg, thousands separators),+ making it more machine readable by default. + ([#1771](https://github.com/hledgerorg/hledger/issues/1771)) (Stephen Morgan)++- Unicode may now be used in field names/references in CSV rules files.+ ([#1809](https://github.com/hledgerorg/hledger/issues/1809)) (Stephen Morgan)++- Error messages improved:+ - Balance assignments+ - aregister+ - Command line parsing (less "user error")++Fixes++- `--layout=bare` no longer shows a commodity symbol for zero amounts. + ([#1789](https://github.com/hledgerorg/hledger/issues/1789)) (Stephen Morgan)++- `balance --budget` no longer elides boring parents of unbudgeted accounts + if they have a budget. + ([#1800](https://github.com/hledgerorg/hledger/issues/1800)) (Stephen Morgan)++- `roi` now reports TWR correctly++ - when there are several PnL changes occurring on a single day+ - and also when investment is fully sold/withdrawn/discounted at the end of a particular reporting period.++ ([#1791](https://github.com/hledgerorg/hledger/issues/1791)) (Dmitry Astapov)++Documentation++- There is a new CONVERSION & COST section, replacing COSTING. + ([#1554](https://github.com/hledgerorg/hledger/issues/1554))++- Some problematic interactions of account aliases with other features have been noted. + ([#1788](https://github.com/hledgerorg/hledger/issues/1788))++- Updated: [Declaring accounts > Account types](https://hledger.org/hledger.html#account-types)++# 1.24.1 2021-12-10++Fixes++- `balance --declared` is now filtered correctly by a `not:ACCT` query.+ (#1783)++- More reliable --version output, with commit date and without patch level.++API changes:++- new type synonyms ProgramName, PackageVersion, VersionString+- versionStringForProgname -> versionString with extra argument+- versionStringFor -> versionStringWith with extra argument++# 1.24 2021-12-01++Features++- balance commands provide more control over how multicommodity amounts+ are displayed. (And they no longer elide too-wide amounts by default.)+ The --commodity-column flag has been deprecated and replaced by a new+ --layout option, with three values:+ + - wide (the default, shows amounts on one line unelided, like older hledger versions)+ - tall (a new display mode, shows one amount per line)+ - bare (like the old --commodity-columm, shows one commodity per line with symbols in their own column)+ + (Stephen Morgan)++- The balance commands have a new `--declared` flag, causing them to+ include leaf (ie, non-parent) accounts declared by account directives,+ even if they contain no transactions yet. Together with `-E`, this shows+ a balance for both used and declared accounts.+ The idea is to be able to see a useful "complete" balance report, even+ when you don't have transactions in all of your declared accounts yet.+ (#1765)++- journal files now support a `decimal-mark` directive as a more+ principled way (than `commodity` directives) to specify the decimal character+ in use in that file, to ensure accurate number parsing.+ (#1670, Lawrence Wu)++Improvements++- The stats command now shows rough but useful performance stats: run+ time and processing speed in transactions per second.++- balance: support the --related flag, like register, showing the+ other postings from the transactions. (#1469, Stephen Morgan)++- roi now uses posting dates when available, and honors the --date2+ flag. This will not change the results computed for the typical+ use-case, it just makes "roi" more thorough/consistent.+ (Dmitry Astapov)++- aregister now shows transactions' secondary date if the --date2 flag is used.+ (#1731)++- timedot: a D default commodity (and style) declared in a parent+ journal file will now be applied to timedot amounts. This means they+ can be priced and valued/converted.++- cli: The --pretty and --forecast options can now be written after the+ command name, like other general options.+ (Stephen Morgan)++- register -V -H with no interval now values at report end date, like balance.+ (#1718, Stephen Morgan)++- Allow megaparsec 9.2.++- Drop the base-compat-batteries dependency. (Stephen Morgan)++Fixes++- prices: Do not include zero amounts when calculating amounts for balance assignments. (#1736) (Stephen Morgan)+ This is not usually a problem, but can get in the way of auto-inferring prices.++- csv: Successfully parse an empty csv file. (#1183) (Stephen Morgan)++- balance: Balance reports with --depth=0 properly report aggregated+ values, not zero everywhere. (#1761) (Stephen Morgan)++- prices: Do not try to generate prices when there would be a zero+ denominator. Also correctly generate reverse prices for zero+ amounts. (Stephen Morgan)++- csv: Allow both amount-in and amount-out fields to contain a zero.+ (#1733, Stephen Morgan)++- balance: Balance reports should consider date: queries when+ calculating report span with --date2. (#1745, Stephen Morgan)++- print: auto: The print command should always display inferred+ amounts for --auto generated postings. (#1276, Stephen Morgan)+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ++# 1.23 2021-09-21++Features++- The balance command has a new `--gain` report type, showing+ unrealised capital gains/losses. Essentially, this is the difference+ between the amounts' costs and their total present value. More+ precisely, between the value of the amounts' costs and the value of+ the amounts on the valuation date(s). (Ie, you can report gain in a+ different currency.)+ ([#1623](https://github.com/hledgerorg/hledger/issues/1623),+ [#1432](https://github.com/hledgerorg/hledger/issues/1432),+ Stephen Morgan, Charlotte Van Petegem)++- The new `-c/--commodity-style` option makes it easy to override+ commodity display styles at runtime, eg to adjust the number of+ decimal places or change the position of the symbol.+ ([#1593](https://github.com/hledgerorg/hledger/issues/1593), Arjen Langebaerd)++- The balance commands have a new `--commodity-column` flag that+ displays commodity symbols in a dedicated column, showing one line+ per commodity and all amounts as bare numbers.+ ([#1559](https://github.com/hledgerorg/hledger/issues/1559),+ [#1626](https://github.com/hledgerorg/hledger/issues/1626),+ [#1654](https://github.com/hledgerorg/hledger/issues/1654),+ Lawrence Wu, Simon Michael, Stephen Morgan)++- The `balance --budget` option can now take an argument,+ a case insensitive description substring which selects a subset of+ the journal's periodic transactions for setting budget goals. + This makes it possible to keep multiple named budgets in one journal, + and select the one you want with --budget's argument. + ([#1612](https://github.com/hledgerorg/hledger/issues/1612))++- Period expressions now support `every weekday`, `every weekendday` and+ `every mon,wed,...` (multiple days of the week).+ This is intended for periodic transaction rules used with+ `--forecast` (or `bal --budget`).+ ([#1632](https://github.com/hledgerorg/hledger/issues/1632), Lawrence Wu)++- The new `--today=DATE` option allows overriding today's date. This+ can be useful in tests and examples using relative dates, to make+ them reproducible.+ ([#1674](https://github.com/hledgerorg/hledger/issues/1674), Stephen Morgan)++- In CSV rules, multi-line comments are now supported. Newlines in CSV+ data are preserved, or newlines can be added by writing `\n` when+ assigning to `comment`, `comment1` etc. + (Malte Brandy)++Improvements++- Incremental performance improvements; hledger 1.23 is the fastest+ hledger yet, about 10% faster than 1.22. + (Stephen Morgan)++- `register` no longer slows down when there are many report intervals.+ ([#1683](https://github.com/hledgerorg/hledger/issues/1683), Stephen Morgan)++- Numbers in SQL output now always use decimal period (`.`),+ independent of commodity display styles. + (Stephen Morgan)++- `--sort` now gives a more intuitive sort oder when there are+ multiple commodities. Negative numbers in one commodity are always+ less than positive numbers in another commodity.+ ([#1563](https://github.com/hledgerorg/hledger/issues/1563), Stephen Morgan)++- `--infer-market-price` has been renamed to `--infer-market-prices`.+ (The old spelling still works, since we accept flag prefixes.)++- Our pretty-printed JSON now orders object attributes alphabetically,+ across all GHC and haskell lib versions.++- register with a report interval starting on custom dates+ (eg: `hledger reg -p "every 15th day of month") now makes the + date column wide enough to show the start and end dates.+ It also wastes less whitespace after the column.+ ([#1655](https://github.com/hledgerorg/hledger/issues/1655), Stephen Morgan)++- The --forecast option will now reject a report interval in its+ argument, instead of silently ignoring it.++- In JSON output, object attributes are now ordered alphabetically,+ consistently for all GHC and haskell lib versions. + ([#1618](https://github.com/hledgerorg/hledger/issues/1618), Stephen Morgan)++- JSON output now indents with 2 spaces rather than 4. + (Stephen Morgan)++- The balance commands' `-S/--sort-amount` flag now behaves more+ predictably and intuitively with multiple commodities.+ Multi-commodity amounts are sorted by comparing their amounts in+ each commodity, with alphabetically-first commodity symbols being+ most significant, and assuming zero with alphabetically-first commodity symbols being+ most significant, and assuming zero when a commodity is missing.+ ([#1563](https://github.com/hledgerorg/hledger/issues/1563), + [#1564](https://github.com/hledgerorg/hledger/issues/1564), Stephen Morgan)+ +- The close command now uses the later of today or journal's last day+ as default closing date, providing more intuitive behaviour when+ closing a journal with future transactions. Docs have been improved.+ ([#1604](https://github.com/hledgerorg/hledger/issues/1604))++- Rules for selecting the forecast period (within with --forecast+ generates transactions) have been tweaked slightly, and+ some disagreement between docs and implementation has been fixed.+ Now, the forecast period begins on:+ - the start date supplied to the `--forecast` argument, if any+ - otherwise, the later of+ - the report start date if specified with -b/-p/date:+ - the day after the latest normal (non-periodic) transaction in the journal, if any+ - otherwise today.++ It ends on:+ - the end date supplied to the `--forecast` argument, if any+ - otherwise the report end date if specified with -e/-p/date:+ - otherwise 180 days (6 months) from today.++ This is more intuitive in some cases. (Eg:+ `hledger reg --forecast -b 2020-01-01` on a journal containing + only periodic transaction rules now shows forecast transactions + starting from 2020-01-01, rather than from today.)+ ([#1648](https://github.com/hledgerorg/hledger/issues/1648), + [#1665](https://github.com/hledgerorg/hledger/issues/1665),+ [#1667](https://github.com/hledgerorg/hledger/issues/1667), + Stephen Morgan, Simon Michael)++- Require base >=4.11, prevent red squares on Hackage's build matrix.+ (We officially support GHC 8.6+, which means base 4.12, + but Hackage shows all packages building successfully with + base 4.11/GHC 8.4+ somehow, so it's still allowed..)++Fixes++- A rare bug causing incorrect balances to be reported by the+ cf/bs/bse/is commands, since hledger 1.19, has been fixed.+ (cf/bs/bse/is with --tree --no-elide --begin DATE and certain+ account directives could show wrong balances).+ ([#1698](https://github.com/hledgerorg/hledger/issues/1698), Stephen Morgan)++- aregister now aligns multicommodity amounts properly (broken since 1.21).+ ([#1656](https://github.com/hledgerorg/hledger/issues/1656), Stephen Morgan)++- `balance -E` (and hledger-ui Z) now correctly show zero parent accounts,+ fixing a bug introduced in hledger 1.19.+ ([#1688](https://github.com/hledgerorg/hledger/issues/1688), Stephen Morgan)++- The `roi` command no longer gives an ugly error in a certain case+ with PnL applied on the first day of investment. (Dmitry Astapov)++- `--forecast` now generates transactions up to the day before the+ specified report end date (instead of two days before).+ ([#1633](https://github.com/hledgerorg/hledger/issues/1633), Stephen Morgan)++- Certain errors in CSV conversion, such as a failing balance assertion,+ were always being reported as line 2.++# 1.22.2 2021-08-07++Breaking changes++- aregister no longer hides future transactions by default.+ This is a consequence of the fix for + [#1638](https://github.com/hledgerorg/hledger/issues/1638). + It makes aregister consistent, so we think it's a reasonable change.+ So if you have future-dated transactions in your journal which you+ don't want reported, you now must exclude them with `-e tomorrow` or+ `date:-tomorrow` in the command, as with other reports.+ (Stephen Morgan)++Improvements++- Timedot format's doc has been rewritten.++Fixes++- Make balance assignments in forecasted transactions work again+ (broken in 1.22.1).+ Forecast transactions are now generated early and processed+ in the same way as other transactions.+ ([#1638](https://github.com/hledgerorg/hledger/issues/1638), Stephen Morgan)++- aregister preserves the order of same-day transactions again+ (broken in 1.22.1).+ ([#1642](https://github.com/hledgerorg/hledger/issues/1642), Stephen Morgan)++# 1.22.1 2021-08-02++Improvements++- Bash shell completions (for hledger, hledger-ui, hledger-web) are+ now included in the hledger package's release tarballs, making them+ more likely to be installed by system packages. (Jakob Schöttl)++- roi docs now discuss how to quote multi-word queries. (#1609, Dmitry+ Astapov)++- Allow megaparsec 9.1++Fixes++- `cur:` and `amt:` queries now match the original amounts before+ valuation and cost conversion, as they did before hledger 1.22. We+ believe this is the more useful behaviour in practice. (#1625)+ (Stephen Morgan)++- Queries now work better with `register --related`, no longer showing+ duplicate postings when more than one posting in a transaction is+ matched. (#1629) (Stephen Morgan)++- Valuation now works with `register --related`. (#1630) (Stephen+ Morgan)++- Auto posting rules now also see inferred amounts,+ not just explicit amounts. (#1412) (Stephen Morgan)++- Our info manuals now have more robust directory metadata (no+ subdirectory path), making them more likely to be linked in your+ top-level Info directory by system packages. (#1594) (Simon Michael,+ Damien Cassou)++- The error message for a non-existent input file no longer shows+ excess double quotes. (#1601, Stephen Morgan)++- Journal format docs: The commodity directive's scope is now+ correctly described (lasts until end of current file).++- The aregister command now properly ignores a `depth:` argument. + It might now also behave more correctly with valuation or `--txn-dates`.+ (#1634, Stephen Morgan)++# 1.22 2021-07-03++Features++- check: A new `balancednoautoconversion` check requires transactions+ to balance without the use of inferred transaction prices. (Explicit+ transaction prices are allowed.) This check is included in `--strict`+ mode. The old `autobalanced` check has been renamed to+ `balancedwithautoconversion`. (Stephen Morgan)++Improvements++- Many internal optimisations have been applied (cf hledger-lib+ changelog). Overall, you can expect most reports to be about 20%+ faster. The register report is more than 2x faster and uses 4x less+ memory. (Stephen Morgan)++ ~/src/hledger$ quickbench -w hledger-1.21,hledger+ Running 5 tests 1 times with 2 executables at 2021-06-29 13:13:26 HST:+ + Best times:+ +----------------------------------------------------++--------------+---------++ | || hledger-1.21 | hledger |+ +====================================================++==============+=========++ | -f examples/10000x1000x10.journal print || 1.18 | 0.90 |+ | -f examples/10000x1000x10.journal register || 12.82 | 5.95 |+ | -f examples/10000x1000x10.journal balance || 1.38 | 0.86 |+ | -f examples/1000x1000x10.journal balance --weekly || 0.96 | 0.78 |+ | -f examples/10000x1000x10.journal balance --weekly || 13.07 | 10.79 |+ +----------------------------------------------------++--------------+---------+++- ANSI color is now disabled automatically (on stdout) when the+ `-o/--output-file` option is used (with a value other than `-`).+ (#1533)++- ANSI color is now also available in debug output, determined in the+ usual way by `--color`, `NO_COLOR`, and whether the output (stderr)+ is interactive.+ +- The --version flag shows more details of the build, when known: git+ tag, number of commits since the tag, commit hash, platform and+ architecture. (Stephen Morgan)++- balance: Capitalisation of "account" and "total" (and lack of a+ colon in the latter) in CSV output is now consistent for single- and+ multi-period reports.++- balance reports' CSV output now includes full account names. (#1566)+ (Stephen Morgan)++- csv: We now accept spaces when parsing amounts from CSV. (Eric+ Mertens)++- json: Avoid adding unnecessary decimal places in JSON output. (Don't+ increase them all to 10 decimal places.) (Stephen Morgan)+ +- json: Simplify amount precision (asprecision) in JSON output.+ It is now just the number of decimal places, rather than an object.+ (Stephen Morgan)++- GHC 9.0 is now officially supported, and GHC 8.0, 8.2, 8.4 are not;+ building hledger now requires GHC 8.6 or greater.++- Added a now-required lower bound on containers. (#1514)++Fixes++- Auto posting rules now match postings more precisely, respecting+ `cur:` and `amt:` queries. (#1582) (Stephen Morgan)++- balance reports: Fix empty cells when amounts are too wide to fit+ (broken since 1.20) (#1526). (Stephen Morgan)++- csv: Fix the escaping of double quotes in CSV output (broken in+ 1.21). (Stephen Morgan, #1508)++- register: Fix the running total when there is a report interval+ (broken since 1.19) (#1568). (Stephen Morgan)++- stats: No longer gets confused by posting dates. (#772) (Stephen Morgan)++- timeclock: `hledger print` shows timeclock amounts with just 2+ decimal places again (broken in 1.21). (#1527)++- When all transaction amounts have the same sign, the error message+ no longer adds an inferred price. (#1551) (Stephen Morgan)++- Cleaned up some references to old man pages. (Felix Yan)++# 1.21 2021-03-10++## general++- hledger is now generally about 10% more memory- and time-efficient,+ and significantly more so in certain cases, eg journals with many+ total transaction prices. (Stephen Morgan)++- The `--help/-h` and `--version` flags are no longer position-sensitive;+ if there is a command argument, they now always refer to the command+ (where applicable).++- The new `--info` flag opens the hledger info manual, if "info" is in $PATH.+ `hledger COMMAND --info` will open COMMAND's info node.++- The `--man` flag opens the hledger man page, if "man" is in $PATH.+ `hledger COMMAND --man` will scroll the page to CMD's section, if "less"+ is in $PATH. (We force the use of "less" in this case, overriding any+ $PAGER or $MAN_PAGER setting.)++- Some command aliases, considered deprecated, have been removed:+ `txns`, `equity`, and the single-letter command aliases `a`, `b`,+ `p`, and `r`. This was discussed at+ https://github.com/hledgerorg/hledger/pull/1423 and on the hledger+ mail list. It might annoy some folks; please read the issue and do+ follow up there if needed.+ +- Notable documentation updates:+ the separate file format manuals have been merged into the hledger manual,+ the topic hierarchy has been simplified,+ the `balance` command docs and "commands" section have been rewritten.++## valuation++- Costing and valuation are now independent, and can be combined.+ `--value=cost` and `--value=cost,COMM` are still supported+ (equivalent to `--cost` and `--cost --value=then,COMM` respectively), + but deprecated. (Stephen Morgan)++- `-V` is now always equivalent to `--value=end`. (Stephen Morgan)++- `--value=end` now includes market price directives as well as+ transactions when choosing a valuation date for single-period+ reports. (#1405, Stephen Morgan)++- `--value=end` now picks a consistent valuation date for single- and+ and multi-period reports. (#1424, Stephen Morgan)++- `--value=then` is now supported with all reports, not just register. (Stephen Morgan)++- The too-vague `--infer-value` flag has been renamed to `--infer-market-price`.+ Tip: typing `--infer-market` or even `--infer` is sufficient.+ The old spelling still works, but is now deprecated.++## commands++- add: Infix matches are now scored higher. If the search pattern+ occurs in full within the other description, that match gets a +0.5+ score boost.++- add: `--debug` now shows transaction matching results, useful when+ troubleshooting.++- balance: To accomodate new report types, the+ `--change|--cumulative|--historical|--budget` flags have been split+ into two groups: report type (`--sum|--budget|...`) and accumulation+ type (`--change|--cumulative|--historical`). `--sum` and `--change`+ are the defaults, and your balance commands should still work as+ before. (Stephen Morgan et al, #1353)++- balance: The `--valuechange` report type has been added, showing the+ changes in period-end values. (Stephen Morgan, #1353)++- balance: With `--budget`, the first and last subperiods are enlarged+ to whole intervals for calculating the budget goals also. (Stephen+ Morgan)++- balance: In multi-period balance reports, specifying a report period+ now also forces leading/trailing empty columns to be displayed,+ without having to add `-E`. This is consistent with `balancesheet`+ etc. (#1396, Stephen Morgan)++- balancesheet, cashflow: declaring just a Cash account no longer+ hides other Asset accounts.++- check: Various improvements:++ - check name arguments may be given as case-insensitive prefixes+ - `accounts` and `commodities` may also be specified as arguments+ - `ordereddates` now checks each file separately (#1493)+ - `ordereddates` no longer supports the `--unique` flag or query arguments+ - `payees` is a new check requiring payee declarations+ - `uniqueleafnames` now gives a fancy error message like the others+ - the old `checkdates`/`checkdupes` commands have been dropped++- help: The `help` command now shows only the hledger (CLI) manual,+ its `--info/--man/--pager` flags have been renamed to `-i/-m/-p`,+ and `--cat` has been dropped.++- help: With a TOPIC argument (any heading or heading prefix, case+ insensitive), it will open the manual positioned at this topic if+ possible. (Similar to the new `--man` and `--info` flags described above.)+ <!-- `hledger help print` will show `print`'s doc with the best available viewer (usually info). -->+ <!-- `hledger help print -m` is equivalent to `hledger print --man`.) -->++- payees: Add `--used`/`--declared` flags, like the `accounts` command.++- print: Now always shows amounts with all decimal places,+ unconstrained by commodity display style. This ensures more+ parseable and sensible-looking output in more cases, and behaves+ more like Ledger's print. (There may be a cosmetic issue with+ trailing zeroes.) (#931, #1465)++- print: With `--match`, infix matches are now scored higher, as with+ the add command.++- print: `--match` now provides debug output useful for troubleshooting.++ If you forget to give `--match` an argument, it can confusingly+ consume a following flag. Eg if you write:++ hledger print --match -x somebank # should be: hledger print --match=somebank -x++ it gets quietly parsed as:++ hledger print --match="-x"++ Now you can at least use --debug to figure it out:++ hledger print --match -x somebank --debug+ finding best match for description: "-x"+ similar transactions:+ ...++- roi: Now supports the valuation options (#1417), and uses commodity display styles.+ Also the manual has been simplified, with some content moved to the Cookbook.+ (Dmitry Astapov):++## journal format++- The `commodity` directive now properly sets the display style of the+ no-symbol commodity. (#1461)++## csv format++- More kinds of malformed signed numbers are now ignored, in+ particular just a sign without a number, which simplifies sign+ flipping with amount-in/amount-out.++## API++- API changes include:+ ```+ Hledger.Cli.Utils:+ +journalSimilarTransaction+ + Hledger.Cli.Commands.Add:+ transactionsSimilarTo -> Hledger.Data.Journal.journalTransactionsSimilarTo+ and now takes a number-of-results argument+ ```++# 1.20.4 2021-01-29++- aregister: ignore a depth limit, as in 1.19 (#1468).+ In 1.20-1.20.3, aregister had stopped showing transactions in subaccounts + below a depth limit. Now it properly shows all subaccount transactions, + ensuring that the register's final total matches a balance report with + similar arguments.++# 1.20.3 2021-01-14++- When searching for price chains during valuation/currency conversion:++ - It no longer hangs when there are price loops. (And in case of+ future bugs, it will give up rather than search forever.) (#1439)+ - It now really finds the shortest path. (#1443)+ - Useful progress info is displayed with `--debug=1` or `--debug=2`.++- balance, incomestatement: End-valued multi-period balance change+ reports (eg: `bal -MV`) have been reverted to show value-of-change,+ as in previous hledger versions, rather than change-of-value, for+ now. (#1353, #1428) (Stephen Morgan)++- balance: End-valued balance change reports now choose the same final+ valuation date and show consistent results whether single-period or+ multi-period. (#1424) (Stephen Morgan)++- balance: the `--drop` option now works with `csv` and `html` output.+ (#1456) (Ilya Konovalov)++- check: the `commodities` check, and `-s`/`--strict` mode, now ignore+ the "AUTO" internal pseudo-commodity. (#1419) (Ilya Konovalov)++- register: Then-valued multi-period register reports+ (eg: `register -M --value=then`) now calculate the correct values.+ (#1449) (Stephen Morgan)++- roi: now shows a better error message when required prices are+ missing. (#1446) (Dmitry Astapov)++- The no-symbol commodity's input number format can now be set by a+ `commodity` directive, like other commodities. (#1461)++# 1.20.2 2020-12-28++- help: Fix loss of capitalisation in part of the hledger-ui manual. ++- Fix the info manuals' node structure.++- Drop unused parsec dependency.++# 1.20.1 2020-12-15++- bal, bs, cf, is: In amount-sorted balance reports, equal-balance accounts + are now reliably sorted by name. (Simon Michael, Stephen Morgan)++- help: Fix the topic hierarchy in Info manuals.++# 1.20 2020-12-05++## general++- strict mode: with -s/--strict, hledger requires that+ all accounts and commodities are declared with directives.++- Reverted a stripAnsi change in 1.19.1 that caused a 3x slowdown of amount rendering+ in terminal reports. (#1350)++- Amount and table rendering has been improved, so that stripAnsi is no longer needed.+ This speeds up amount rendering in the terminal, speeding up some reports by 10% or more since 1.19.+ (Stephen Morgan)++- Amount eliding no longer displays corrupted ANSI codes (#1352, Stephen Morgan)++- Eliding of multicommodity amounts now makes better use of available space,+ avoiding unnecessary eliding (showing as many amounts as possible within+ 32 characters). (Stephen Morgan)++- Command line help for --no-elide now mentions that it also disables eliding of+ multicommodity amounts.++- Query terms containing quotes (eg to match account names containing quotes)+ now work properly. (#1368, Stephen Morgan)++- cli, journal: Date range parsing is more robust, fixing failing/incorrect cases such as: (Stephen Morgan)++ - a hyphenated range with just years (`2017-2018`)+ - a hyphenated date with no day in a hyphenated range (`2017-07-2018`)+ - a dotted date with no day in a dotted range (`2017.07..2018.02`)+ +- Debug output is prettier (eg, in colour), using pretty-simple instead of pretty-show.++- csv, timedot, timeclock files now respect command line --alias options,+ like journal files. (#859)++- Market price lookup for value reports is now more robust, fixing several bugs+ (and debug output is more informative).+ There has been a slight change in functionality: when chaining prices,+ we now prefer chains of all "forward" prices, even if longer, with chains+ involving reverse prices being the last resort.+ (#1402)++## commands++- add: number style (eg thousands separators) no longer disturbs the value+ that is offered as default. (#1378)++- bal: --invert now affects -S/--sort-amount, reversing the order. (#1283, #1379) (Stephen Morgan)++- bal: --budget reports no longer insert an extra space inside the brackets. (Stephen Morgan)++- bal: --budget reports now support CSV output (#1155)++- bal, is, bs --change: + Valued multiperiod balance change reports now show changes of value, + rather than the value of changes. (#1353, Stephen Morgan)++- bal: clearer debug output, following debug levels policy++- check: A new command which consolidating the various check-* commands.+ It runs the default, strict, or specified checks and produces+ no output and a zero exit code if all is well.++- check-dates: this command is deprecated and will be removed+ in next release; use "hledger check ordereddates" instead.++- check-dupes: this command is deprecated and will be removed+ in next release; use "hledger check uniqueleafnames" instead.++- import: The journal's commodity styles (declared or inferred) are now applied+ to imported amounts, overriding their original number format.++- roi: TWR now handles same-day pnl changes and cashflows,+ calculation failure messages have been improved, and+ the documentation includes more detail and examples.+ (#1398) (Dmitry Astapov)++## journal format++- The journal's commodity styles are now applied to forecasted transactions. (#1371)++- journal, csv: commodity style is now inferred from the first amount, as documented,+ not the last. This was "working wrongly" since hledger 1.12..++- A zero market price no longer causes "Ratio has zero denominator" error+ in valued reports. (#1373)++## csv format++- The new `decimal-mark` rule allows reliable number parsing+ when CSV numbers contain digit group marks (eg thousands separators).++- The CSV reader's verbose "assignment" debug output is now at level 9.++# 1.19.1 2020-09-07++- Fix alignment of coloured numbers (#1345, #1349, Stephen Morgan)++- Fix a regression in account type autodetection for accounts with+ capitalised names. (#1341)++- Allow megaparsec 9++# 1.19 2020-09-01++## general++- When parsing dates, the year is now required to have at least four+ digits. So eg we no longer accept `200/1/1` as a valid date, it+ would need to be written `0200/1/1`. This was done for.. reasons,+ and is experimental; let us know if it causes you trouble.++- The --color/--colour=WHEN command line option, support for the+ NO_COLOR environment variable, and smarter autodetection of colour+ terminals have been added (#1296)++- Command line options taking a numeric argument are now validated+ more carefully, preventing issues with unexpected negatives or Int+ overflow. (Stephen Morgan)++- In queries, you can now specify a quarter like `2020q1` or `q4`+ (the q is case-insensitive). (#1247, Henning Thieleman, Stephen Morgan)++- In report intervals, `fortnightly` has been added as a synonym for+ `biweekly`. (Stephen Morgan)++- -t and -l command line flags have been added as short forms of+ --tree and --flat (#1286)++- All reports displaying accounts now choose flat mode by default+ (Stephen Morgan)++- Reports now show at most 2 commodities of multicommodity amounts,+ unless the --no-elide flag is used. This helps keep them readable by+ default, since multicolumn, multicommodity balance reports otherwise+ tend to become very wide, especially in tree mode.++- Numbers with more than 255 decimal places, which we do not support,+ now give an error instead of silently misparsing. (#1326)++- Digit groups are now limited to at most 255 digits each. (#1326)++- Account aliases (on command line or in journal) containing a bad+ regular expression now give a more detailed error message.++- A tab character could get parsed as part of a commodity symbol, with+ confusing results. This no longer happens. (#1301, Dmitry Astapov)++- Debug output is now organised better by debug level.+ The levels are:++ 0. normal command output only (no warnings)+ 1. useful warnings & most common troubleshooting info (valuation, eg)+ 2. common troubleshooting info, more detail+ 3. report options selection+ 4. report generation+ 5. report generation, more detail+ 6. input file reading+ 7. input file reading, more detail+ 8. command line parsing+ 9. any other rarely needed or more in-depth info++- Added a missing lower bound for aeson, making cabal installs more+ reliable. (#1268)++- lib: parseAmountQueryTerm: allow whitespace around arg parts (#1312)+ Whitespace around the operator, sign, or number is now tolerated.++## commands++- account,bal,bs,cf,is: --drop now also works in tree mode (Stephen Morgan)++- add: fix an error in the command line help (arguments are inputs,+ not a query)++- aregister: a new command showing a transaction-oriented account+ register, like hledger-ui, hledger-web, or your bank statement. + Each line represents a whole transaction in one account, unlike+ the register command which shows individual postings possibly from+ multiple accounts. You might prefer aregister when reconciling+ real-world asset/liability accounts, and register when reviewing+ detailed revenues/expenses. (#1294)++- bal,bs,cf,is: boring parents are now elided by default in tabular+ balance reports too, like single-column reports. (Stephen Morgan)++- bal,bs,cf,is: monthly column headings are no longer elided to just+ the short month name, if multiple years are being displayed.++- bal --budget's column headings are now end dates rather than+ periods when appropriate (ie with --cumulative or --historical).++- bs,cf,is: -%/--no-total no longer forces --no-total (Stephen Morgan)++- bs,cf,is: --no-total now hides subtotals as well as the grand total+ (Stephen Morgan)++- codes: a new command for listing transaction codes++- print: a new `sql` output format has been added (Dmitry Astapov)++- roi: errors are now shown without a call stack++- tags: add --parsed flag, hide empties without --empty. With the+ --parsed flag, all tags or values are shown in the order they are+ parsed from the input data, including duplicates. With -E/--empty,+ any blank/empty values will also be shown, otherwise they are+ omitted.++## journal format++- account directives can specify a new `Cash` account type. This is a+ subtype of `Asset`, denoting accounts which should be displayed+ in `cashflow` reports. + +- The built-in regular expressions for choosing default account types+ have been tweaked, and documentation for account types has been+ improved.++## csv format++- Inferring the appropriate default field separator based on file+ extension (, for .csv, ; for .ssv, \t for .tsv) now works as+ documented.++- Conditional rule patterns can now be grouped with the `&` (AND) operator,+ allowing more powerful matching. (Michael Sanders)++- Invalid csv rules files now give clearer parse error messages.+ (Dmitry Astapov)++- "If tables", a compact bulk format for conditional rules, have been+ added. (Dmitry Astapov)++- csv conversion with a lot of conditional rules is now faster (Dmitry Astapov)++# 1.18.1 2020-06-21++- journal: document recursive wildcards++- by default, value reports work as in 1.17; to infer market prices from+ transactions, add the new --infer-value flag. (#1239, #1253)++- organise debug output better++- print: amounts in csv output now have commodity symbol, digit group+ separators and prices removed (Dmitry Astapov)++# 1.18 2020-06-07++## General++- The --forecast flag now takes an optional argument+ (--forecast=PERIODICEXPR), allowing periodic transactions to+ start/end on any date and to overlap recorded transactions.+ (#835, #1236) (Dmitry Astapov)++- An upper case file extension no longer confuses file format+ detection. (#1225)++- In the commands list, redundant source scripts are now hidden+ properly when a corresponding .com/.exe file exists. (#1225)++- We now show `..` instead of `-` to indicate date ranges, eg in+ report titles, to stand out more from hyphenated dates. + (Stephen Morgan)+ +- Period expressions (eg in -p, date:, and periodic rules) now accept+ `to`, `until`, `-`, or `..` as synonyms. (Stephen Morgan)++- When parsing amounts, whitespace between sign and number is now allowed.++- A clearer error message is shown on encountering a malformed regular+ expression.++## commands++- commands allowing different output formats now list their supported+ formats accurately in --help (#689)++- commands allowing JSON output now actually produce JSON (#689)++- bal, bs: show .. (not ,,) in report titles, like other reports++## journal format++- We now also infer market prices from transactions, like Ledger.+ See https://hledger.org/hledger.html#market-prices (#1239). + + Upgrade note: this means value reports (-V, -X etc.) can give+ different output compared to hledger 1.17. If needed, you can+ prevent this by adding a P directive declaring the old price, on or+ after the date of the transaction causing the issue.++- The include directive now accepts a file format prefix, like the+ -f/--file option. This works with glob patterns too, applying the+ prefix to each path. This can be useful when included files don't+ have the standard file extension, eg:++ include timedot:2020*.md++- We now accept (and ignore) Ledger-style lot dates+ (`[DATE]`) and four lot price forms (`{PRICE}`, `{{PRICE}}`,+ `{=PRICE}`, `{{=PRICE}}`), anywhere after the posting amount but+ before any balance assertion.++- We now accept Ledger-style parenthesised "virtual posting+ costs" (`(@)`, `(@@)`). In hledger these are equivalent to the+ unparenthesised form.++- The unbalanced transaction error message is clearer, especially when+ postings all have the same sign, and is split into multiple lines+ for readability.++## csv format++- You can now generate up to 99 postings in a transaction. (Vladimir Sorokin)++- You can now generate postings with an explicit 0 amount. (#1112)++- For each posting, when both numbered and unnumbered amount+ assignments are active (eg: both `amount` and `amount1`), we ignore+ the unnumbered ones. This makes it easier to override old `amount`+ rules.+ +- Fix a 1.17.1 regression involving amount-in/amount-out. (#1226)++- Assigning too many non-zero or zero values to a posting amount now+ gives a clearer error. (#1226)++# 1.17.1.1 2020-03-19++- update bounds after some belated hledger-* version bumps++# 1.17.1 2020-03-19++- csv: amount1 no longer forces a second posting or second posting amount.+ The "special handling for pre 1.17 rules" should now be less+ noticeable. amount1/amount2 no longer force a second posting or+ explicit amounts on both postings. (Only amount/amount-in/amount-out+ do that.) Error messages and handling of corner cases may be more+ robust, also.++- journal: a commodity directive without decimal mark now gives a more+ verbose error message with examples++- journal: inclusive balance assignments now work (#1207)++- require newer Decimal, math-functions libs to ensure consistent+ rounding behaviour, even when built with old GHCs/snapshots. + hledger uses banker's rounding (rounds to nearest even number, eg+ 0.5 displayed with zero decimal places is "0").++# 1.17 2020-03-01++## General++- hledger's default date format is now YYYY-MM-DD (ISO-8601 dates).+ (Brian Wignall, Jakob Schöttl, Simon Michael)++- Drop the file format auto-detection feature.++ For a long time hledger has auto-detected the file format when it's+ not known, eg when reading from a file with unusual extension (like+ .dat or .txt), or from standard input (-f-), or when using the+ include directive (which currently ignores file extensions). This+ was done by trying all readers until one succeeded. This worked+ well in practice. But recent changes to timedot format have made+ this kind of auto-detection unreliable. (timedot and journal formats+ overlap).++ For predictability and to minimise confusion, hledger will no longer+ guess; when there's no file extension or reader prefix available, it+ always assumes journal format.++ To specify one of the other formats, you must use its standard file+ extension (`.timeclock`, `.timedot`, `.csv`, `.ssv`, `.tsv`), or a+ reader prefix (`-f csv:foo.txt`, `-f timedot:-`).++ Experimental, feedback welcome.++- Fix extra $ symbol (Mateus Furquim)++- --output-format now rejects invalid formats++- Numbers in JSON output now provide a floating point Number+ representation as well as our native Decimal object representation,+ since the later can sometimes contain 255-digit integers. The+ floating point numbers can have up to 10 decimal digits (and an+ unbounded number of integer digits.)+ Experimental, suggestions needed. (#1195)++- Fix finding latest date in queryEndDate Or queries and simplify+ date comparison code. (Stephen Morgan)++- Fix issue 457. (Jacek Generowicz)+ Issue #457 pointed out that commands such as++ hledger ui 'amt:>200'++ failed. This was because the process of dispatching from `hledger ui`+ to `hledger-ui` (note addition of `-`) lost the quotes around+ `amt:>20` and the `>` character was interpreted as a shell redirection+ operator, rather than as part of the argument.++ The machinery for quoting or escaping arguments which contain+ characters which require quoting or escaping (thus far whitespace and+ quotes) already existed. This solution simply adds shell stdio+ redirection characters to this set.++## commands++- add: you can use `<` to undo and redo previous inputs (Gaith Hallak)++- bs, cf, is, bal, print, reg: support json output++- bs, cf, is: fix excess subreport columns in csv output++- bs, cf, is, bal: fix an issue with border intersections in+ --pretty-tables output. (Eric Mertens)++- close: fix a rounding bug that could generate unbalanced transactions. (#1164)++- close: hide cost prices by default, show them with --show-costs.+ close no longer preserves costs (transaction prices) unless you ask+ it to, since that can generate huge entries when there are many+ foreign currency/investment transactions. (#1165)++- close: equity amounts are omitted by default, for simpler entries;+ -x/--explicit shows them (usually causing more postings). (#1165)++- close: --interleaved generates equity postings alongside each closed+ account, making troubleshooting easier.++- close: "equity:opening/closing balances" is now the default+ closing and opening account.++- close: --close-desc/--open-desc customise the closing/opening+ transaction descriptions. (#1165)++- close: some --open*/--close* flags have been simplified for memorability:++ --closing -> --close+ --opening -> --open+ --close-to -> --close-acct+ --open-from -> --open-acct++ The old flags are accepted as hidden aliases, and deprecated. (#1165)++- print, register: a new valuation type, --value=then, shows the+ market value at each posting's date.++- print: -V/-X/--value now imply -x/--explicit, as -B/--cost does.+ This avoids a bug where print -V of a transaction with an implicit+ commodity conversion would convert only some of its postings to value.++## journal format++- The include directive no longer tries all readers. It now picks+ just one, based on the included file's extension, defaulting to+ journal. (It doesn't yet handle a reader prefix.)++- The default commodity (D) directive now limits display precision too. (#1187)+ D directives are now fully equivalent to commodity directives for+ setting a commodity's display style. (Previously it couldn't limit+ the number of decimal places.) When both kinds of directive exist,+ commodity directives take precedence. When there are multiple D+ directives in the journal, only the last one affects display style.++## csv format++- Conditional blocks can now match single fields. \o/++- The experimental --separator command line option has been dropped,+ replaced a new `separator` directive in CSV rule files. (Aleksandar Dimitrov)+ Also the `.tsv` and `.ssv` file extensions are now recognised,+ and set the default `separator` to TAB and semicolon respectively.+ (#1179)++- Allow manual assignment of the "expenses:unknown" account name. (#1192)++- CSV rule keywords are now case insensitive. (Aleksandar Dimitrov)++## timeclock format++- Misc. fixes making parsing more robust. (Jakob Schöttl)++## timedot format++- More support for org mode: org headlines can now be used for date+ lines and timelog items (the stars are ignored). Also, any org+ headlines before the first date line are ignored.++- You can now write a description after a date, which will be used in+ all of that day's transactions.++# 1.16.2 2020-01-14++- add support for megaparsec 8 (#1175)+ +- close: mention --close-to/--open-from in docs+ +# 1.16.1 2019-12-03++- Drop unnecessary mtl-compat dependency++- Fix building with GHC 8.0, 8.2++# 1.16 2019-12-01++## General++- add support for GHC 8.8, base-compat 0.11 (#1090)++- drop support for GHC 7.10++- The benchmark suite has been disabled.++- The --anon flag now also anonymises transaction codes and account+ names declared with account directives. (Mykola Orliuk) (#901)++## commands++- balance/bs/cf/is: balance commands now support the -%/--percent flag+ to show amounts as percentages of the column's total. (Michael Kainer)++ If there are multiple commodities involved in a report hledger bails+ with an error message. This can be avoided by using -B/--cost. Also note+ that if one uses -% with the balance command the chances are high that+ all numbers are 0. This is due to the fact that by default balance sums+ up to zero. If one wants to use -% in a meaningful way with balance one+ has to add a query.++ In order to keep the implementation as simple as possible --tree has no+ influence over how the percentages are calculated, i.e., the percentages+ always represent the fraction of the columns total. If one wants to know+ the percentages relative to a parent account, one has to use a query to+ narrow down the accounts.++- balance: --budget no longer errors when there is neither budget nor+ transactions in the report period (Dmitry Astapov)++- balance: --budget has improved debug output (shows budget txns)+ (Dmitry Astapov)++- check-dates: now sets the exit status code (Amitai Burstein)++- close: no longer strips zeroes after the decimal mark, and preserves+ parseable output (#1137)++- close: the --close-to, --open-from options allow closing/opening+ account names to be chosen++- import: create the journal if missing, like the add command+ Streamlines import/migration instructions.++- import: --catchup marks all transactions imported, without importing++- import: more informative output: mention the input files, also show+ a message when nothing was imported++- prices: show price amounts with proper display style; always show+ full precision++- roi: don't give an error with empty input data (Dmitry Astapov)++- tests: unit tests are now run by tasty, and show coloured output by default (#1090).+ Test running options have changed, see the command help. + Some unit tests have been collapsed, so the reported test count has+ dropped a little.++## journal format++- Fixed: wrong dates generated by certain periodic transaction rules,+ eg "~ every 12 months from 2019/04". (Dmitry Astapov) (#1085)++## csv format++CSV conversion is now more powerful (#1095, Dmitry Astapov, Simon Michael):++- A variable number of postings can be generated, from zero to nine. (#627, #1095)++- In conditional blocks, `skip` can be used to skip one or more+ records after a pattern match, or the new `end` rule can be used to+ skip all remaining records. (#1076)++- The new `balance-type` CSV rule controls which kind of balance+ assertions are generated (=, ==, =*, ==*)++- Postings with balance assignments can be generated. (#1000)++- Both the amount-in/amount-out fields having a non-empty value is now+ accepted, as long as one of them is zero. (#570)++- Line feeds/carriage returns in (quoted) CSV values are now converted+ to spaces during conversion. (#416, #841)++- Field assignments can now unset a field (eg a posting can be+ suppressed by assigning no value to its account).++- CSV records with varying lengths are now allowed; short records will+ be padded with empty fields as needed. This allows us to handle eg+ exported Google spreadsheets, where trailing empty fields are omitted.++- Journals generated from CSV are now finalised and checked like+ ordinary journals (#1000). So invalid transactions generated from+ CSV will be rejected, amount styles will be standardised etc.++- Fixed: we no longer add an extra (third) space between description and comment.++- Fixed: whitespace on the line after an if block no longer causes misparsing. (#1120)++- Fixed: an empty field assignment no longer consumes the next line. (#1001)++- Fixed: interpolation of field names containing punctuation now works.++- Docs have been rewritten and clarified.++Migration notes:++- When `print`ing from CSV, there is now one less space between+ transaction descriptions and comments, which may generate noisy+ diffs if you are comparing old and new reports. diff -w+ (--ignore-all-space) will filter these out.++- CSV rules now give you more freedom to generate any journal+ entries you want, including malformed or unbalanced ones. + The csv reader now checks the journal after conversion,+ so it will report any problems with the generated entries.++- Balance assertions generated from CSV are not checked, currently.+ This is appropriate when you are downloading partial CSV data to+ be merged into your main journal. If you do need to check balance+ assertions right away, you can pipe through hledger again:++ $ hledger -f a.csv print | hledger -f- print++# 1.15.2 2019-09-05++- -V and -X now respect a report end date (set with -e or -p or date:)+ when choosing the valuation date (which determines the market prices+ used). This is how -V works in hledger 1.14 and Ledger, and it means+ that -V isn't exactly equivalent to either --value=end or+ --value=now. Possibly some other corner cases in valuation have been+ fixed as well. "Effect of --value on reports" in the hledger manual+ has been updated and is more accurate.++# 1.15.1 2019-09-02++- add commodities, descriptions, diff, notes, payees commands to manual++# 1.15 2019-09-01++## General++- There is a new valuation option `--value=TYPE[,COMM]`, with+ backwards-compatible `-B/--cost`, `-V/--market`, `-X/--exchange=COMM`+ variants. These provide control over valuation date (#329), and+ inference of indirect market prices (similar to Ledger's -X) (#131).+ Experimental.+ +- Market valuation (-V/-X/--value) is now much faster (#999):++ +-------------------------------------------++--------------+--------------++ | || hledger-1.14 | hledger-1.15 |+ +===========================================++==============+==============++ | -f examples/10000x1000x10.journal bal -Y || 2.43 | 2.44 |+ | -f examples/10000x1000x10.journal bal -YV || 44.91 | 6.48 |+ | -f examples/10000x1000x10.journal reg -Y || 4.60 | 4.15 |+ | -f examples/10000x1000x10.journal reg -YV || 61.09 | 7.21 |+ +-------------------------------------------++--------------+--------------+++- How date options like `-M` and `-p` interact has been updated and clarified.+ (Jakob Schöttl) (#1008, #1009, #1011)++- Restore `--aux-date` and `--effective` as `--date2` aliases (#1034).+ These Ledger-ish spellings were dropped over the years, to improve+ `--help`'s layout. Now we support them again, as semi-hidden flags+ (`--help` doesn't list them, but they are mentioned in `--date2`'s help).++## commands++- add, web: on Windows, trying to add transactions to a file path+ containing trailing periods (eg `hledger add -f Documents.\.hledger.journal`) + now gives an error, since this could cause data loss otherwise (#1056).+ This affects the add command and hledger-web's add form.++- bal: --budget: don't always convert to cost.++- bal: --budget: don't show a percentage when budgeted and actual+ amounts are in different commodities.++- bal/bs/bse: `-H/--historical` or `--cumulative` now disables `-T/--row-total` (#329).+ Multiperiod balance reports which show end balances (eg, `bal -MH` or `bs -M`)+ no longer show a Totals column, since summing end balances generally+ doesn't make sense.++- bs: show end date(s) in title, not transactions date span (#1078)+ Compound balance reports showing ending balances (eg balancesheet),+ now show the ending date (single column) or range of ending+ dates (multi column) in their title. ,, (double comma) is used+ rather than - (hyphen) to suggest a sequence of discrete dates+ rather than a continuous span.++- close: preserve transaction prices (costs) accurately (#1035).+ The generated closing/opening transactions were collapsing/misreporting+ the costs in balances involving multiple costs.+ Now, each separately-priced amount gets its own posting.+ (And only the last of these (for each commodity) gets a balance assertion.)+ Also the equity posting's amount is now always shown explicitly, + which in multicommodity situations means that multiple equity postings are shown. + The upshot is that a balance -B report will be unchanged after+ the closing & opening transactions generated by the close command.++- descriptions, payees, notes commands added (Caleb Maclennan)++- diff: Gabriel Ebner's hledger-diff is now a built in command,+ and https://github.com/gebner/hledger-diff is deprecated.++- help: don't require a journal file++- print: now also canonicalises the display style of balance assertion amounts (#1042)++- reg: show negative amounts in red, like balance and Ledger++- reg: fix `--average`, broken since 1.12 (#1003)++- stats: show count of market prices (P directives), and the commodities covered++- tags: add --values flag to list tag values.++- tags: now runs much faster when there many tags++## journal format++- Transactions and postings generated/modified by periodic transaction+ rules and/or transaction modifier rules are now marked with tags+ (`generated-transaction`, `generated-posting`, `modified`) for+ easier troubleshooting and filtering.++## csv format++- When interpolating CSV values, outer whitespace is now stripped.+ This removes a potential snag in amount field assignments (#1051),+ and hopefully is harmless and acceptable otherwise.++- We no longer add inter-field spaces in CSV error messages.+ Some CSV errors would show the problem record, eg:++ 2000-01-01,a,"1"+ + with extra spaces added, eg:++ the CSV record is: "2000-01-01", "a", "1"++ which was inaccurate and not valid RFC-4180 CSV format.++- CSV parse errors are human-readable again (broken since 1.11) (#1038)++- CSV rules now allow the amount to be unassigned, if there is an+ assignment to "balance" (generating a balance assignment in this+ case). (#1000)++# 1.14.2 2019-03-20++- require easytest <0.3 to fix build issue++- fix some CSV parse errors which weren't in human readable format++# 1.14.1 2019-03-01++- fix missing Commodities.txt build error++# 1.14 2019-03-01++- journal: subaccount-including balance assertions have been+ added, with syntax =* and ==* (experimental) (#290)++- new commodities command lists commodity symbols++- new --invert option flips sign of amounts in reports++# 1.13.2 2019-02-04++- print, register: restore the accidentally dropped -o, -O flags (#967)++# 1.13.1 2019-02-02++- stop depending on here to avoid haskell-src-meta/stackage blockage.++# 1.13 2019-02-01++- cli: reorganised commands list. Addons now have a + prefix.++- cli: the command line help and manual section for all hledger's+ commands are now consistent, and generated from the same source.++- cli: comprehensive bash completion support is now provided (in+ shell-completion/). See how-to in the Cookbook. (Jakob Schöttl)++- balance --budget: budget amounts now aggregate hierarchically, like+ account balances. Unbudgeted accounts can be shown with -E/--empty+ (along with zero-balance accounts), and the --show-budgeted flag has+ been dropped. (Dmitry Astapov)++- balance: new --transpose flag switches the rows and columns of+ tabular balance reports (in txt and csv output formats). (Dmitry+ Astapov)++- close: generated balance assertions now have exact amounts with all+ decimal digits, ignoring display precision. Also, balance assertion+ amounts will no longer contain prices. (#941, #824, #958)++- files: now shows up in the commands list++- import: be silent when there's nothing to import++- roi: percentages smaller than 0.01% are displayed as zero (Dmitry+ Astapov)++- stats, ui: correct file order is preserved when using --auto (#949)++- journal: account directive: the account name can now be followed by+ a comment on the same line++- journal: account directive: account types for the bs/bse/cf/is+ commands can now be set with a `type:` tag, whose value is `Asset`,+ `Liability`, `Equity`, `Revenue`, `Expense`, `A`, `L`, `E`, `R` or+ `X` (case-insensitive). The previous syntax (`account assets A`) is+ now deprecated.++- journal: account directive: account sort codes like `account 1000`+ (introduced in 1.9, deprecated in 1.11) are no longer supported.++- journal: transaction modifiers (auto postings) can affect periodic+ transactions (--auto can add postings to transactions generated with+ --forecast). (Dmitry Astapov)++- journal: balance assertion errors now show exact amounts with all+ decimal digits. Previously it was possible, in case of a commodity+ directive limiting the display precision, to have a balance+ assertion error with asserted and actual amounts looking the+ same. (#941)++- journal: fixed a periodic transaction parsing failure (#942) (Dmitry+ Astapov)++# 1.12.1 2018-12-03++- roi: use math-functions lib instead of statistics,+ be more stackage nightly compatible++# 1.12 2018-12-02++- install script: ensure a new-enough version of stack; more informative output++- build with GHC 8.6/base-4.12 (Peter Simons)++- add required upper bound for statistics (Samuel May)++- --anon anonymises more thoroughly (including linked original postings) (Moritz Kiefer)++- unbalanced transaction errors now include location info (Mykola Orliuk)++- accounts command: --drop also affects the default flat output, without needing an explicit --flat flag++- accounts command: the --codes flag has been dropped++- accounts command: filtering by non-account-name queries now works++- add command: fix transaction rendering regression during data entry and in journal file++- balance command: fix wrongful eliding of zero-balance parent accounts in tree mode (Dmitry Astapov)++- journal format, bs/bse/cf/is commands: account directives can declare account types (#877)+ Previously you had to use one of the standard english account names+ (assets, liabilities..) for top-level accounts, if you wanted them to+ appear in the right place in the balancesheet, balancesheetequity,+ cashflow or incomestatement reports.++ Now you can use your preferred account names, and use account directives+ to declare which accounting class (Asset, Liability, Equity, Revenue or+ eXpense) an account (and its subaccounts) belongs to, by writing one of+ the letters A, L, E, R, X after the account name, after two or more+ spaces. This syntax may change (see issue). Experimental.++ Currently we allow unlimited account type declarations anywhere in the+ account tree. So you could declare a liability account somewhere under+ assets, and maybe a revenue account under that, and another asset account+ even further down. In such cases you start to see oddities like accounts+ appearing in multiple places in a tree-mode report. I have left it this+ way for now in case it helps with, eg, modelling contra accounts, or+ combining multiple files each with their own account type+ declarations. (In that scenario, if we only allowed type declarations on+ top-level accounts, or only allowed a single account of each type,+ complications seem likely.)++- journal format: periodic transaction rules now require a double space separator.+ In periodic transaction rules which specify a transaction description or+ same-line transaction comment, this must be separated from the period+ expression by two or more spaces, to prevent ambiguous parsing. Eg+ this will parse correctly as "monthly" thanks to the double space:++ ~ monthly In 2020 we'll end this monthly transaction.++- journal format: exact/complete balance assertions (Samuel May).+ A stronger kind of balance assertion, written with a double equals sign,+ asserts an account's complete account balance, not just the balance in+ one commodity. (But only if it is a single-commodity balance, for now.)+ Eg:++ 1/1+ (a) A 1+ (a) B 1+ (a) 0 = A 1 ; commodity A balance assertion, succeeds+ (a) 0 == A 1 ; complete balance assertion, fails++- journal format: account directives now allow whitespace or a comment after the account name++- journal format: using \~ for home directory in include directives now works (#896) (Mykola Orliuk)++- journal format: prevent misleading parse error messages with cyclic include directives (#853) (Alex Chen)++- journal format: transaction modifier multipliers handle total-priced amounts correctly (#928).+ Multipliers (*N) in transaction modifier rules did not multiply+ total-priced amounts properly. Now the total prices are also multiplied,+ keeping the transaction balanced.++- journal format: do amount inference/balance assignments/assertions before transaction modifiers (#893, #908) (Jesse Rosenthal)+ Previously, transaction modifier (auto postings) rules were applied+ before missing amounts were inferred. This meant amount multipliers could+ generate too many missing-amount postings, making the transaction+ unbalanceable (#893).++ Now, missing amount inference (and balance assignments, and balance+ assertions, which are interdependent) are done earlier, before+ transaction modifier rules are applied (#900, #903).++ Also, we now disallow the combination of balance assignments and+ transaction modifier rules which both affect the same account, which+ could otherwise cause confusing balance assertion failures (#912).+ (Because assignments now generate amounts to satisfy balance assertions+ before transaction modifier rules are applied (#908).)++- journal format: periodic transaction rules are now aware of Y default year directives. (#892)+ Ie when a default year Y is in effect, they resolve partial or relative+ dates using Y/1/1 as the reference date, rather than today's date.++# 1.11.1 2018-10-06++- fix wrong transaction rendering in balance assertion errors and when+ using the add command++# 1.11 2018-09-30++- The default display order of accounts is now influenced by+ the order of account directives. Accounts declared by account+ directives are displayed first (top-most), in declaration order,+ followed by undeclared accounts in alphabetical order. Numeric+ account codes are no longer used, and are ignored and considered+ deprecated.++ So if your accounts are displaying in a weird order after upgrading,+ and you want them alphabetical like before, just sort your account+ directives alphabetically.++- Account sorting (by name, by declaration, by amount) is now more+ robust and supported consistently by all commands (accounts,+ balance, bs..) in all modes (tree & flat, tabular & non-tabular).++- close: new --opening/--closing flags to print only the opening or+ closing transaction++- files: a new command to list included files++- prices: query arguments are now supported. Prices can be filtered by+ date, and postings providing transaction prices can also be filtered.++- rewrite: help clarifies relation to print --auto (#745)++- roi: a new command to compute return on investment, based on hledger-irr++- test: has more verbose output, more informative failure messages,+ and no longer tries to read the journal++- csv: We use a more robust CSV lib (cassava) and now support+ non-comma separators, eg --separator ';' (experimental, this flag+ will probably become a CSV rule) (#829)++- csv: interpolated field names in values are now properly case insensitive, so+ this works:++ fields ...,Transaction_Date,...+ date %Transaction_Date++- journal: D (default commodity) directives no longer break multiplier+ amounts in transaction modifiers (AKA automated postings) (#860)++- journal: "Automated Postings" have been renamed to "Transaction Modifiers".++- journal: transaction comments in transaction modifier rules are now parsed correctly. (#745)++- journal: when include files form a cycle, we give an error instead+ of hanging.++- upper-case day/month names in period expressions no longer give an error (#847, #852)++# 1.10 2018-06-30++- journal: many parse error messages have become more informative, and+ some now show the source line and error location.++- journal: ;tag: is no longer parsed as a tag named ";tag" (#655)++- journal: transaction price amounts having their own price amounts is+ now a parse error++- journal: amounts with space as digit group separator and trailing whitespace+ now parse correctly (#780)++- journal: in amounts containing digits and a single space, the space+ is now interpreted as a digit group separator, not a decimal separator (#749)++- journal: in commodity/format/D directives, the amount must now include a decimal separator.++ When more precise control is needed over number parsing, our+ recommended solution is commodity directives. Commodity directives+ that don't specify the decimal separator leave things ambiguous,+ increasing the chance of misparsing numbers. In some cases it could+ cause amounts with a decimal point to be parsed as if with a digit+ group separator, so 1.234 became 1234.++ It seems the simple and really only way to do this reliably is to require+ an explicit decimal point character. Most folks probably do this already.+ Unfortunately, it makes another potential incompatibility with ledger and+ beancount journals. But the error message will be clear and easy to+ work around.++- journal: directives currently have diverse and somewhat tricky+ semantics, especially with multiple files. The manual now describes+ their behaviour precisely.++- journal: `alias` and `apply account` directives now affect `account` directives (#825)++- journal: periodic transactions can now have all the usual transaction fields+ (status mark, code, description, comment), for generating more expressive+ forecast transactions.++- journal: forecast transactions now have the generating period+ expression attached as a tag named "recur".++- journal: periodic transactions now start on the first instance of the+ recurring date, rather than the day after the last regular transaction (#750)++- journal: periodic transaction rules now allow period expressions relative to today's date++- csv: amount-in/amount-out errors are more detailed++- balance: --drop is now ignored when not in flat mode,+ rather than producing a corrupted report (#754)++- budget: --drop now preserves the <unbudgeted> top-level account in --budget reports++- register: in CSV output, the code field is now included (#746)++- smart dates now allow the YYYYMM format, and are better documented++- use hledger-lib 1.10++# 1.9.1 2018-04-30++- use hledger-lib 1.9.1++- budget (balance --budget): monthly columns are displayed in the+ proper order. This fixes a regression in 1.9.++- budget: budgets can be built from periodic transactions with+ different intervals again. In 1.9, budgets were restricted to a+ single interval, but this was a mistake. This restores the 1.5+ behaviour.++- budget: budget reports are more intuitive and much less likely to+ produce no output.++- budget: when no report interval is specified, a budget report for+ the whole journal period is shown.++- budget: periodic transactions and the requested report period can+ each have their own start/end dates, and the resulting report will+ span the union of those periods, showing zeroes where data is+ missing.++- budget: total row and total/average columns are now calculated correctly++- budget: actual, percentage, and goal amounts are now aligned in+ columns for better readability (usually, unless numbers get huge).++- budget: combining --budget and --sort-amount is not yet supported+ and now gives an error.++- csv: handle "-%amount" in a rule when the CSV amount is parenthesised (#736)++- journal: automated postings are now generated early, before journal finalisation,+ so they are present for amount inference, transaction balancing, and balance assertions+ (#729)++- journal: automated postings are now inserted right after the posting that triggered them+ (#729)++- cli: command-line account aliases are now applied early, before journal finalisation,+ so they are equivalent to alias directives in the journal (#730)++- journal: inferred amounts now have the appropriate standard amount style applied+ (setting the precision correctly, eg). (#737)++- journal: when checking for balanced transactions, amount styles declared with+ commodity directives are also used (previously only inferred amount styles were).++# 1.9 2018-03-31++- support ghc 8.4, latest deps++- journal: account directives can define a numeric account code to+ customize sorting. bal/bs/cf/is will sort accounts by account code,+ if any, then account name.++- journal: support scientific number notation (#704, #706)++- csv: reading a CSV file containing no records is no longer an error++- cli: when the system text encoding is UTF-8, ignore any UTF-8 BOM+ prefix found when reading files. (Paypal's new CSV has this BOM+ prefix, causing a confusing parse error.)++- cli: tabular reports no longer have a trailing blank line added.+ (This allows omitting the ">=0" delimiters in our functional tests,+ making them easier to read and maintain.)++- acc: the accounts command now has --declared and --used flags++- bal: the --invert flag flips all signs++- bal: --drop now works with CSV output++- bal/bs/bse/cf/is: show overall report span in title++- bal/bs/bse/cf/is: show short month names as headings in monthly reports++- bal/bs/bse/cf/is: these commands can now generate HTML output++- bal/bs/is/cf: drop short name and indent fields from multicolumn CSV++- bs/bse/cf/is: these, the "financial statement" commands, now show+ normal income, liability and equity balances as positive numbers.+ Negative numbers now indicate a contra-balance (eg an overdrawn+ checking account), a net loss, or a negative net worth. This makes+ these reports more like conventional financial statements, and easier+ to read and share with others. (Other commands, like balance, have not+ changed.) (experimental)++- bs/cf/is: always show a tabular report, even with no report+ interval. Previously you would get a simple borderless report like+ the original balance command. Less code, fewer bugs.++- bs/bse/cf/is: in CSV output, don't repeat the headings row for each subreport++- budget: warn that CSV output with bal --budget is unimplemented++- budget: bal --budget shows budget goals even with no or zero actual amounts.+ Makes budget reports more intuitive, at the cost of a temporary hack+ which may misorder columns in some cases (if actual and budget+ activity occur in a different range of columns).++- budget: --budget uses only periodic txns with the selected interval.\+ Budgets with different interval, eg a daily and weekly budget, are independent.++- budget: show mostly fixed-width columns for readability++- budget: fix bug where a budget report could include budget goals+ ending on the day before the report start date (splitSpan issue)++- close: the equity command has been renamed to close. It now ignores+ any begin date (it always closes historical end balances). It also+ ignores --date2.++# 1.5 2017-12-31++- --auto adds Ledger-style automated postings to transactions (Dmitry Astapov, Mykola Orliuk)++- --forecast generates Ledger-style periodic transactions in the future (Dmitry Astapov, Mykola Orliuk)++- -V/--value uses today's market prices by default, not those of last transaction date. #683, #648++- add: suggest implied (parent) and declared (by account directives) account names also++- bal: --budget shows performance compared to budget goals defined+ with periodic transactions. Accounts with budget goals are+ displayed folded (depth-clipped) at a depth matching the budget+ specification. Unbudgeted accounts are hidden, or with+ --show-unbudgeted, shown at their usual depth. (Dmitry Astapov)++- import: the output of --dry-run is now valid journal format++- print: -B shows converted amounts again, as in 1.1, even without+ -x. #551 (Mykola Orliuk, Simon Michael)++- tag: the first argument now filters tag names, additional arguments+ filter transactions (#261)++- remove upper bounds on all but hledger* and base (experimental)++# 1.4 2017-09-30++- cli: a @FILE argument reads flags & args from FILE, one per line++- cli: reorganized commands list, added some new command aliases:++ - accounts: a+ - balance: b+ - print: p, txns+ - register: r++- cli: accept -NUM as a shortcut for --depth=NUM (eg: -2)++- cli: improve command-line help for --date2 (#604)++- cli: make --help and -h the same, drop --man and --info for now (#579)++- help: offers multiple formats, accepts topic substrings.+ The separate info/man commands have been dropped. help now+ chooses an appropriate documentation format as follows:++ - it uses info if available,+ - otherwise man if available,+ - otherwise $PAGER if defined,+ - otherwise less if available,+ - otherwise it prints on stdout+ - (and it always prints on stdout when piped).++ You can override this with the `--info`/`--man`/`--pager`/`--cat` flags.+ (#579)++- bal/bs/cf/is: --sort-amount/-S sorts by largest amount instead of+ account name++- bs/cf/is: support --output-file and --output-format=txt\|csv+ The CSV output should be reasonably ok for dragging into a+ spreadsheet and reformatting.++- bal/bs/cf/is: consistent double space between columns, consistent+ single final blank line. Previously, amounts wider than the column+ headings would be separated by only a single space.++- bs/is: don't let an empty subreport disable the grand totals (fixes #588)++- cf: exclude asset accounts with ":fixed" in their name (Christian G. Warden, Simon Michael, #584)++- new balancesheetequity command: like balancesheet but also shows+ equity accounts (Nicholas Niro)++- new import command: adds new transactions seen in one or more input+ files to the main journal file++- print: --new shows only transactions added since last time+ (saves state in .latest.JOURNALFILE file)++- new tags command: lists tags in matched transactions++- most addons formerly shipped in bin/ are now builtin commands. These+ include: check-dates, check-dupes, equity, prices, print-unique,+ register-match, rewrite.++- refactor: new Commands module and subdirectory.+ Builtin commands are now gathered more tightly in a single module,+ Hledger.Cli.Commands, facilitating change. The legacy "convert"+ command has been dropped.++- refactor: BalanceView -> CompoundBalanceCommand++- deps: drop support for directory < 1.2++- deps: allow ansi-terminal 0.7++- deps: drop oldtime flag, require time 1.5+++- deps: simplify shakespeare bounds++- deps: remove ghc < 7.6 support++# 1.3.1 2017-08-25++- bs/is: don't let an empty subreport disable the grand totals (#588)++- allow megaparsec 6 (#594)++- allow megaparsec-6.1 (Hans-Peter Deifel)++- restore upper bounds on hledger packages++# 1.3 2017-06-30++The "uncleared" transaction/posting status, and associated UI flags+and keys, have been renamed to "unmarked" to remove ambiguity and+confusion. This means that we have dropped the `--uncleared` flag,+and our `-U` flag now matches only unmarked things and not pending+ones. See the issue and linked mail list discussion for more+background. (#564)++Also the -P short flag has been added for --pending, and the -U/-P/-C+flags can be combined.++bs/is: fix "Ratio has zero denominator" error (#535)++bs/is/cf: fix --flat (#552) (Justin Le, Simon Michael)++bal/bs/is/cf: show negative amounts in red (Simon Michael, Justin Le).+These commands now shows negative amounts in red, when hledger detects+that ANSI codes are supported, (ie when TERM is not "dumb" and stdout+is not being redirected or piped).++print: show pending mark on postings (fixes #563).+A pending mark on postings is now displayed, just like a cleared mark.+Also there will now be a space between the mark and account name.++print: amounts are now better aligned, eg when there are posting+status marks or virtual postings++# 1.2 2017-03-31++## CLI++"hledger" and "hledger -h" now print a better organised commands list+and general usage message respectively (#297).++The common reporting flags can now be used anywhere on the command line.++Fixed deduplication of addons in commands list.++Fixed ugly stack traces in command line parse error messages.++The -V/--value flag is now a global report flag, so it works with+balance, print, register, balancesheet, incomestatement, cashflow,+etc. (Justin Le)++The `--pivot` global reporting option replaces all account names with+the value of some other field or tag. It has been improved, eg:++- we don't add the field/tag name name as a prefix+- when pivoting on a tag, if the tag is missing we show a blank+ (rather than showing mixed tag values and account names)+- a pipe character delimiter may be used in descriptions to get a more accurate+ and useful payee report (`hledger balance --pivot payee`)++options cleanups++## Addons++Easier installation:+move add-ons and example scripts to bin/,+convert to stack scripts,+add a build script to install all deps,+add some functional tests,+test add-ons with Travis CI,+add installation docs to download page.++Improved docs:+all addons now contain their own documentation. Most of them (all but+hledger-budget) use a new reduced-boilerplate declaration format+and can show short (-h) and long (--help) command line help.+(Long help is declared with pre and postambles to the generated+options help, short help is that truncated at the start of the hledger+common flags.)++`hledger` now shows a cleaner list of addon commands, showing only the+compiled version of an addon when both source and compiled versions+are in $PATH. (Addons with .exe extension or no extension are+considered compiled. Modification time is not checked, ie, an old+compiled addon will override a newer source version. If there are+three or more versions of an addon, all are shown. )++New addons added/included:++- autosync - example symlink to ledger-autosync+- budget - experimental budget reporting command supporting Ledger-like periodic transactions and automated transactions (Mykola Orliuk)+- chart - pie-chart-generating prototype, a repackaging of the old hledger-chart tool+- check - more powerful balance assertions (Michael Walker)+- check-dupes - find accounts sharing the same leaf name (Stefano Rodighiero)+- prices - show all market price records (Mykola Orliuk)+- register-match - a helper for ledger-autosync's deduplication, finds best match for a transaction description++The equity command now always generates a valid journal transaction,+handles prices better, and adds balance assertions (Mykola Orliuk).++The rewrite command is more robust and powerful (Mykola Orliuk):++- in addition to command-line rewrite options, it understands rewrite rules+ defined in the journal, similar to Ledger's automated transactions (#99).+ Eg:++ = ^income+ (liabilities:tax) *.33++ = expenses:gifts+ budget:gifts *-1+ assets:budget *1++- it can generate diff output, allowing easier review of the proposed+ changes, and safe modification of original journal files (preserving+ file-level comments and directives). Eg:++ hledger-rewrite --diff Agency --add-posting 'Expenses:Taxes *0.17' | patch++- rewrites can affect multiple postings in a transaction, not just one.++- posting-specific dates are handled better++## balance++A new --pretty-tables option uses unicode characters for rendering+table borders in multicolumn reports (#522) (Moritz Kiefer)++## balancesheet/cashflow/incomestatement++These commands are now more powerful, able to show multicolumn reports+and generally having the same features as the balance command. (Justin Le)++balancesheet has always ignored a begin date specified with a `-b` or+`-p` option; now it also ignores a begin date specified with a `date:`+query. (Related discussion at #531)++## print++The output of print is now always a valid journal (fixes #465) (Mykola Orliuk).++print now tries to preserves the format of implicit/explicit balancing+amounts and prices, by default. To print with all amounts explicit,+use the new `--explicit/-x` flag (fixes #442). (Mykola Orliuk)++Don't lose the commodity of zero amounts/zero balance assertions (fixes #475) (Mykola Orliuk)++## Misc++Fix a regression in the readability of option parsing errors (#478) (Hans-Peter Deifel)++Fix an example in Cli/Main.hs (Steven R. Baker)++Allow megaparsec 5.2 (#503)++# 1.1 2016-12-31++## balance++- with -V, don't ignore market prices in the future (#453, #403)++- with -V and multiple same-date market prices, use the last parsed not the highest price (#403)++## misc++- fix non-existent "oldtime" dependency (#431)++- extra/hledger-equity.hs now generates valid journal format when there are multiple commodities++# 1.0.1 2016-10-27++- allow megaparsec 5.0 or 5.1++- fix benchmark build failure (#423)++# 1.0 2016-10-26++## add++- suggest only one commodity at a time as default amount (#383)++ (since we currently can't input more than one at a time)++## balance++- added --change flag for consistency++- -H/--historical now also affects single-column balance reports with a start date (#392).++ This has the same effect as just omitting the start date, but adds consistency.++- in CSV output, render amounts in one-line format (#336)++## balancesheet++- fix an infinite loop (#393)++## print++- in CSV output, fix and rename the transaction id field++## register++- fix a sorting regression with --date2 (#326)++- --average/-A is now affected by --historical/-H++- added --cumulative flag for consistency++- in CSV output, include the transaction id and rename the total field (#391)++## stats++- fixed an issue with ordering of include files++## misc++- --pivot option added, groups postings by tag instead of account (#323) (Malte Brandy)++- --anon option added, obfuscates account names and descriptions (#265) (Brian Scott)++ (Only affects the hledger tool, for now.)++- try to clarify balance/register's various report modes,++ kinds of "balance" displayed, and related options and language.++- with multiple --change/--cumulative/--historical flags, use the last one instead of complaining++- don't add the "d" suffix when displaying day periods++- stack-ify extra/hledger-rewrite.hs++## misc++- added GHC 8 support, dropped GHC 7.6 and 7.8 support.++ GHC 7.8 support could be restored with small code changes and a maintainer.++- a cabal.project file has been added (Moritz Kiefer)++- use hpack for maintaining cabal files (#371).++ Instead of editing cabal files directly, we now edit the less+ verbose and less redundant package.yaml files and let stack (or+ hpack) update the cabal files. We commit both the .yaml and+ .cabal files.++- clean up some old cabal flags++- tools/simplebench has been spun off as the quickbench package.++- add Appveyor CI builds, provide up-to-date binaries for Windows++- extra: add a bunch of CSV rules examples++## docs++- the website is simpler, clearer, and more mobile-friendly.++ Docs are now collected on a single page and organised by type: getting started, reference, more.++- reference docs have been split into one manual for each executable and file format.++ This helps with maintenance and packaging and also should make it+ easier to see what's available and to read just what you need.++- manuals are now provided in html, plain text, man and info formats++ generated from the same source by a new Shake-based docs build system. (#292)++- versioned manuals are provided on the website, covering recent releases and the latest dev version (#385, #387)++- manuals are built in to the hledger executables, allowing easy offline reading on all platforms.++ PROG -h shows PROG's command-line usage+ PROG --help shows PROG's manual (fixed width)+ PROG --man shows PROG's manual with man (formatted/paged)+ PROG --info shows PROG's manual with info (hypertext)+ hledger help [TOPIC] shows any manual+ hledger man [TOPIC] shows any manual with man+ hledger info [TOPIC] shows any manual with info++- the general and reporting options are now listed in all executable manuals.++ We assume any of them which are unsupported are harmlessly ignored.++- demo.hledger.org is using beancount's example journal.++ This is the somewhat realistic example journal from the beancount+ project, tweaked for hledger.++- minor copyedits (jungle-boogie)++## cli++- parsing multiple input files is now robust.++ When multiple -f options are provided, we now parse each file+ individually rather than just concatenating them, so they can+ have different formats (#320). Note this also means that+ directives (like \`Y\` or \`alias\`) no longer carry over from one+ file to the next.++- -I has been added as the short flag for --ignore-assertions++ (this is different from Ledger's CLI, but useful for hledger-ui).++- parsing an argument-less --debug option is more robust++# 0.27 2015-10-30++Account aliases:++- Regular expression account aliases are now fast enough that you can+ use lots of them without slowing things down. They now take+ O(aliases x accounts) time, instead of O(aliases x transactions);+ also, regular expressions are no longer recompiled unnecessarily.++Documentation:++- Each hledger package now includes one or more man pages, generated+ from markdown by the mighty pandoc. Currently there are six: one+ for each main executable and each input file format. Currently these+ somewhat duplicate the manual on the website; this will be resolved+ somehow. (#282).++- The site is now built with hakyll-std, a generic hakyll script.++- hledger once again has a HCAR entry.++Tools:++- The hledger cabal files are now generated from package.yaml files by+ hpack, in principle, removing a lot of error-prone duplication and+ boilerplate. (In practice, both files are being updated manually+ for the moment, until hpack supports flags and conditional blocks.)++- Time/allocation and heap profiling is working again, and easier:++ - `make quickprof-CMD` generates a profile for CMD, which runs+ against one of the sample journals. (CMD must be one word,+ enclosing in double quotes isn't working here for some reason).++ - `make quickheap-CMD` generates a heap profile for CMD, in+ hledgerprof.ps, and tries to open it in a viewer (currently the+ mac-friendly "open" executable, so you may need to adjust this in+ the makefile). As with quickprof, CMD must be one word and runs+ against one of the sample journals.++ - `make hledgerprof` builds the hledgerprof executable used for+ time/allocation profiling. `make hledgercov` builds the hledgercov+ executable used for coverage reports.++- Travis CI now tests the build on each github push and announces+ status changes by email and on #hledger.++Journal format:++- Dates must now begin with a digit (not /, eg).++- The comment directive longer requires an end comment, and will+ extend to the end of the file(s) without it.++Command-line interface:++- Output (balance reports, register reports, print output etc.)+ containing wide characters, eg chinese/japanese/korean characters,+ should now align correctly, when viewed in apps and fonts that show+ wide characters as double width (#242).++- The argument for --depth or depth: must now be positive.++add:++- Journal entries are now written with all amounts explicit, to avoid+ losing price info (#283).++- Fixed a bug which sometimes (when the same letter pair was repeated)+ caused it not to pick the most similar past transaction for defaults.++balance:++- There is now a -V/--value flag to report current market value (as in Ledger).+ It converts all reported amounts using their "default market price".+ "Market price" is the new name for "historical prices", defined with the P directive.+ The default market price for a commodity is the most recent one found in the journal on or before the report end date.++ Unlike Ledger, hledger's -V uses only the market prices recorded+ with P directives; it does not use the "transaction prices"+ recorded as part of posting amounts (which are used by -B/--cost).+ Also, using both -B and -V at the same time is supported.++- Fixed a bug in amount normalization which caused amount styles+ (commodity symbol placement, decimal point character, etc.) to be+ lost in certain cases (#230, #276).++- The balance command's --format option can now adjust the rendering+ style of multi-commodity amounts, if you begin the format string+ with one of:++ %_ - renders amounts on multiple lines, bottom-aligned (the default)+ %^ - renders amounts on multiple lines, top-aligned+ %, - renders amounts on one line, comma-separated++- The balance report's final total (and the line above it) now adapt+ themselves to a custom --format.++print:++- The --match option prints the journal entry that best matches a+ description (ie whose description field is most similar to the value+ given, and if there are several equally similar, the most recent).+ This was originally an add-on I used to guess account names for+ ledger-autosync. It's nice for quickly looking up a recent+ transaction from a guessed or partial description.++- print now always right-aligns the amounts in an entry, even when+ they are wider than 12 characters. (If there is a price, it's+ considered part of the amount for right-alignment.)++register:++- Amount columns now resize automatically, using more space if it's+ needed and available.++# 0.26 2015-07-12++Account aliases:++- Account aliases are once again non-regular-expression-based, by default. (#252)++ The regex account aliases added in 0.24 trip up people switching between+ hledger and Ledger. (Also they are currently slow).++ This change makes the old non-regex aliases the default; they are+ unsurprising, useful, and pretty close in functionality to Ledger's.++ The new regex aliases are still available; they must be enclosed+ in forward slashes. (Ledger effectively ignores these.)++Journal format:++- We now parse, and also print, journal entries with no postings, as+ proposed on the mail lists. These are not well-formed General+ Journal entries/transactions, but here is my rationale:++ - Ledger and beancount parse them+ - if they are parsed, they should be printed+ - they provide a convenient way to record (and report) non-transaction events+ - they permit more gradual introduction and learning of the concepts.+ So eg a beginner can keep a simple journal before learning about accounts and postings.++- Trailing whitespace after a `comment` directive is now ignored.++Command-line interface:++- The -f/file option may now be used multiple times.+ This is equivalent to concatenating the input files before running hledger.+ The add command adds entries to the first file specified.++Queries:++- real: (no argument) is now a synonym for real:1++- tag: now matches tag names with a regular expression, like most other queries++- empty: is no longer supported, as it overlaps a bit confusingly with+ amt:0. The --empty flag is still available.++- You can now match on pending status (#250)++ A transaction/posting status of ! (pending) was effectively equivalent+ to * (cleared). Now it's a separate state, not matched by --cleared.+ The new Ledger-compatible --pending flag matches it, and so does+ --uncleared.++ The relevant search query terms are now status:*, status:! and+ status: (the old status:1 and status:0 spellings are deprecated).++ Since we interpret --uncleared and status: as "any state except cleared",+ it's not currently possible to match things which are neither cleared+ nor pending.++activity:++- activity no longer excludes 0-amount postings by default.++add:++- Don't show quotes around the journal file path in the "Creating..."+ message, for consistency with the subsequent "Adding..." message.++balancesheet:++- Accounts beginning with "debt" or now also recognised as liabilities.++print:++- We now limit the display precision of inferred prices. (#262)++ When a transaction posts to two commodities without specifying the+ conversion price, we generate a price which makes it balance (cf+ https://hledger.org/hledger.html#prices). The print command showed+ this with full precision (so that manual calculations with the+ displayed numbers would look right), but this sometimes meant we+ showed 255 digits (when there are multiple postings in the+ commodity being priced, and the averaged unit price is an+ irrational number). In this case we now set the price's display+ precision to the sum of the (max) display precisions of the+ commodities involved. An example:++ hledgerdev -f- print+ <<<+ 1/1+ c C 10.00+ c C 11.00+ d D -320.00+ >>>+ 2015/01/01+ c C 10.00 @ D 15.2381+ c C 11.00 @ D 15.2381+ d D -320.00++ >>>=0++ There might still be cases where this will show more price decimal+ places than necessary.++- We now show inferred unit prices with at least 2 decimal places.++ When inferring prices, if the commodities involved have low+ display precisions, we don't do a good job of rendering+ accurate-looking unit prices. Eg if the journal doesn't use any+ decimal places, any inferred unit prices are also displayed with+ no decimal places, which makes them look wrong to the user. Now,+ we always give inferred unit prices a minimum display precision of+ 2, which helps a bit.++register:++- Postings with no amounts could give a runtime error in some obscure case, now fixed.++stats:++- stats now supports -o/--outputfile, like register/balance/print.+- An O(n\^2) performance slowdown has been fixed, it's now much faster on large journals.++ +--------------------------------------++--------+--------++ | || 0.25 | 0.26 |+ +======================================++========+========++ | -f data/100x100x10.journal stats || 0.10 | 0.16 |+ | -f data/1000x1000x10.journal stats || 0.45 | 0.21 |+ | -f data/10000x1000x10.journal stats || 58.92 | 2.16 |+ +--------------------------------------++--------+--------+++Miscellaneous:++- The June 30 day span was not being rendered correctly; fixed. (#272)++- The bench script invoked by "cabal bench" or "stack bench" now runs+ some simple benchmarks.++ You can get more accurate benchmark times by running with --criterion.+ This will usually give much the same numbers and takes much longer.++ Or with --simplebench, it benchmarks whatever commands are+ configured in bench/default.bench. This mode uses the first+ "hledger" executable in $PATH.++- The deprecated shakespeare-text dependency has been removed more thoroughly.++# 0.25.1 2015-04-29++- timelog: support the description field (#247)++# 0.25 2015-04-07++- GHC 7.10 compatibility (#239)++- build with terminfo support on POSIX systems by default++ On non-windows systems, we now build with terminfo support by+ default, useful for detecting terminal width and other things.++ This requires the C curses dev libraries, which makes POSIX+ installation slightly harder; if it causes problems you can+ disable terminfo support with the new `curses` cabal flag, eg:+ cabal install -f-curses ... (or cabal might try this+ automatically, I'm not sure).++- register: use the full terminal width, respect COLUMNS, allow column width adjustment++ On POSIX systems, register now uses the full terminal width by+ default. Specifically, the output width is set from:++ 1. a --width option+ 2. or a COLUMNS environment variable (NB: not the same as a bash shell var)+ 3. or on POSIX (non-windows) systems, the current terminal width+ 4. or the default, 80 characters.++ Also, register's --width option now accepts an optional+ description column width following the overall width (--width+ WIDTH\[,DESCWIDTH\]). This also sets the account column width, since+ the available space (WIDTH-41) is divided up between these two+ columns. Here's a diagram:++ <--------------------------------- width (W) ---------------------------------->+ date (10) description (D) account (W-41-D) amount (12) balance (12)+ DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA++ Examples:++ $ hledger reg # use terminal width on posix+ $ hledger reg -w 100 # width 100, equal description/account widths+ $ hledger reg -w 100,40 # width 100, wider description+ $ hledger reg -w $COLUMNS,100 # terminal width and set description width++- balance: new -T/--row-total and -A/--average options++ In multicolumn balance reports, -T/--row-total now shows a row totals+ column and -A/--average shows a row averages column.+ This helps eg to see monthly average expenses (hledger bal \^expenses -MA).++ NB our use of -T deviates from Ledger's UI, where -T sets a custom+ final total expression.++- balance: -N is now short for --no-total+- balance: fix partially-visible totals row with --no-total++ A periodic (not using --cumulative or --historical) balance report+ with --no-total now hides the totals row properly.++- journal, csv: comment lines can also start with *++ As in Ledger. This means you can embed emacs org/outline-mode nodes in+ your journal file and manipulate it like an outline.++# 0.24.1 2015-03-15++- journal: fix balance accumulation across assertions (#195)++ A sequence of balance assertions asserting first one commodity, then+ another, then the first again, was not working.++- timelog: show hours with two decimal places instead of one (#237)+- in weekly reports, simplify week 52's heading like the others+- disallow trailing garbage in a number of parsers++ Trailing garbage is no longer ignored when parsing the following:+ balance --format option, register --width option, hledger-rewrite+ options, hledger add's inputs, CSV amounts, posting amounts,+ posting dates in tags.++- allow utf8-string-1 (fpco/stackage/#426)++# 0.24 2014-12-25++General:++- fix redundant compilation when cabal installing the hledger packages+- switch to Decimal for representing amounts (#118)+- report interval headings (eg in balance, register reports) are shown+ compactly when possible+- general speedups++Journal format:++- detect decimal point and digit groups more robustly (#196)+- check that transaction dates are followed by whitespace or newline+- check that dates use a consistent separator character+- balance assertions now are specific to a single commodity, like+ Ledger (#195)+- support multi-line comments using "comment", "end comment"+ directives, like Ledger++CSV format:++- reading CSV data from stdin now works better+- the rules file include directive is now relative to the current+ file's directory (#198)+- the original order of same-day transactions is now usually preserved+ (if the records appear to be in reverse date order, we reverse them+ before finally sorting by transaction date)+- CSV output is now built in to the balance, print, and register+ commands, controlled by -O/--output-format (and -o/--output-file,+ see below)++CLI:++- the --width and --debug options now require their argument (#149)+- when an option is repeated, the last value takes precedence (#219).+ This is helpful eg for customising your reporting command aliases on+ the fly.+- smart dates (used in -p/-b/-e/date:/date2:) now must use a+ consistent separator character, and must be parseable to the end+- output destination and format selection is now built in to the+ balance, print and register commands, controlled by -o/--output-file+ and -O/--output-format options. Notes:+ - -o - means stdout+ - an output file name suffix matching a supported format will also+ set the output format, unless overridden by --output-format+ - commands' supported output formats are listed in their+ command-line help. Two formats are currently available:+ txt (the default) and csv.+- balance assertions can be disabled with --ignore-assertions++Account aliases:++- all matching account aliases are now applied, not just one directive+ and one option+- account aliases now match by case insensitive regular expressions+ matching anywhere in the account name+- account aliases can replace multiple occurrences of the pattern+ within an account name+- an account alias replacement pattern can reference matched groups+ with \N++Queries:++- date:/date2: with a malformed date now reports an error instead of+ being ignored+- amt: now supports >= or <=+- clarify status: docs and behaviour; \"*\" is no longer a synonym for+ "1" (fixes #227)++balance:++- fix: in tree mode, --drop is ignored instead of showing empty account names+- a depth limit of 0 now shows summary items with account name "...",+ instead of an empty report (#206)+- in multicolumn balance reports, -E now also shows posting-less+ accounts with a non-zero balance during the period (in addition to+ showing leading & trailing empty columns)+- in multicolumn reports, multi-commodity amounts are rendered on one+ line for better layout (#186)+- multicolumn reports' title now includes the report span++register:++- runs faster with large output+- supports date2:, and date:/date2: combined with --date2, better (fixes+ #201, #221, #222)+- a depth limit of 0 now shows summary items (see balance)+- -A/--average now implies -E/--empty+- postings with multi-commodity amounts are now top-aligned, like+ Ledger++Extra commands:++- hledger-equity: fix end date in title; print closing entry too+- hledger-check-dates: added++# 0.23.3 2014-09-12++- allow text 1.2+ (#207)++# 0.23.2 2014-05-08++- register: also fix date sorting of postings (#184)++# 0.23.1 2014-05-07++- register: fix a refactoring-related regression that the tests+ missed: if transactions were not ordered by date in the journal,+ register could include postings before the report start date in the+ output. (#184)+- add: don't apply a default commodity to amounts on entry (#138)+- cli: options before the add-on command name are now also passed to it (#182)+- csv: allow the first name in a fields list to be empty (#178)+- csv: don't validate fields count in skipped lines (#177)++# 0.23 2014-05-01++Journal format:++- A # (hash) in column 0 is now also supported for starting a top-level journal comment, like Ledger.+- The "too many missing amounts" error now reminds about the 2-space rule.+- Fix: . (period) is no longer parsed as a valid amount.+- Fix: default commodity directives no longer limit the maximum display precision (#169).+- Fix: + before an amount is no longer parsed as part of the commodity (#181).++CLI:++- Command-line help cleanups, layout improvements.+- Descriptions are shown for known add-ons in the command list.+- Command aliases have been simplified.+- Add-ons can now have any of these file extensions:+ none, hs, lhs, pl, py, rb, rkt, sh, bat, com, exe.+- Add-ons are displayed without their file extensions when possible.+- Add-ons with the same name as a built-in command or alias are ignored.+- Fix: add-on detection and invocation now works on windows.+- Fix: add-ons with digits in the name are now found.+- Fix: add-on arguments containing a single quote now work.+- Fix: when -- is used to hide add-on options from the main program,+ it is no longer passed through as an add-on argument.++Queries:++- The currency/commodity query prefix (sym:) has been renamed to cur:.+- Currency/commodity queries are applied more strongly in register and+ balance reports, filtering out unwanted currencies entirely. Eg+ hledger balance cur:'$' now reports only the dollar amounts even if+ there are multi-currency transactions or postings.+- Amount queries like amt:N, amt:<N and amt:>N, where N is not 0, now do an unsigned+ comparison of the amount and N. That is, they compare the absolute magnitude.+ To do a signed comparison instead, write N with its sign (eg amt:+N, amt:<+N, amt:>-N).+- Fix: amount queries no longer give false positives on multi-commodity amounts.++accounts:++- An accounts command has been added, similar to Ledger's, for listing account names+ in flat or hierarchical mode.++add:++- Tab completion now works at all prompts, and will insert the default if the input area is empty.+- Account and amount defaults are more robust and useful.+- Transactions may also be completed by the enter key, when there are no more default postings.+- Input prompts are displayed in a different colour when supported.++balance:++- Balance reports in flat mode now always show exclusive (subaccount-excluding) balances.+- Balance reports in flat mode with --depth now aggregate deeper accounts at the depth limit instead of excluding them.+- Multicolumn reports in flat mode now support --drop.+- Multicolumn balance reports can now show the account hierarchy with --tree.+- Multicolumn report start/end dates are adjusted to encompass the displayed+ report periods, so the first and last periods are "full" and comparable to the others.+- Fix: zero-balance leaf accounts below a non-zero-balance parent are no longer always shown (#170).+- Fix: multicolumn reports now support --date2 (cf #174).++balancesheet, cashflow, incomestatement:++- These commands now support --flat and --drop.++print:++- Tag queries (tag:) will now match a transaction if any of its postings match.++register:++- The --display option has been dropped. To see an accurate running total which+ includes the prior starting balance, use --historical/-H (like balance).+- With a report interval, report start/end dates are adjusted to encompass the displayed+ periods, so the first and last periods are "full" and comparable to the others.+- Fix: --date2 now works with report intervals (fixes #174).++Miscellaneous:++- Default report dates now derive from the secondary dates when --date2 is in effect.+- Default report dates now notice any posting dates outside the transaction dates' span.+- Debug output improvements.+- New add-on example: extra/hledger-rewrite.hs, adds postings to matched entries.+- Compatible with GHC 7.2 (#155) - GHC 7.8, shakespeare 2++# 0.22.2 2014-04-16++- display years before 1000 with four digits, not three+- avoid pretty-show to build with GHC < 7.4+- allow text 1.1, drop data-pprint to build with GHC 7.8.x++# 0.22.1 2014-01-06 and older++See <https://hledger.org/relnotes.html> (or doc/relnotes.md).
Hledger/Cli.hs view
@@ -1,910 +1,887 @@-{-| -Hledger.Cli re-exports the options, utilities and commands provided by the-hledger command-line program.--}--module Hledger.Cli (- module Hledger.Cli.Add,- module Hledger.Cli.Balance,- module Hledger.Cli.Convert,- module Hledger.Cli.Histogram,- module Hledger.Cli.Print,- module Hledger.Cli.Register,- module Hledger.Cli.Stats,- module Hledger.Cli.Options,- module Hledger.Cli.Utils,- module Hledger.Cli.Version,- tests_Hledger_Cli- )-where-import Control.Monad-import qualified Data.Map as Map-import Data.Time.Calendar-import System.Time (ClockTime(TOD))-import Test.HUnit--import Hledger-import Hledger.Cli.Add-import Hledger.Cli.Balance-import Hledger.Cli.Convert-import Hledger.Cli.Histogram-import Hledger.Cli.Print-import Hledger.Cli.Register-import Hledger.Cli.Stats-import Hledger.Cli.Options-import Hledger.Cli.Utils-import Hledger.Cli.Version---- | hledger and hledger-lib's unit tests aggregated from all modules--- plus some more which are easier to define here for now.-tests_Hledger_Cli :: Test-tests_Hledger_Cli = TestList- [- tests_Hledger_Data- ,tests_Hledger_Read- -- ,tests_Hledger_Cli_Add- -- ,tests_Hledger_Cli_Balance- ,tests_Hledger_Cli_Convert- -- ,tests_Hledger_Cli_Histogram- ,tests_Hledger_Cli_Options- -- ,tests_Hledger_Cli_Print- ,tests_Hledger_Cli_Register- -- ,tests_Hledger_Cli_Stats--- ,"account directive" ~:- let sameParse str1 str2 = do j1 <- readJournal Nothing str1 >>= either error' return- j2 <- readJournal Nothing str2 >>= either error' return- j1 `is` j2{filereadtime=filereadtime j1, files=files j1, jContext=jContext j1}- in TestList- [- "account directive 1" ~: sameParse - "2008/12/07 One\n test:from $-1\n test:to $1\n"- "!account test\n2008/12/07 One\n from $-1\n to $1\n"-- ,"account directive 2" ~: sameParse - "2008/12/07 One\n test:foo:from $-1\n test:foo:to $1\n"- "!account test\n!account foo\n2008/12/07 One\n from $-1\n to $1\n"-- ,"account directive 3" ~: sameParse - "2008/12/07 One\n test:from $-1\n test:to $1\n"- "!account test\n!account foo\n!end\n2008/12/07 One\n from $-1\n to $1\n"-- ,"account directive 4" ~: sameParse - ("2008/12/07 One\n alpha $-1\n beta $1\n" ++- "!account outer\n2008/12/07 Two\n aigh $-2\n bee $2\n" ++- "!account inner\n2008/12/07 Three\n gamma $-3\n delta $3\n" ++- "!end\n2008/12/07 Four\n why $-4\n zed $4\n" ++- "!end\n2008/12/07 Five\n foo $-5\n bar $5\n"- )- ("2008/12/07 One\n alpha $-1\n beta $1\n" ++- "2008/12/07 Two\n outer:aigh $-2\n outer:bee $2\n" ++- "2008/12/07 Three\n outer:inner:gamma $-3\n outer:inner:delta $3\n" ++- "2008/12/07 Four\n outer:why $-4\n outer:zed $4\n" ++- "2008/12/07 Five\n foo $-5\n bar $5\n"- )-- ,"account directive should preserve \"virtual\" posting type" ~: do- j <- readJournal Nothing "!account test\n2008/12/07 One\n (from) $-1\n (to) $1\n" >>= either error' return- let p = head $ tpostings $ head $ jtxns j- assertBool "" $ (paccount p) == "test:from"- assertBool "" $ (ptype p) == VirtualPosting-- ]-- ,"account aliases" ~: do- Right j <- readJournal Nothing "!alias expenses = equity:draw:personal\n1/1\n (expenses:food) 1\n"- let p = head $ tpostings $ head $ jtxns j- assertBool "" $ paccount p == "equity:draw:personal:food"-- ,"ledgerAccountNames" ~:- ledgerAccountNames ledger7 `is`- ["assets","assets:cash","assets:checking","assets:saving","equity","equity:opening balances",- "expenses","expenses:food","expenses:food:dining","expenses:phone","expenses:vacation",- "liabilities","liabilities:credit cards","liabilities:credit cards:discover"]-- ,"balance report tests" ~:- let opts `gives` es = do- j <- samplejournal- d <- getCurrentDay- accountsReportAsText opts (accountsReport opts (optsToFilterSpec opts d) j) `is` es- in TestList- [- "balance report with no args" ~:- defreportopts `gives`- [" $-1 assets"- ," $1 bank:saving"- ," $-2 cash"- ," $2 expenses"- ," $1 food"- ," $1 supplies"- ," $-2 income"- ," $-1 gifts"- ," $-1 salary"- ," $1 liabilities:debts"- ,"--------------------"- ," 0"- ]-- ,"balance report can be limited with --depth" ~:- defreportopts{depth_=Just 1} `gives`- [" $-1 assets"- ," $2 expenses"- ," $-2 income"- ," $1 liabilities"- ,"--------------------"- ," 0"- ]- - ,"balance report with account pattern o" ~:- defreportopts{patterns_=["o"]} `gives`- [" $1 expenses:food"- ," $-2 income"- ," $-1 gifts"- ," $-1 salary"- ,"--------------------"- ," $-1"- ]-- ,"balance report with account pattern o and --depth 1" ~:- defreportopts{patterns_=["o"],depth_=Just 1} `gives`- [" $1 expenses"- ," $-2 income"- ,"--------------------"- ," $-1"- ]-- ,"balance report with account pattern a" ~:- defreportopts{patterns_=["a"]} `gives`- [" $-1 assets"- ," $1 bank:saving"- ," $-2 cash"- ," $-1 income:salary"- ," $1 liabilities:debts"- ,"--------------------"- ," $-1"- ]-- ,"balance report with account pattern e" ~:- defreportopts{patterns_=["e"]} `gives`- [" $-1 assets"- ," $1 bank:saving"- ," $-2 cash"- ," $2 expenses"- ," $1 food"- ," $1 supplies"- ," $-2 income"- ," $-1 gifts"- ," $-1 salary"- ," $1 liabilities:debts"- ,"--------------------"- ," 0"- ]-- ,"balance report with unmatched parent of two matched subaccounts" ~: - defreportopts{patterns_=["cash","saving"]} `gives`- [" $-1 assets"- ," $1 bank:saving"- ," $-2 cash"- ,"--------------------"- ," $-1"- ]-- ,"balance report with multi-part account name" ~: - defreportopts{patterns_=["expenses:food"]} `gives`- [" $1 expenses:food"- ,"--------------------"- ," $1"- ]-- ,"balance report with negative account pattern" ~:- defreportopts{patterns_=["not:assets"]} `gives`- [" $2 expenses"- ," $1 food"- ," $1 supplies"- ," $-2 income"- ," $-1 gifts"- ," $-1 salary"- ," $1 liabilities:debts"- ,"--------------------"- ," $1"- ]-- ,"balance report negative account pattern always matches full name" ~: - defreportopts{patterns_=["not:e"]} `gives`- ["--------------------"- ," 0"- ]-- ,"balance report negative patterns affect totals" ~: - defreportopts{patterns_=["expenses","not:food"]} `gives`- [" $1 expenses:supplies"- ,"--------------------"- ," $1"- ]-- ,"balance report with -E shows zero-balance accounts" ~:- defreportopts{patterns_=["assets"],empty_=True} `gives`- [" $-1 assets"- ," $1 bank"- ," 0 checking"- ," $1 saving"- ," $-2 cash"- ,"--------------------"- ," $-1"- ]-- ,"balance report with cost basis" ~: do- j <- (readJournal Nothing $ unlines- [""- ,"2008/1/1 test "- ," a:b 10h @ $50"- ," c:d "- ]) >>= either error' return- let j' = journalCanonicaliseAmounts $ journalConvertAmountsToCost j -- enable cost basis adjustment- accountsReportAsText defreportopts (accountsReport defreportopts nullfilterspec j') `is`- [" $500 a:b"- ," $-500 c:d"- ,"--------------------"- ," 0"- ]-- ]-- ,"journalCanonicaliseAmounts" ~:- "use the greatest precision" ~:- (map precision $ journalAmountAndPriceCommodities $ journalCanonicaliseAmounts $ journalWithAmounts ["1","2.00"]) `is` [2,2]-- ,"commodities" ~:- Map.elems (commodities ledger7) `is` [Commodity {symbol="$", side=L, spaced=False, decimalpoint='.', precision=2, separator=',', separatorpositions=[]}]-- -- don't know what this should do- -- ,"elideAccountName" ~: do- -- (elideAccountName 50 "aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa"- -- `is` "aa:aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa")- -- (elideAccountName 20 "aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa"- -- `is` "aa:aa:aaaaaaaaaaaaaa")-- ,"default year" ~: do- j <- readJournal Nothing defaultyear_journal_str >>= either error' return- tdate (head $ jtxns j) `is` fromGregorian 2009 1 1- return ()-- ,"print report tests" ~: TestList- [-- "print expenses" ~:- do - let opts = defreportopts{patterns_=["expenses"]}- j <- samplejournal- d <- getCurrentDay- showTransactions opts (optsToFilterSpec opts d) j `is` unlines- ["2008/06/03 * eat & shop"- ," expenses:food $1"- ," expenses:supplies $1"- ," assets:cash $-2"- ,""- ]-- , "print report with depth arg" ~:- do - let opts = defreportopts{depth_=Just 2}- j <- samplejournal- d <- getCurrentDay- showTransactions opts (optsToFilterSpec opts d) j `is` unlines- ["2008/01/01 income"- ," income:salary $-1"- ,""- ,"2008/06/01 gift"- ," income:gifts $-1"- ,""- ,"2008/06/03 * eat & shop"- ," expenses:food $1"- ," expenses:supplies $1"- ," assets:cash $-2"- ,""- ,"2008/12/31 * pay off"- ," liabilities:debts $1"- ,""- ]-- ]-- ,"register report tests" ~:- let registerdates = filter (not . null) . map (strip . take 10) . lines- in- TestList- [-- "register report with no args" ~:- do - j <- samplejournal- let opts = defreportopts- (postingsReportAsText opts $ postingsReport opts (optsToFilterSpec opts date1) j) `is` unlines- ["2008/01/01 income assets:bank:checking $1 $1"- ," income:salary $-1 0"- ,"2008/06/01 gift assets:bank:checking $1 $1"- ," income:gifts $-1 0"- ,"2008/06/02 save assets:bank:saving $1 $1"- ," assets:bank:checking $-1 0"- ,"2008/06/03 eat & shop expenses:food $1 $1"- ," expenses:supplies $1 $2"- ," assets:cash $-2 0"- ,"2008/12/31 pay off liabilities:debts $1 $1"- ," assets:bank:checking $-1 0"- ]-- ,"register report with cleared option" ~:- do - let opts = defreportopts{cleared_=True}- j <- readJournal' sample_journal_str- (postingsReportAsText opts $ postingsReport opts (optsToFilterSpec opts date1) j) `is` unlines- ["2008/06/03 eat & shop expenses:food $1 $1"- ," expenses:supplies $1 $2"- ," assets:cash $-2 0"- ,"2008/12/31 pay off liabilities:debts $1 $1"- ," assets:bank:checking $-1 0"- ]-- ,"register report with uncleared option" ~:- do - let opts = defreportopts{uncleared_=True}- j <- readJournal' sample_journal_str- (postingsReportAsText opts $ postingsReport opts (optsToFilterSpec opts date1) j) `is` unlines- ["2008/01/01 income assets:bank:checking $1 $1"- ," income:salary $-1 0"- ,"2008/06/01 gift assets:bank:checking $1 $1"- ," income:gifts $-1 0"- ,"2008/06/02 save assets:bank:saving $1 $1"- ," assets:bank:checking $-1 0"- ]-- ,"register report sorts by date" ~:- do - j <- readJournal' $ unlines- ["2008/02/02 a"- ," b 1"- ," c"- ,""- ,"2008/01/01 d"- ," e 1"- ," f"- ]- let opts = defreportopts- registerdates (postingsReportAsText opts $ postingsReport opts (optsToFilterSpec opts date1) j) `is` ["2008/01/01","2008/02/02"]-- ,"register report with account pattern" ~:- do- j <- samplejournal- let opts = defreportopts{patterns_=["cash"]}- (postingsReportAsText opts $ postingsReport opts (optsToFilterSpec opts date1) j) `is` unlines- ["2008/06/03 eat & shop assets:cash $-2 $-2"- ]-- ,"register report with account pattern, case insensitive" ~:- do - j <- samplejournal- let opts = defreportopts{patterns_=["cAsH"]}- (postingsReportAsText opts $ postingsReport opts (optsToFilterSpec opts date1) j) `is` unlines- ["2008/06/03 eat & shop assets:cash $-2 $-2"- ]-- ,"register report with display expression" ~:- do - j <- samplejournal- let gives displayexpr = - (registerdates (postingsReportAsText opts $ postingsReport opts (optsToFilterSpec opts date1) j) `is`)- where opts = defreportopts{display_=Just displayexpr}- "d<[2008/6/2]" `gives` ["2008/01/01","2008/06/01"]- "d<=[2008/6/2]" `gives` ["2008/01/01","2008/06/01","2008/06/02"]- "d=[2008/6/2]" `gives` ["2008/06/02"]- "d>=[2008/6/2]" `gives` ["2008/06/02","2008/06/03","2008/12/31"]- "d>[2008/6/2]" `gives` ["2008/06/03","2008/12/31"]-- ,"register report with period expression" ~:- do - j <- samplejournal- let periodexpr `gives` dates = do- j' <- samplejournal- registerdates (postingsReportAsText opts $ postingsReport opts (optsToFilterSpec opts date1) j') `is` dates- where opts = defreportopts{period_=maybePeriod date1 periodexpr}- "" `gives` ["2008/01/01","2008/06/01","2008/06/02","2008/06/03","2008/12/31"]- "2008" `gives` ["2008/01/01","2008/06/01","2008/06/02","2008/06/03","2008/12/31"]- "2007" `gives` []- "june" `gives` ["2008/06/01","2008/06/02","2008/06/03"]- "monthly" `gives` ["2008/01/01","2008/06/01","2008/12/01"]- "quarterly" `gives` ["2008/01/01","2008/04/01","2008/10/01"]- let opts = defreportopts{period_=maybePeriod date1 "yearly"}- (postingsReportAsText opts $ postingsReport opts (optsToFilterSpec opts date1) j) `is` unlines- ["2008/01/01 - 2008/12/31 assets:bank:saving $1 $1"- ," assets:cash $-2 $-1"- ," expenses:food $1 0"- ," expenses:supplies $1 $1"- ," income:gifts $-1 0"- ," income:salary $-1 $-1"- ," liabilities:debts $1 0"- ]- let opts = defreportopts{period_=maybePeriod date1 "quarterly"}- registerdates (postingsReportAsText opts $ postingsReport opts (optsToFilterSpec opts date1) j) `is` ["2008/01/01","2008/04/01","2008/10/01"]- let opts = defreportopts{period_=maybePeriod date1 "quarterly",empty_=True}- registerdates (postingsReportAsText opts $ postingsReport opts (optsToFilterSpec opts date1) j) `is` ["2008/01/01","2008/04/01","2008/07/01","2008/10/01"]-- ]-- , "register report with depth arg" ~:- do - j <- samplejournal- let opts = defreportopts{depth_=Just 2}- (postingsReportAsText opts $ postingsReport opts (optsToFilterSpec opts date1) j) `is` unlines- ["2008/01/01 income assets:bank $1 $1"- ," income:salary $-1 0"- ,"2008/06/01 gift assets:bank $1 $1"- ," income:gifts $-1 0"- ,"2008/06/02 save assets:bank $1 $1"- ," assets:bank $-1 0"- ,"2008/06/03 eat & shop expenses:food $1 $1"- ," expenses:supplies $1 $2"- ," assets:cash $-2 0"- ,"2008/12/31 pay off liabilities:debts $1 $1"- ," assets:bank $-1 0"- ]-- ,"show dollars" ~: show (dollars 1) ~?= "$1.00"-- ,"show hours" ~: show (hours 1) ~?= "1.0h"-- ,"unicode in balance layout" ~: do- j <- readJournal'- "2009/01/01 * медвежья шкура\n расходы:покупки 100\n актив:наличные\n"- let opts = defreportopts- accountsReportAsText opts (accountsReport opts (optsToFilterSpec opts date1) j) `is`- [" -100 актив:наличные"- ," 100 расходы:покупки"- ,"--------------------"- ," 0"- ]-- ,"unicode in register layout" ~: do- j <- readJournal'- "2009/01/01 * медвежья шкура\n расходы:покупки 100\n актив:наличные\n"- let opts = defreportopts- (postingsReportAsText opts $ postingsReport opts (optsToFilterSpec opts date1) j) `is` unlines- ["2009/01/01 медвежья шкура расходы:покупки 100 100"- ," актив:наличные -100 0"]-- ,"subAccounts" ~: do- l <- liftM (journalToLedger nullfilterspec) samplejournal- let a = ledgerAccount l "assets"- map aname (ledgerSubAccounts l a) `is` ["assets:bank","assets:cash"]-- ]-- --- fixtures/test data--date1 = parsedate "2008/11/26"--- t1 = LocalTime date1 midday--samplejournal = readJournal' sample_journal_str--sample_journal_str = unlines- ["; A sample journal file."- ,";"- ,"; Sets up this account tree:"- ,"; assets"- ,"; bank"- ,"; checking"- ,"; saving"- ,"; cash"- ,"; expenses"- ,"; food"- ,"; supplies"- ,"; income"- ,"; gifts"- ,"; salary"- ,"; liabilities"- ,"; debts"- ,""- ,"2008/01/01 income"- ," assets:bank:checking $1"- ," income:salary"- ,""- ,"2008/06/01 gift"- ," assets:bank:checking $1"- ," income:gifts"- ,""- ,"2008/06/02 save"- ," assets:bank:saving $1"- ," assets:bank:checking"- ,""- ,"2008/06/03 * eat & shop"- ," expenses:food $1"- ," expenses:supplies $1"- ," assets:cash"- ,""- ,"2008/12/31 * pay off"- ," liabilities:debts $1"- ," assets:bank:checking"- ,""- ,""- ,";final comment"- ]--defaultyear_journal_str = unlines- ["Y2009"- ,""- ,"01/01 A"- ," a $1"- ," b"- ]---- write_sample_journal = writeFile "sample.journal" sample_journal_str---- entry2_str = unlines--- ["2007/01/27 * joes diner"--- ," expenses:food:dining $10.00"--- ," expenses:gifts $10.00"--- ," assets:checking $-20.00"--- ,""--- ]---- entry3_str = unlines--- ["2007/01/01 * opening balance"--- ," assets:cash $4.82"--- ," equity:opening balances"--- ,""--- ,"2007/01/01 * opening balance"--- ," assets:cash $4.82"--- ," equity:opening balances"--- ,""--- ,"2007/01/28 coopportunity"--- ," expenses:food:groceries $47.18"--- ," assets:checking"--- ,""--- ]---- periodic_entry1_str = unlines--- ["~ monthly from 2007/2/2"--- ," assets:saving $200.00"--- ," assets:checking"--- ,""--- ]---- periodic_entry2_str = unlines--- ["~ monthly from 2007/2/2"--- ," assets:saving $200.00 ;auto savings"--- ," assets:checking"--- ,""--- ]---- periodic_entry3_str = unlines--- ["~ monthly from 2007/01/01"--- ," assets:cash $4.82"--- ," equity:opening balances"--- ,""--- ,"~ monthly from 2007/01/01"--- ," assets:cash $4.82"--- ," equity:opening balances"--- ,""--- ]---- journal1_str = unlines--- [""--- ,"2007/01/27 * joes diner"--- ," expenses:food:dining $10.00"--- ," expenses:gifts $10.00"--- ," assets:checking $-20.00"--- ,""--- ,""--- ,"2007/01/28 coopportunity"--- ," expenses:food:groceries $47.18"--- ," assets:checking $-47.18"--- ,""--- ,""--- ]---- journal2_str = unlines--- [";comment"--- ,"2007/01/27 * joes diner"--- ," expenses:food:dining $10.00"--- ," assets:checking $-47.18"--- ,""--- ]---- journal3_str = unlines--- ["2007/01/27 * joes diner"--- ," expenses:food:dining $10.00"--- ,";intra-entry comment"--- ," assets:checking $-47.18"--- ,""--- ]---- journal4_str = unlines--- ["!include \"somefile\""--- ,"2007/01/27 * joes diner"--- ," expenses:food:dining $10.00"--- ," assets:checking $-47.18"--- ,""--- ]---- journal5_str = ""---- journal6_str = unlines--- ["~ monthly from 2007/1/21"--- ," expenses:entertainment $16.23 ;netflix"--- ," assets:checking"--- ,""--- ,"; 2007/01/01 * opening balance"--- ,"; assets:saving $200.04"--- ,"; equity:opening balances "--- ,""--- ]---- journal7_str = unlines--- ["2007/01/01 * opening balance"--- ," assets:cash $4.82"--- ," equity:opening balances "--- ,""--- ,"2007/01/01 * opening balance"--- ," income:interest $-4.82"--- ," equity:opening balances "--- ,""--- ,"2007/01/02 * ayres suites"--- ," expenses:vacation $179.92"--- ," assets:checking "--- ,""--- ,"2007/01/02 * auto transfer to savings"--- ," assets:saving $200.00"--- ," assets:checking "--- ,""--- ,"2007/01/03 * poquito mas"--- ," expenses:food:dining $4.82"--- ," assets:cash "--- ,""--- ,"2007/01/03 * verizon"--- ," expenses:phone $95.11"--- ," assets:checking "--- ,""--- ,"2007/01/03 * discover"--- ," liabilities:credit cards:discover $80.00"--- ," assets:checking "--- ,""--- ,"2007/01/04 * blue cross"--- ," expenses:health:insurance $90.00"--- ," assets:checking "--- ,""--- ,"2007/01/05 * village market liquor"--- ," expenses:food:dining $6.48"--- ," assets:checking "--- ,""--- ]--journal7 = Journal- [] - [] - [- txnTieKnot $ Transaction {- tdate=parsedate "2007/01/01",- teffectivedate=Nothing,- tstatus=False,- tcode="*",- tdescription="opening balance",- tcomment="",- tmetadata=[],- tpostings=[- Posting {- pstatus=False,- paccount="assets:cash",- pamount=(Mixed [dollars 4.82]),- pcomment="",- ptype=RegularPosting,- pmetadata=[],- ptransaction=Nothing- },- Posting {- pstatus=False,- paccount="equity:opening balances",- pamount=(Mixed [dollars (-4.82)]),- pcomment="",- ptype=RegularPosting,- pmetadata=[],- ptransaction=Nothing- }- ],- tpreceding_comment_lines=""- }- ,- txnTieKnot $ Transaction {- tdate=parsedate "2007/02/01",- teffectivedate=Nothing,- tstatus=False,- tcode="*",- tdescription="ayres suites",- tcomment="",- tmetadata=[],- tpostings=[- Posting {- pstatus=False,- paccount="expenses:vacation",- pamount=(Mixed [dollars 179.92]),- pcomment="",- ptype=RegularPosting,- pmetadata=[],- ptransaction=Nothing- },- Posting {- pstatus=False,- paccount="assets:checking",- pamount=(Mixed [dollars (-179.92)]),- pcomment="",- ptype=RegularPosting,- pmetadata=[],- ptransaction=Nothing- }- ],- tpreceding_comment_lines=""- }- ,- txnTieKnot $ Transaction {- tdate=parsedate "2007/01/02",- teffectivedate=Nothing,- tstatus=False,- tcode="*",- tdescription="auto transfer to savings",- tcomment="",- tmetadata=[],- tpostings=[- Posting {- pstatus=False,- paccount="assets:saving",- pamount=(Mixed [dollars 200]),- pcomment="",- ptype=RegularPosting,- pmetadata=[],- ptransaction=Nothing- },- Posting {- pstatus=False,- paccount="assets:checking",- pamount=(Mixed [dollars (-200)]),- pcomment="",- ptype=RegularPosting,- pmetadata=[],- ptransaction=Nothing- }- ],- tpreceding_comment_lines=""- }- ,- txnTieKnot $ Transaction {- tdate=parsedate "2007/01/03",- teffectivedate=Nothing,- tstatus=False,- tcode="*",- tdescription="poquito mas",- tcomment="",- tmetadata=[],- tpostings=[- Posting {- pstatus=False,- paccount="expenses:food:dining",- pamount=(Mixed [dollars 4.82]),- pcomment="",- ptype=RegularPosting,- pmetadata=[],- ptransaction=Nothing- },- Posting {- pstatus=False,- paccount="assets:cash",- pamount=(Mixed [dollars (-4.82)]),- pcomment="",- ptype=RegularPosting,- pmetadata=[],- ptransaction=Nothing- }- ],- tpreceding_comment_lines=""- }- ,- txnTieKnot $ Transaction {- tdate=parsedate "2007/01/03",- teffectivedate=Nothing,- tstatus=False,- tcode="*",- tdescription="verizon",- tcomment="",- tmetadata=[],- tpostings=[- Posting {- pstatus=False,- paccount="expenses:phone",- pamount=(Mixed [dollars 95.11]),- pcomment="",- ptype=RegularPosting,- pmetadata=[],- ptransaction=Nothing- },- Posting {- pstatus=False,- paccount="assets:checking",- pamount=(Mixed [dollars (-95.11)]),- pcomment="",- ptype=RegularPosting,- pmetadata=[],- ptransaction=Nothing- }- ],- tpreceding_comment_lines=""- }- ,- txnTieKnot $ Transaction {- tdate=parsedate "2007/01/03",- teffectivedate=Nothing,- tstatus=False,- tcode="*",- tdescription="discover",- tcomment="",- tmetadata=[],- tpostings=[- Posting {- pstatus=False,- paccount="liabilities:credit cards:discover",- pamount=(Mixed [dollars 80]),- pcomment="",- ptype=RegularPosting,- pmetadata=[],- ptransaction=Nothing- },- Posting {- pstatus=False,- paccount="assets:checking",- pamount=(Mixed [dollars (-80)]),- pcomment="",- ptype=RegularPosting,- pmetadata=[],- ptransaction=Nothing- }- ],- tpreceding_comment_lines=""- }- ]- []- []- ""- nullctx- []- (TOD 0 0)--ledger7 = journalToLedger nullfilterspec journal7---- journal8_str = unlines--- ["2008/1/1 test "--- ," a:b 10h @ $40"--- ," c:d "--- ,""--- ]---- timelogentry1_str = "i 2007/03/11 16:19:00 hledger\n"--- timelogentry1 = TimeLogEntry In (parsedatetime "2007/03/11 16:19:00") "hledger"---- timelogentry2_str = "o 2007/03/11 16:30:00\n"--- timelogentry2 = TimeLogEntry Out (parsedatetime "2007/03/11 16:30:00") ""---- a1 = Mixed [(hours 1){price=Just $ Mixed [Amount (comm "$") 10 Nothing]}]--- a2 = Mixed [(hours 2){price=Just $ Mixed [Amount (comm "EUR") 10 Nothing]}]--- a3 = Mixed $ amounts a1 ++ amounts a2--journalWithAmounts :: [String] -> Journal-journalWithAmounts as =- Journal- []- []- [t | a <- as, let t = nulltransaction{tdescription=a,tpostings=[nullposting{pamount=parse a,ptransaction=Just t}]}]- []- []- ""- nullctx- []- (TOD 0 0)- where parse = fromparse . parseWithCtx nullctx someamount+{-|+This is the root module of the @hledger@ package,+providing hledger's command-line interface.+The main function,+commands,+command-line options,+and utilities useful to other hledger command-line programs+are exported.+It also re-exports hledger-lib:Hledger+and cmdargs:System.Concole.CmdArgs.Explicit++See also:++- hledger-lib:Hledger+- [The README files](https://github.com/search?q=repo%3Asimonmichael%2Fhledger+path%3A**%2FREADME*&type=code&ref=advsearch)+- [The high-level developer docs](https://hledger.org/dev.html)++hledger is a Haskell rewrite of John Wiegley's "ledger". +It generates financial reports from a plain text general journal.+You can use the command line:++> $ hledger++or ghci:++> $ make ghci+> ghci> Right j <- runExceptT $ readJournalFile definputopts "examples/sample.journal" -- or: j <- defaultJournal+> ghci> :t j+> j :: Journal+> ghci> stats defcliopts j+> Main file : examples/sample.journal+> Included files : +> Transactions span : 2008-01-01 to 2009-01-01 (366 days)+> Last transaction : 2008-12-31 (733772 days from now)+> Transactions : 5 (0.0 per day)+> Transactions last 30 days: 0 (0.0 per day)+> Transactions last 7 days : 0 (0.0 per day)+> Payees/descriptions : 5+> Accounts : 8 (depth 3)+> Commodities : 1 ($)+> Market prices : 0 ()+> +> Run time (throughput) : 1695276900.00s (0 txns/s)+> ghci> balance defcliopts j+> $1 assets:bank:saving+> $-2 assets:cash+> $1 expenses:food+> $1 expenses:supplies+> $-1 income:gifts+> $-1 income:salary+> $1 liabilities:debts+> --------------------+> 0 +> ghci> ++etc.+++SPDX-License-Identifier: GPL-3.0-or-later+Copyright (c) 2007-2025 (each year in this range) Simon Michael <simon@joyful.com> and contributors.++This program is free software: you can redistribute it and/or modify+it under the terms of the GNU General Public License as published by+the Free Software Foundation, either version 3 of the License, or+(at your option) any later version.++This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;+without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.+See the GNU General Public License for more details.+You should have received a copy of the GNU General Public License along with this program.+If not, see <https://www.gnu.org/licenses/>.++-}++{-# OPTIONS_GHC -Wno-unrecognised-pragmas #-}+{-# HLINT ignore "Unused LANGUAGE pragma" #-}+{-# LANGUAGE CPP #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE TupleSections #-}++module Hledger.Cli (+ main,+ argsToCliOpts,+ -- * Re-exports+ module Hledger.Cli.CliOptions,+ module Hledger.Cli.Conf,+ module Hledger.Cli.Commands,+ module Hledger.Cli.DocFiles,+ module Hledger.Cli.Utils,+ module Hledger.Cli.Version,+ module Hledger,+ -- ** System.Console.CmdArgs.Explicit+ module CmdArgsWithoutName+)+where++#if MIN_VERSION_base(4,20,0)+import Control.Exception.Backtrace (setBacktraceMechanismState, BacktraceMechanism(..))+#endif+import Control.Monad (when, unless, void)+import Data.Bifunctor (second)+import Data.Char (isDigit)+import Data.Either (isRight)+import Data.Function ((&))+import Data.Functor ((<&>))+import Data.List+import Data.Maybe (isJust, fromMaybe, fromJust)+import Data.Text (pack, unpack, Text)+import Data.Time.Clock.POSIX (getPOSIXTime)+import Safe+import System.Console.CmdArgs.Explicit+import System.Console.CmdArgs.Explicit as CmdArgsWithoutName hiding (Name)+import System.Environment+import System.Exit+import System.Info (os)+import System.Process (rawSystem, system)+import Text.Megaparsec (optional, takeWhile1P, eof)+import Text.Megaparsec.Char (char)+import Text.Printf++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Conf+import Hledger.Cli.Commands+import Hledger.Cli.Commands.Quickref (showQuickref)+import Hledger.Cli.Commands.Run+import Hledger.Cli.DocFiles+import Hledger.Cli.Utils+import Hledger.Cli.Version+import Hledger.Utils.I18n (shortLangTag, writeStartingCatalog)+++verboseDebugLevel = 8++-- A dummy mode just for parsing --conf/--no-conf flags.+confflagsmode = defMode{+ modeGroupFlags=Group [] confflags []+ ,modeArgs = ([], Just $ argsFlag "")+ }++-- A dummy mode just for parsing the help/doc/version/test flags.+helpflagsmode = defMode{+ modeGroupFlags=Group [] helpflags []+ ,modeArgs = ([], Just $ argsFlag "")+ }++------------------------------------------------------------------------------+-- | hledger CLI's main procedure.+--+-- Here we will parse the command line, read any config file,+-- and search for hledger-* addon executables in the user's PATH,+-- then choose the appropriate builtin operation or addon operation to run,+-- then run it in the right way, usually reading input data (eg a journal) first.+--+-- When making a CLI usable and robust with main command, builtin subcommands,+-- various kinds of addon commands, and config files that add general and+-- command-specific options, while balancing circular dependencies, environment,+-- idioms, legacy, and libraries with their own requirements and limitations:+-- things get crazy, and there is a tradeoff against complexity and bug risk.+-- We try to provide the most intuitive, expressive and robust CLI that's feasible+-- while keeping the CLI processing below sufficiently comprehensible, troubleshootable,+-- and tested. It's an ongoing quest.+-- See also: Hledger.Cli.CliOptions, cli.test, addons.test, --debug and --debug=8.+--+-- Probably the biggest source of complexity here is that cmdargs can't parse+-- a command line containing undeclared flags, but this arises often with our+-- addon commands and builtin/custom commands which haven't implemented all options,+-- so we have to work hard to work around this.+-- https://github.com/ndmitchell/cmdargs/issues/36 is the wishlist issue;+-- implementing that would simplify hledger's CLI processing a lot.+--+main :: IO ()+main = handleExit $ withGhcDebug' $ do++#if MIN_VERSION_base(4,20,0)+ -- Control ghc 9.10+'s stack traces.+ -- CostCentreBacktrace - collect cost-centre stack backtraces (only available when built with profiling)+ -- HasCallStackBacktrace - collect HasCallStack backtraces+ -- ExecutionBacktrace - collect backtraces from native execution stack unwinding+ -- IPEBacktrace - collect backtraces from Info Table Provenance Entries+#ifdef DEBUG+ setBacktraceMechanismState HasCallStackBacktrace True+#else+ setBacktraceMechanismState HasCallStackBacktrace False+#endif+#endif++ -- 0. let's go!++ let+ dbgio :: Show a => String -> a -> IO ()+ dbgio = dbgIO verboseDebugLevel++ dbgio "running" prognameandversion+ starttime <- getPOSIXTime+ dbgTimeResetIO -- start the clock for --debug's phase timings+ -- give ghc-debug a chance to take control+ when (ghcDebugMode == GDPauseAtStart) $ ghcDebugPause'+ ---------------------------------------------------------------+ dbgio "\n1. Preliminary command line parsing" ()++ -- Naming notes:+ -- "arg" often has the most general meaning, including things like: -f, --flag, flagvalue, arg, >file, &, etc.+ -- clicmdarg = the first non-flag argument on the command line = the subcommand name+ -- cmdname = the full unabbreviated command name, or ""+ -- confcmdargs = arguments for the subcommand, from config file++ -- Do some argument preprocessing to help cmdargs+ cliargs <- getArgs+ >>= expandArgsAt -- interpolate @ARGFILEs+ <&> replaceNumericFlags -- convert -NUM to --depth=NUM+ -- run's inline-commands marker (argsMarkRunCommands) is inserted later, into finalargs,+ -- so that a -- introduced by a command alias is also handled+ let+ (clicmdarg, cliargswithoutcmd, cliargswithcmdfirst) = moveFlagsAfterCommand cliargs+ cliargswithcmdfirstwithoutclispecific = dropCliSpecificOpts cliargswithcmdfirst+ (cliargsbeforecmd, cliargsaftercmd) = second (drop 1) $ break (==clicmdarg) cliargs+ dbgio "cli args with preprocessing" cliargs+ dbg1IO "cli args with preprocessing and options moved after command" cliargswithcmdfirst+ dbgio "cli command argument found" clicmdarg+ dbgio "cli args before command" cliargsbeforecmd+ dbgio "cli args after command" cliargsaftercmd+ -- dbgio "cli args without command" cliargswithoutcmd++ ---------------------------------------------------------------+ dbgio "\n2. Read the config file if any" ()++ -- Identify any --conf/--no-conf options.+ -- Run cmdargs on just the args that look conf-related.+ let+ cliconfargs = dropUnsupportedOpts confflagsmode cliargswithoutcmd+ cliconfrawopts = cmdargsParse "for conf options" confflagsmode cliconfargs++ -- Read extra general and command-specific args/opts from the config file, if any.+ -- If it can't be read, that's an error, unless the command line doesn't need it.+ (conf, mconffile) <-+ seq cliconfrawopts $ -- order debug output+ if clicmdarg=="setup" -- the setup command checks config files, but never uses one itself+ then return (nullconf,Nothing)+ else getConf cliconfrawopts >>= \case+ Right c -> return c+ Left err -> do+ skip <- canSkipConf clicmdarg cliargswithoutcmd+ if skip+ then dbg1IO "config file has errors, but not needed for help/version/test output" err >> return (nullconf,Nothing)+ else error' $ rstrip err <> "\n(" <> progname <> " " <> packageversion+ <> " could not read this config file. To run without it, add -n.)"+ -- Whether !-prefixed shell command aliases from this config file are allowed to run+ -- (only from a trusted config file: one given with --conf, or a user-level config file).+ shellaliasesallowed <- confFileIsTrusted cliconfrawopts mconffile++ ---------------------------------------------------------------+ dbgio "\n3. Identify a command name if possible; handle version/help flags" ()++ -- Try to identify the subcommand name, from the first non-flag argument on the command line.++ let+ confallgenargs = confLookup "general" conf & replaceNumericFlags+ -- Drop any --conf/--no-conf flags found in the config file:+ -- they can't have their usual effect (which config file to use was decided before+ -- reading it), and leaving them in rawopts could confuse later config file reads.+ confothergenargs = dropConfFlags confallgenargs+ confdroppedgenargs = confallgenargs \\ confothergenargs+ cmdarg = clicmdarg+ nocmdprovided = null cmdarg++ -- The argument may be a command alias (a custom command) defined in the config file.+ -- If so, expand it to the real command name and the extra arguments to prepend.+ -- Command aliases never override exact builtin command names, and later definitions win.+ cmdaliases = reverse $ confAliases conf -- reversed so that lookup finds the last definition+ aliasexpansion = expandCommandAlias (isJust . findBuiltinCommand) cmdaliases cmdarg+ (effectivecmdarg, aliasargs) = case aliasexpansion of+ HledgerCommand c as -> (c, replaceNumericFlags as)+ ShellCommand _ -> (cmdarg, []) -- handled separately below+ isaliascmd = effectivecmdarg /= cmdarg || not (null aliasargs)++ -- Search PATH for addon commands, excluding any that match builtin command names.+ -- With a long PATH this takes several milliseconds, so it is done only when it can matter:+ -- not when there is no command, nor when the command argument is exactly a builtin command's+ -- name or alias (identified and parsed the same way with or without addons), unless that+ -- is run or repl, which run addon commands.+ let addonsneeded = not nocmdprovided && case findBuiltinCommand effectivecmdarg of+ Just (m, _) -> any (`elem` ["run","repl"]) (modeNames m)+ Nothing -> True+ addons <- if addonsneeded then addonCommandNames else return []++ let+ -- The argument may be an abbreviated command name, which we need to expand.++ -- Run cmdargs on conf + cli args to get the full command name.+ -- If no command argument was provided, or if cmdargs fails because+ -- the command line contains a bad flag or wrongly present/missing flag value,+ -- cmdname will be "".+ args = [effectivecmdarg | not $ null effectivecmdarg] <> cliargswithcmdfirstwithoutclispecific+ -- Actually, only scan the first non-flag argument, to avoid flag errors at this stage.+ possiblecmdarg = take 1 $ dropWhile isFlagArg args+ cmdname = stringopt "command" $ cmdargsParse "for command name" (mainmode addons) possiblecmdarg++ badcmdprovided = null cmdname && not nocmdprovided+ isaddoncmd = not (null cmdname) && cmdname `elem` addons++ -- If it's a builtin command, get its mode and action.+ mbuiltincmdaction = findBuiltinCommand cmdname+ effectivemode = maybe (mainmode []) fst mbuiltincmdaction++ -- The required-value flags to pre-check on the final command line.+ -- For an addon command, only hledger's general flags; any other flags are the addon's.+ -- Otherwise, the flags supported by the command's mode.+ finalreqvalflagargs+ | isaddoncmd = generalReqValFlagArgs+ | otherwise = modeReqValFlagArgs effectivemode++ dbgio "cli args with command first and no cli-specific opts" cliargswithcmdfirstwithoutclispecific+ when isaliascmd $+ dbg1IO "expanded command alias" (cmdarg, (effectivecmdarg, aliasargs))+ dbg1IO "command found" cmdname+ dbgio "no command provided" nocmdprovided+ dbgio "bad command provided" badcmdprovided+ dbgio "is addon command" isaddoncmd++ -- If the command is a !-prefixed shell command alias, run it now (if allowed) and exit.+ -- This happens before the badcmdprovided check, since the alias name is not a real command.+ case aliasexpansion of+ ShellCommand shcmd+ | shellaliasesallowed -> do+ -- append any arguments written after the alias name (not hledger's own options)+ let fullcmd = unwords $ shcmd : map quoteForCommandLine cliargsaftercmd+ dbg1IO "running shell command alias" fullcmd+ system fullcmd >>= exitWith+ | otherwise -> error' $+ "the command alias '" <> cmdarg <> "' runs a shell command (! " <> shcmd <> ")"+ <> maybe "" (\f -> ",\ndefined in " <> f) mconffile <> ".\n"+ <> "Shell command aliases are only allowed from your user config file (~/.hledger.conf or XDG),\n"+ <> "or a config file given with --conf; refusing to run it from an automatically-found config file."+ _ -> return ()++ -- If a bad command was provided, show that error now, before the full cmdargsParse attempt.+ when badcmdprovided $ do+ let aliasnote = if effectivecmdarg /= cmdarg then " (expanded from the " <> cmdarg <> " command alias)" else ""+ error' $ "command " <> effectivecmdarg <> aliasnote <> " is not recognised. Run 'hledger help commands' to see a list."++ ---------------------------------------------------------------+ dbgio "\n4. Get applicable options/arguments from config file" ()++ -- Ignore any general opts or cli-specific opts not known to be supported by the command.+ let+ addoncmdssupportinggenopts = ["ui", "web"] -- addons known to support hledger general options+ supportedgenargsfromconf+ | cmdname `elem` addoncmdssupportinggenopts =+ [a | a <- confothergenargs, not $ any (`isPrefixOf` a) addoncmdssupportinggenopts]+ | isaddoncmd = []+ | otherwise = dropUnsupportedOpts effectivemode confothergenargs+ excludedgenargsfromconf = confothergenargs \\ supportedgenargsfromconf+ confcmdargs0+ | null cmdname = []+ | otherwise = confLookup cmdname conf & replaceNumericFlags+ -- For an addon, prepend a "--" so that cmdargs parses the addon's own flags as+ -- positional args rather than rejecting them. This separator is for parsing only;+ -- it is not part of the args passed on to the addon.+ confcmdargs = confcmdargs0 & if isaddoncmd then ("--":) else id++ when (isJust mconffile) $ do+ unless (null confdroppedgenargs) $+ dbg1IO "ignored conf-selecting flags from config file" confdroppedgenargs+ dbg1IO "using general args from config file" confothergenargs+ unless (null excludedgenargsfromconf) $+ dbg1IO "excluded general args from config file, not supported by this command" excludedgenargsfromconf+ dbg1IO "using subcommand args from config file" confcmdargs++ ---------------------------------------------------------------+ dbgio "\n5. Combine config file and command line args" ()++ let+ finalargs =+ [effectivecmdarg | not $ null effectivecmdarg]+ <> supportedgenargsfromconf+ <> confcmdargs+ <> aliasargs+ <> cliargswithoutcmd+ & replaceNumericFlags -- convert any -NUM opts from the config file+ & (if cmdname=="run" then argsMarkRunCommands else id) -- mark run's inline commands so its -- survives cmdargs (also for an aliased run)++ -- finalargs' <- expandArgsAt finalargs -- expand @ARGFILEs in the config file ? don't bother+ dbg1IO "final args" finalargs++ -- Run cmdargs on command name + supported conf general args + conf subcommand args + cli args to get the final options.+ -- A bad flag or flag argument will cause the program to exit with an error here.+ let rawopts = cmdargsParseWith finalreqvalflagargs "final command line" (mainmode addons) finalargs++ ---------------------------------------------------------------+ seq rawopts $ -- order debug output+ dbgio "\n6. Select an action and run it" ()++ -- We check for the help/doc/version flags first, since they are a high priority.+ -- (A perfectionist might think they should be so high priority that adding -h+ -- to an invalid command line would show help. But cmdargs tends to fail first,+ -- preventing this, and trying to detect them without cmdargs, and always do the+ -- right thing with builtin commands and addon commands, gets much too complicated.)+ let+ quickrefFlag = boolopt "quickref" rawopts+ webmanFlag = boolopt "webman" rawopts+ helpFlag = boolopt "help" rawopts+ examplesFlag = boolopt "examples" rawopts+ infoFlag = boolopt "info" rawopts+ manFlag = boolopt "man" rawopts+ versionFlag = boolopt "version" rawopts+ testFlag = maybestringopt "test" rawopts+ writeLangFlag = maybestringopt "write-lang" rawopts+ -- ignoredopts cmd = error' $ cmd ++ " tried to read options but is not supposed to"+ ignoredjournal cmd = error' $ cmd ++ " tried to read the journal but is not supposed to"++ -- validate opts/args more and convert to CliOpts+ opts <- rawOptsToCliOpts rawopts >>= \opts0 -> return opts0{progstarttime_=starttime}+ dbg2IO "processed opts" opts+ dbgio "period from opts" (period_ . _rsReportOpts $ reportspec_ opts)+ dbgio "interval from opts" (interval_ . _rsReportOpts $ reportspec_ opts)+ dbgio "query from opts & args" (_rsQuery $ reportspec_ opts)++ -- Ensure that anything calling getArgs later will see all args, including config file args.+ dbgTimeIO 1 "startup" ()++ -- Some things (--color, --debug, some checks in journalFinalise) are detected by unsafePerformIO,+ -- eg in Hledger.Utils.IO.progArgs, which means they aren't be seen in a config file+ -- (because many things before this point have forced the one-time evaluation of progArgs).+ withArgs (progname:finalargs) $+ if+ -- 6.1. no command and a help/doc flag found - show general help/docs+ | nocmdprovided && quickrefFlag -> showQuickref+ | nocmdprovided && helpFlag -> runPager $ showModeUsage (mainmode []) ++ "\n"+ | nocmdprovided && examplesFlag -> runTldrForPage "hledger"+ | nocmdprovided && infoFlag -> runInfoForTopic "hledger" Nothing+ | nocmdprovided && manFlag -> runManForTopic "hledger" Nothing+ | nocmdprovided && webmanFlag -> void $ openBrowserOn $ webManualUrl "hledger" Nothing++ -- 6.2. --version flag found and none of these other conditions - show version+ | versionFlag && not (isaddoncmd || quickrefFlag || helpFlag || examplesFlag || infoFlag || manFlag || webmanFlag) -> putStrLn prognameandversion++ -- or --test flag found, with no command - run the unit tests+ | Just pat <- testFlag, not isaddoncmd ->+ if nocmdprovided then runUnitTests pat+ else error' $ "--test can't be used with a command (" <> cmdarg <> "); to select tests, use --test=PATTERN"++ -- or --write-lang flag found - write a translation catalog to start translating from+ | Just lang <- writeLangFlag, not isaddoncmd -> writeLang lang++ -- 6.3. no command found, nothing else to do - show the quick reference card+ | nocmdprovided -> do+ dbg1IO "no command, showing quickref" ()+ showQuickref++ -- 6.4. builtin command found+ | Just (cmdmode, cmdaction) <- mbuiltincmdaction -> do+ let mmodecmdname = headMay $ modeNames cmdmode+ dbg1IO "running builtin command mode" $ fromMaybe "" mmodecmdname++ -- run the builtin command according to its type+ if+ -- 6.4.1. help/doc flag - show command help/docs+ | quickrefFlag -> showQuickref+ | helpFlag -> runPager $ showModeUsage cmdmode ++ "\n"+ | examplesFlag -> runTldrForPage $ maybe "hledger" (("hledger-"<>)) mmodecmdname+ | infoFlag -> runInfoForTopic "hledger" mmodecmdname+ | manFlag -> runManForTopic "hledger" mmodecmdname+ | webmanFlag -> void $ openBrowserOn $ webManualUrl "hledger" mmodecmdname++ -- 6.4.2. builtin command which should not require or read the journal - run it+ -- (help/setup; help's own action dispatches its subtopics)+ | cmdname `elem` journalIgnoringCommandNames ->+ cmdaction opts (ignoredjournal cmdname)++ -- 6.4.3. builtin command which can work with a non-existent journal+ | cmdname `elem` journalCreatingCommandNames ->+ withPossibleJournal opts (cmdaction opts)++ -- 6.4.4. "run" and "repl" need findBuiltinCommands passed to it to avoid circular dependency in the code+ | cmdname == "run" -> Hledger.Cli.Commands.Run.run Nothing findBuiltinCommand addons cmdaliases shellaliasesallowed opts+ | cmdname == "repl" ->+ -- the config file (if any) and the opts to re-read it with, so repl can auto-reload aliases;+ -- and the addon-rescan action, so repl can auto-reload the addon command list+ let mconfinfo = (\f -> (f, cliconfrawopts)) <$> mconffile+ in Hledger.Cli.Commands.Run.repl findBuiltinCommand addons cmdaliases shellaliasesallowed mconfinfo (Just addonCommandNames) opts++ -- 6.4.5. "files" reads the journal just to find the files read, tolerating missing or failing ones+ | cmdname == "files" -> withJournal opts{inputopts_=(inputopts_ opts){_scanfiles=True}} $ cmdaction opts++ -- 6.4.6. all other builtin commands - read the journal and if successful run the command with it+ | otherwise -> withJournal opts $ cmdaction opts++ -- 6.5. external addon command found - run it,+ -- passing any cli arguments written after the command name+ -- and any command-specific opts from the config file.+ -- The first "--" argument in each source -- a config file section, a command+ -- alias, or the command line -- is hledger's separator and is consumed here;+ -- any later "--" arguments in that source are the addon's, and are passed on.+ -- Anything written after a source's first "--" is passed on untouched, including+ -- args which would otherwise look like hledger's own cli-specific options.+ -- Arguments written before the command name, and general opts from the config file,+ -- are not passed since we can't be sure they're supported.+ | isaddoncmd -> do+ let+ -- Each argument source carries its own separator: the first "--" in a+ -- source is hledger's and is consumed, and whatever follows it in that+ -- source is passed on untouched. Splitting per source rather than over+ -- the concatenation matters, or a "--" in a config section or alias+ -- would suppress the stripping of hledger's own options off the+ -- command line, leaking eg "--conf FILE" to the addon.+ consumeSeparator as = let (bs, cs) = breakAtFirstSeparator as in dropCliSpecificOpts bs <> cs+ addonargs = concatMap consumeSeparator+ [supportedgenargsfromconf, confcmdargs0, aliasargs, cliargswithoutcmd]+ addonexe = printf "%s-%s" progname cmdname :: String+ shellcmd = unwords $ map quoteForCommandLine $ addonexe : addonargs+ dbgio "addon command selected" cmdname+ dbgio "addon command arguments" addonargs+ dbg1IO "running addon" shellcmd+ -- Pass the arguments as an argv list, so that they reach the addon exactly as+ -- written, without shell quoting getting in the way. Except on Windows, where+ -- we go through the shell, which is what runs .bat and other script addons there.+ (if os == "mingw32" then system shellcmd else rawSystem addonexe addonargs) >>= exitWith++ -- deprecated command found+ -- cmdname == "convert" = error' (modeHelp oldconvertmode)++ -- 6.6. something else (shouldn't happen) - show an error+ | otherwise -> usageError $+ "could not understand the arguments "++show finalargs+ <> if null confothergenargs then "" else "\ngeneral arguments added from config file: "++show confothergenargs+ <> if null confcmdargs then "" else "\ncommand arguments added from config file: "++show confcmdargs++ -- 7. And we're done.+ dbgTimeIO 1 (if null cmdname then "(no command)" else cmdname) ()+ -- Give ghc-debug a final chance to take control.+ when (ghcDebugMode == GDPauseAtEnd) $ ghcDebugPause'++------------------------------------------------------------------------------++-- | Write a catalog for translating hledger into this language, for --write-lang,+-- and say where it is and what to do next.+writeLang :: String -> IO ()+writeLang lang = writeStartingCatalog (pack lang) >>= \case+ Left e -> error' e+ Right (path, tag, builtin) -> putStr $ unlines+ [ (if builtin then "Wrote hledger's built-in " else "Wrote a new, untranslated ")+ ++ unpack tag ++ " catalog to " ++ path ++ "."+ , "Edit it with Poedit or a text editor; hledger --lang " ++ unpack (shortLangTag tag)+ ++ " uses it from now on."+ , "To share your translation, see https://hledger.org/TRANSLATING.html."+ ]++-- | A helper for addons/scripts: this parses hledger CliOpts from these+-- command line arguments and add-on command names, roughly how hledger main does.+-- If option parsing/validating fails, it exits the program with usageError.+-- Unlike main, this does not read extra args from a config file+-- or search for addons; to do those things, mimic the code in main for now.+argsToCliOpts :: [String] -> [String] -> IO CliOpts+argsToCliOpts args addons = do+ let+ (_, _, args0) = moveFlagsAfterCommand args+ args1 = replaceNumericFlags args0+ rawopts = cmdargsParse "for options" (mainmode addons) args1+ rawOptsToCliOpts rawopts++-- | When the config file can't be read, can this command line do without it ?+-- Yes if it asks for help/docs, version info or unit tests,+-- with no command or a command that is recognised without the config file.+-- (Not with a command alias defined in the config file; there the config error+-- is more useful than "command not recognised".)+-- Flags must be written in full here, not abbreviated.+-- Takes the command argument (or "") and the other command line arguments.+canSkipConf :: String -> [String] -> IO Bool+canSkipConf cmdarg args+ | not helpflag = return False+ | null cmdarg = return True+ | otherwise = do+ addons <- addonCommandNames+ return $ either (const False) (not . null . stringopt "command") $+ process (mainmode addons) [cmdarg]+ where+ rawopts = cmdargsParse "for help flags" helpflagsmode $ dropUnsupportedOpts helpflagsmode args+ helpflag = isJust (maybestringopt "test" rawopts) || isJust (maybestringopt "write-lang" rawopts)+ || any (`boolopt` rawopts) ["help","info","man","webman","examples","quickref","version"]++-- | Parse the given command line arguments/options with the given cmdargs mode,+-- after adding values to any valueless --debug flags,+-- with debug logging showing the given description of this parsing pass+-- (useful when cmdargsParse is called more than once).+-- If parsing fails, exit the program with an informative error message.+cmdargsParse :: String -> Mode RawOpts -> [String] -> RawOpts+cmdargsParse = cmdargsParseWith reqValFlagArgs++-- | Like 'cmdargsParse', but pre-check for missing values only on the given required-value+-- flag args, rather than on every one known to hledger. Use this once the command being run+-- is known, so that flags belonging to other commands are left for cmdargs (or an addon).+cmdargsParseWith :: [String] -> String -> Mode RawOpts -> [String] -> RawOpts+cmdargsParseWith reqvalflagargs desc m args0 =+ process m (ensureDebugFlagHasVal (checkReqValFlagArgsHaveValues reqvalflagargs args0))+ & either+ (\e -> error' $ e <> "\n* while parsing the following args, " <> desc <> ":\n* " <> unwords (map quoteIfNeeded args0))+ (dbgMsg verboseDebugLevel ("cmdargs: parsing " <> desc <> ": " <> show args0))+ -- XXX better error message when cmdargs fails (eg spaced/quoted/malformed flag values) ?++-- | Check that each of the given required-value flags appearing in the arg list is followed by a+-- value, not another known flag. If such a flag is at the end of the args, or is followed by+-- something that looks like a known hledger flag, abort with a usage error naming the offending+-- flag. Returns the args unchanged.+--+-- Scanning stops at the first "--", since cmdargs treats everything after it as positional args.+--+-- Joined forms like -fFILE or --file=FILE are single tokens, so they bypass the check.+-- A bare "-" (commonly used to mean stdin), and prefixed forms like "csv:-", are allowed as values.+-- Values that start with "-" but are not known flags (eg "-date" as a register --sort key) are also+-- allowed, so we don't break legitimate dash-prefixed value syntax.+-- Flags whose value-ness varies by command (ambiguousFlagArgs, eg -m/-p) are not checked here,+-- since the command is not yet known; cmdargs validates them per-command.+checkReqValFlagArgsHaveValues :: [String] -> [String] -> [String]+checkReqValFlagArgsHaveValues reqvalflagargs = go+ where+ -- --debug is declared as flagReq but treated as optional-value via ensureDebugFlagHasVal,+ -- so don't validate it here.+ -- Ambiguous flags (required-value in some commands, valueless in others, eg -m/-p) are also+ -- skipped, since we can't know here which command's meaning applies; cmdargs will check them.+ checkable a = a `elem` reqvalflagargs && a /= "--debug" && a `notElem` ambiguousFlagArgs+ knownFlags = noValFlagArgs `union` reqValFlagArgs `union` optValFlagArgs+ looksLikeKnownFlag b =+ b `elem` knownFlags+ || any (`isPrefixOf` b) longReqValFlagArgs_+ || any (`isPrefixOf` b) longOptValFlagArgs_+ go [] = []+ go as@("--":_) = as+ go [a]+ | checkable a = usageError $ a <> " needs a value, none provided"+ | otherwise = [a]+ go (a:b:rest)+ | checkable a, looksLikeKnownFlag b =+ usageError $ a <> " needs a value, but the next argument is another flag: " <> b+ | otherwise = a : go (b:rest)++-- | Split these args at the first "--" argument, dropping it.+-- That one is the separator hiding later args from hledger's own parsing;+-- any others belong to whatever we pass the args on to.+breakAtFirstSeparator :: [String] -> ([String], [String])+breakAtFirstSeparator as = case break (=="--") as of+ (bs, _:cs) -> (bs, cs)+ _ -> (as, [])++-- | Remove any --conf/--no-conf/-n flags, and any --conf value, from these args.+dropConfFlags :: [String] -> [String]+dropConfFlags = go+ where+ go [] = []+ go ("--conf":as) = go $ drop 1 as+ go (a:as)+ | a `elem` ["-n","--no-conf"] || "--conf=" `isPrefixOf` a = go as+ | otherwise = a : go as++-- | cmdargs does not allow options to appear before the subcommand argument.+-- We prefer to hide this restriction from the user, providing a more forgiving CLI.+-- So this helper tries to move any pre-command flags/options, and their values if any, after the command argument.+-- If there is a "--"" argument, only the preceding args are rearranged.+-- To be precise: pre-command options will be moved to the end of the part of the command line preceding the first -- argument.+-- The pre-command options' relative order will be preserved, but since they may be moved after post-command options,+-- the overall order of options may change.+-- XXX moving them right after the command would probably be better.+--+-- For convenience of the caller, this currently returns a triple:+-- (+-- the command, if one was found (or ""),+-- the rearranged args without the command,+-- the command followed by the rearranged args+-- )+--+-- Notes:+--+-- Detecting the command argument is tricky because of the flexibility of traditional flag syntax.+-- Short flags can be joined together, some flags can have a value or no value,+-- flags and values can be separated by =, a space, or nothing, etc.+--+-- In this context, a "flag" is an argument beginning with - or --, followed by one or more non-space characters.+-- We decide if a flag, and possibly its subsequent value argument, are movable+-- by checking these cases in order:+--+-- - it exactly matches a known short or long no-value flag; move it+-- - it exactly matches a short or long requires-value flag; move it and the following argument+-- - it exactly matches a short optional-value flag; assume these don't exist or we don't have any+-- - it exactly matches a long optional-value flag; assume there's no value, move it+-- - it begins with a short requires-value flag; the value is joined to it, move it+-- - it begins with a long requires-value flag followed by =; likewise+-- - it begins with a long optional-value flag followed by =; likewise+--+-- This hackery increases the risk of misleading errors, bugs, and confusion.+-- It should be fairly robust now, being aware of all builtin flags.+-- The main tests are in hledger/test/cli/cli.test, but they are not exhaustive.+--+-- All general and builtin command flags (and their values) will be moved. It's clearer to+-- write command flags after the command, but if not we'll handle it (for greater robustness).+--+-- Long flags should be spelled in full; abbreviated long flags might not get moved.+--+-- Unknown flags (from addons) are assumed to be valueless or have a joined value,+-- and will be moved - but later rejected by cmdargs.+-- Instead these should be written to the right of a "--" argument, which hides them.+--+moveFlagsAfterCommand :: [String] -> (String, [String], [String])+moveFlagsAfterCommand args =+ case moveFlagAndVal (as1, []) of+ ([],as1') -> ("", as, as) where as = as1' <> as2+ (unmoved@(('-':_):_), moved) -> ("", as, as) where as = moved <> unmoved <> as2+ (cmdarg:unmoved, moved) -> (cmdarg, as, cmdarg:as) where as = moved <> unmoved <> as2+ where+ (as1, as2) = break (== "--") args+ -- Move the next argument to the end if it is a movable flag, along with its subsequent value argument if any.+ moveFlagAndVal :: ([String], [String]) -> ([String], [String])+ moveFlagAndVal ((a:b:cs), moved) =+ case isMovableFlagArg a (Just b) of+ 2 -> dbgMsg lvl ("moving 2: "<>a<>" "<>b) $ moveFlagAndVal (cs, moved++[a,b])+ 1 -> dbgMsg lvl ("moving 1: "<>a) $ moveFlagAndVal (b:cs, moved++[a])+ _ -> (a:b:cs, moved)+ moveFlagAndVal ([a], moved) =+ case isMovableFlagArg a Nothing of+ 1 -> dbgMsg lvl ("moving 1: "<>a) ([], moved++[a])+ _ -> ([a], moved)+ moveFlagAndVal ([], moved) = ([], moved)+ lvl = 8++-- Is this a short or long flag argument that should be moved,+-- and is its following argument a value that also should be moved ?+-- Returns:+-- 0 (not a flag; don't move this argument)+-- 1 (a valueless flag, or a long flag with joined argument, or multiple joined valueless short flags; move this argument)+-- 2 (a short or long flag with a value in the next argument; move this and next argument).+isMovableFlagArg :: String -> Maybe String -> Int+isMovableFlagArg a1 ma2+ | a1 `elem` noValFlagArgs = 1 -- short or long no-val flag+ | a1 == "--debug" && isJust ma2 && not (isDebugValue $ fromJust ma2) = 1 --debug without a value+ | a1 `elem` reqValFlagArgs = 2 -- short or long req-val flag (or --debug) with a separate value+ | a1 `elem` optValFlagArgs = 1 -- long (or short ?) opt-val flag, assume no value+ | any (`isPrefixOf` a1) shortReqValFlagArgs = 1 -- short req-val flag with a joined value+ -- or possibly multiple joined valueless short flags, we won't move those correctly+ | any (`isPrefixOf` a1) longReqValFlagArgs_ = 1 -- long req-val flag (or --debug) with a joined value+ | any (`isPrefixOf` a1) longOptValFlagArgs_ = 1 -- long opt-val flag with a joined value+ -- | isLongFlagArg a1 && any (takeWhile (/='=') `isPrefixOf`) longReqValFlagArgs_ ... -- try to move abbreviated long flags ?+ | isFlagArg a1 = 1 -- an addon flag (or mistyped flag) we don't know, assume no value or value is joined+ | otherwise = 0 -- not a flag++-- Is this string a valid --debug value ?+isDebugValue s = isRight $ parsewith isdebugvalp $ pack s+ where isdebugvalp = optional (char '-') >> takeWhile1P Nothing isDigit <* eof :: TextParser m Text++-- Flag arguments are command line arguments beginning with - or --+-- (followed by a short of long flag name, and possibly joined short flags or a joined value).+isFlagArg, isShortFlagArg, isLongFlagArg :: String -> Bool+isFlagArg a = isShortFlagArg a || isLongFlagArg a++isShortFlagArg ('-':c:_) = c /= '-'+isShortFlagArg _ = False++isLongFlagArg ('-':'-':_:_) = True+isLongFlagArg _ = False++-- | Add the leading hyphen(s) to a short or long flag name.+toFlagArg :: Name -> String+toFlagArg f = if length f == 1 then "-"++f else "--"++f++-- | Flatten a possibly multi-named Flag to (name, FlagInfo) pairs.+toFlagInfos :: Flag RawOpts -> [(Name, FlagInfo)]+toFlagInfos f = [(n,i) | let i = flagInfo f, n <- flagNames f]++-- | Is this flag's value optional ?+isOptVal :: FlagInfo -> Bool+isOptVal = \case+ FlagOpt _ -> True+ FlagOptRare _ -> True+ _ -> False++-- | All the general flags defined in hledger's main mode.+generalFlags :: [Flag RawOpts]+generalFlags = concatMap snd groupNamed <> groupHidden <> groupUnnamed+ where Group{..} = modeGroupFlags $ mainmode [] ++-- | All the general flag names.+generalFlagNames :: [Name]+generalFlagNames = concatMap flagNames generalFlags++-- | All hledger's builtin subcommand-specific flags.+commandFlags :: [Flag RawOpts]+commandFlags = concatMap (groupUnnamed.modeGroupFlags) commandModes+ where+ commandModes = concatMap snd groupNamed <> groupUnnamed <> groupHidden+ where Group{..} = modeGroupModes $ mainmode []++-- | The names of general options flags, grouped by whether they expect a value.+-- There may be some overlaps with command flag names.+noValGeneralFlagNames, reqValGeneralFlagNames, optValGeneralFlagNames :: [Name]+noValGeneralFlagNames = [f | (f,i) <- concatMap toFlagInfos generalFlags, i == FlagNone]+reqValGeneralFlagNames = [f | (f,i) <- concatMap toFlagInfos generalFlags, i == FlagReq]+optValGeneralFlagNames = [f | (f,i) <- concatMap toFlagInfos generalFlags, isOptVal i]++-- | The names of builtin subcommand flags, grouped by whether they expect a value.+-- There may be some overlaps with general flag names.+noValCommandFlagNames, reqValCommandFlagNames, optValCommandFlagNames :: [Name]+noValCommandFlagNames = [f | (f,i) <- concatMap toFlagInfos commandFlags, i == FlagNone]+reqValCommandFlagNames = [f | (f,i) <- concatMap toFlagInfos commandFlags, i == FlagReq]+optValCommandFlagNames = [f | (f,i) <- concatMap toFlagInfos commandFlags, isOptVal i]++-- All flag arguments understood by hledger cli and builtin commands, grouped by whether they expect a value.+-- Any command flags which have the same name as a general flag are excluded.+noValFlagArgs = map toFlagArg $ noValGeneralFlagNames `union` (noValCommandFlagNames \\ generalFlagNames)+reqValFlagArgs = map toFlagArg $ reqValGeneralFlagNames `union` (reqValCommandFlagNames \\ generalFlagNames)+optValFlagArgs = map toFlagArg $ optValGeneralFlagNames `union` (optValCommandFlagNames \\ generalFlagNames)++-- The required-value flag args belonging to hledger's general flags.+generalReqValFlagArgs = map toFlagArg reqValGeneralFlagNames++-- The required-value flag args supported by this mode or its immediate subcommands.+modeReqValFlagArgs :: Mode RawOpts -> [String]+modeReqValFlagArgs m = filter (`elem` modeflagargs) reqValFlagArgs+ where modeflagargs = map toFlagArg $ concatMap flagNames $ modeAndSubmodeFlags m++-- Flag args whose value-ness is ambiguous across commands: required-value in some command(s)+-- but valueless (no-value) in others. Their meaning can't be known before the command is+-- identified, so the pre-cmdargs required-value check (checkReqValFlagArgsHaveValues) skips them,+-- deferring to cmdargs' per-command parsing. Eg -m is --match (required value) for print/register+-- but a valueless "use man" flag for help; -p is --period (required value) generally but a valueless+-- "use pager" flag for help. Derived from the reflected flag sets, so it stays correct as flags change.+-- Computed from the raw per-source name lists (before general/command deduplication), so a name that+-- is valueless only as a command flag shadowed by a same-named general flag (eg help's -p) is still seen.+ambiguousFlagArgs = map toFlagArg $+ (reqValGeneralFlagNames `union` reqValCommandFlagNames) `intersect`+ (noValGeneralFlagNames `union` noValCommandFlagNames)++-- Short flag args that expect a required value.+shortReqValFlagArgs = filter isShortFlagArg reqValFlagArgs++-- Long flag args that expect a required value, with = appended.+longReqValFlagArgs_ = map (++"=") $ filter isLongFlagArg reqValFlagArgs++-- Long flag args that expect an optional value, with = appended.+longOptValFlagArgs_ = map (++"=") $ filter isLongFlagArg optValFlagArgs ++ ["--debug"]++-- Drop any arguments which look like cli-specific options (--no-conf, --conf CONFFILE, etc.)+-- Keep synced with mainmode's groupUnnamed.+dropCliSpecificOpts :: [String] -> [String]+dropCliSpecificOpts = \case+ "--conf":_:as -> dropCliSpecificOpts as+ a:as | "--conf=" `isPrefixOf` a -> dropCliSpecificOpts as+ "--no-conf":as -> dropCliSpecificOpts as+ "-n":as -> dropCliSpecificOpts as+ a:as -> a:dropCliSpecificOpts as+ [] -> []++-- | Given a hledger cmdargs mode and a list of command line arguments, try to drop any of the+-- arguments which seem to be flags not supported by this mode. Also drop their values if any.+--+-- >>> dropUnsupportedOpts confflagsmode ["--debug","1","-f","file"]+-- []+-- >>> dropUnsupportedOpts confflagsmode ["--debug","-f","file"]+-- []+dropUnsupportedOpts :: Mode RawOpts -> [String] -> [String]+dropUnsupportedOpts m = \case+ [] -> []+ "--debug":a:as | not (m `supportsFlag` "debug") ->+ go $ if isDebugValue a then as else a:as+ a:as -> if+ | isLongFlagArg a,+ let f = takeWhile (/='=') a,+ let as' = if isReqValFlagArg f && '=' `notElem` a then drop 1 as else as+ -> if m `supportsFlag` f then a : go as else go as'+ | isShortFlagArg a,+ let f = take 2 a,+ let as' = if isReqValFlagArg f && length a == 2 then drop 1 as else as+ -> if m `supportsFlag` f then a : go as else go as'+ | otherwise -> a : dropUnsupportedOpts m as+ where+ go = dropUnsupportedOpts m+ isReqValFlagArg = (`elem` reqValFlagArgs)+ supportsFlag m1 flagarg = elem flagarg $ map toFlagArg $ concatMap flagNames $ modeAndSubmodeFlags m1++-- | Get all the flags defined in a mode or its immediate subcommands,+-- whether in named, unnamed or hidden groups.+-- Does not recurse into subsubcommands,+-- and does not deduplicate (general flags are repeated on all hledger subcommands).+modeAndSubmodeFlags :: Mode a -> [Flag a]+modeAndSubmodeFlags m@Mode{modeGroupModes=Group{..}} =+ modeFlags m <> concatMap modeFlags (concatMap snd groupNamed <> groupUnnamed <> groupHidden)++-- unit tests (tests_Hledger_Cli) are defined in Hledger.Cli.Commands
− Hledger/Cli/Add.hs
@@ -1,292 +0,0 @@-{-| --A history-aware add command to help with data entry.--Note: this might not be sensible, but add has some aspirations of being-both user-friendly and pipeable/scriptable and for this reason-informational messages are mostly written to stderr rather than stdout.---}--module Hledger.Cli.Add-where-import Control.Exception (throw)-import Control.Monad-import Control.Monad.Trans (liftIO)-import Data.Char (toUpper)-import Data.List-import Data.Maybe-import Data.Time.Calendar-import Safe (headMay)-import System.Console.Haskeline (InputT, runInputT, defaultSettings, setComplete, getInputLine)-import System.Console.Haskeline.Completion-import System.IO ( stderr, hPutStrLn, hPutStr )-import System.IO.Error-import Text.ParserCombinators.Parsec-import Text.Printf-import qualified Data.Foldable as Foldable (find)-import qualified Data.Set as Set--import Hledger-import Prelude hiding (putStr, putStrLn, appendFile)-import Hledger.Utils.UTF8 (putStr, putStrLn, appendFile)-import Hledger.Cli.Options-import Hledger.Cli.Register (postingsReportAsText)-import Hledger.Cli.Utils---{- | Information used as the basis for suggested account names, amounts,- etc in add prompt--}-data PostingState = PostingState {- psJournal :: Journal,- psAccept :: AccountName -> Bool,- psSuggestHistoricalAmount :: Bool,- psHistory :: Maybe [Posting]}---- | Read transactions from the terminal, prompting for each field,--- and append them to the journal file. If the journal came from stdin, this--- command has no effect.-add :: CliOpts -> Journal -> IO ()-add opts j- | f == "-" = return ()- | otherwise = do- hPrintf stderr "Adding transactions to journal file \"%s\".\n" f- hPutStrLn stderr $- "To complete a transaction, enter . (period) at an account prompt.\n"- ++"To stop adding transactions, enter . at a date prompt, or control-d/control-c."- today <- getCurrentDay- getAndAddTransactions j opts today- `catch` (\e -> unless (isEOFError e) $ ioError e)- where f = journalFilePath j---- | Read a number of transactions from the command line, prompting,--- validating, displaying and appending them to the journal file, until--- end of input (then raise an EOF exception). Any command-line arguments--- are used as the first transaction's description.-getAndAddTransactions :: Journal -> CliOpts -> Day -> IO ()-getAndAddTransactions j opts defaultDate = do- (t, d) <- getTransaction j opts defaultDate- j <- journalAddTransaction j opts t- getAndAddTransactions j opts d---- | Read a transaction from the command line, with history-aware prompting.-getTransaction :: Journal -> CliOpts -> Day- -> IO (Transaction,Day)-getTransaction j opts defaultDate = do- today <- getCurrentDay- datestr <- runInteractionDefault $ askFor "date, or . to end"- (Just $ showDate defaultDate)- (Just $ \s -> null s- || s == "."- || isRight (parse (smartdate >> many spacenonewline >> eof) "" $ lowercase s))- when (datestr == ".") $ ioError $ mkIOError eofErrorType "" Nothing Nothing- description <- runInteractionDefault $ askFor "description" (Just "") Nothing- let historymatches = transactionsSimilarTo j (patterns_ $ reportopts_ opts) description- bestmatch | null historymatches = Nothing- | otherwise = Just $ snd $ head historymatches- bestmatchpostings = maybe Nothing (Just . tpostings) bestmatch- date = fixSmartDate today $ fromparse $ (parse smartdate "" . lowercase) datestr- accept x = x == "." || (not . null) x &&- if no_new_accounts_ opts- then isJust $ Foldable.find (== x) ant- else True- where (ant,_,_,_) = groupPostings $ journalPostings j- getpostingsandvalidate = do- ps <- getPostings (PostingState j accept True bestmatchpostings) []- let t = nulltransaction{tdate=date- ,tstatus=False- ,tdescription=description- ,tpostings=ps- }- retry msg = do- liftIO $ hPutStrLn stderr $ "\n" ++ msg ++ "please re-enter."- getpostingsandvalidate- either retry (return . flip (,) date) $ balanceTransaction Nothing t -- imprecise balancing- unless (null historymatches) - (liftIO $ do- hPutStrLn stderr "Similar transactions found, using the first for defaults:\n"- hPutStr stderr $ concatMap (\(n,t) -> printf "[%3d%%] %s" (round $ n*100 :: Int) (show t)) $ take 3 historymatches)- getpostingsandvalidate---- fragile--- | Read postings from the command line until . is entered, using any--- provided historical postings and the journal context to guess defaults.-getPostings :: PostingState -> [Posting] -> IO [Posting]-getPostings st enteredps = do- let bestmatch | isNothing historicalps = Nothing- | n <= length ps = Just $ ps !! (n-1)- | otherwise = Nothing- where Just ps = historicalps- defaultaccount = maybe Nothing (Just . showacctname) bestmatch- ordot | null enteredps || length enteredrealps == 1 = ""- | otherwise = ", or . to record"- account <- runInteraction j $ askFor (printf "account %d%s" n ordot) defaultaccount (Just accept)- if account=="."- then- if null enteredps- then do hPutStrLn stderr $ "\nPlease enter some postings first."- getPostings st enteredps- else return enteredps- else do- let defaultacctused = Just account == defaultaccount- historicalps' = if defaultacctused then historicalps else Nothing- bestmatch' | isNothing historicalps' = Nothing- | n <= length ps = Just $ ps !! (n-1)- | otherwise = Nothing- where Just ps = historicalps'- defaultamountstr | isJust bestmatch' && suggesthistorical = Just historicalamountstr- | n > 1 = Just balancingamountstr- | otherwise = Nothing- where- historicalamountstr = showMixedAmountWithPrecision p $ pamount $ fromJust bestmatch'- balancingamountstr = showMixedAmountWithPrecision p $ negate $ sum $ map pamount enteredrealps- -- what should this be ?- -- 1 maxprecision (show all decimal places or none) ?- -- 2 maxprecisionwithpoint (show all decimal places or .0 - avoids some but not all confusion with thousands separators) ?- -- 3 canonical precision for this commodity in the journal ?- -- 4 maximum precision entered so far in this transaction ?- -- 5 3 or 4, whichever would show the most decimal places ?- -- I think 1 or 4, whichever would show the most decimal places- p = maxprecisionwithpoint- amountstr <- runInteractionDefault $ askFor (printf "amount %d" n) defaultamountstr validateamount- let amount = fromparse $ runParser (someamount <|> return missingamt) ctx "" amountstr- amount' = fromparse $ runParser (someamount <|> return missingamt) nullctx "" amountstr- defaultamtused = Just (showMixedAmount amount) == defaultamountstr- commodityadded | c == cwithnodef = Nothing- | otherwise = c- where c = maybemixedamountcommodity amount- cwithnodef = maybemixedamountcommodity amount'- maybemixedamountcommodity = maybe Nothing (Just . commodity) . headMay . amounts- p = nullposting{paccount=stripbrackets account,- pamount=amount,- ptype=postingtype account}- st' = if defaultamtused then st- else st{psHistory = historicalps',- psSuggestHistoricalAmount = False}- when (isJust commodityadded) $- liftIO $ hPutStrLn stderr $ printf "using default commodity (%s)" (symbol $ fromJust commodityadded)- getPostings st' (enteredps ++ [p])- where- j = psJournal st- historicalps = psHistory st- ctx = jContext j- accept = psAccept st- suggesthistorical = psSuggestHistoricalAmount st- n = length enteredps + 1- enteredrealps = filter isReal enteredps- showacctname p = showAccountName Nothing (ptype p) $ paccount p- postingtype ('[':_) = BalancedVirtualPosting- postingtype ('(':_) = VirtualPosting- postingtype _ = RegularPosting- stripbrackets = dropWhile (`elem` "([") . reverse . dropWhile (`elem` "])") . reverse- validateamount = Just $ \s -> (null s && not (null enteredrealps))- || isRight (runParser (someamount>>many spacenonewline>>eof) ctx "" s)---- | Prompt for and read a string value, optionally with a default value--- and a validator. A validator causes the prompt to repeat until the--- input is valid. May also raise an EOF exception if control-d is pressed.-askFor :: String -> Maybe String -> Maybe (String -> Bool) -> InputT IO String-askFor prompt def validator = do- l <- fmap (maybe eofErr id)- $ getInputLine $ prompt ++ maybe "" showdef def ++ ": "- let input = if null l then fromMaybe l def else l- case validator of- Just valid -> if valid input- then return input- else askFor prompt def validator- Nothing -> return input- where- showdef s = " [" ++ s ++ "]"- eofErr = throw $ mkIOError eofErrorType "end of input" Nothing Nothing---- | Append this transaction to the journal's file, and to the journal's--- transaction list.-journalAddTransaction :: Journal -> CliOpts -> Transaction -> IO Journal-journalAddTransaction j@Journal{jtxns=ts} opts t = do- let f = journalFilePath j- appendToJournalFileOrStdout f $ showTransaction t- when (debug_ opts) $ do- putStrLn $ printf "\nAdded transaction to %s:" f- putStrLn =<< registerFromString (show t)- return j{jtxns=ts++[t]}---- | Append a string, typically one or more transactions, to a journal--- file, or if the file is "-", dump it to stdout. Tries to avoid--- excess whitespace.-appendToJournalFileOrStdout :: FilePath -> String -> IO ()-appendToJournalFileOrStdout f s- | f == "-" = putStr s'- | otherwise = appendFile f s'- where s' = "\n" ++ ensureOneNewlineTerminated s---- | Replace a string's 0 or more terminating newlines with exactly one.-ensureOneNewlineTerminated :: String -> String-ensureOneNewlineTerminated = (++"\n") . reverse . dropWhile (=='\n') . reverse---- | Convert a string of journal data into a register report.-registerFromString :: String -> IO String-registerFromString s = do- d <- getCurrentDay- j <- readJournal' s- return $ postingsReportAsText opts $ postingsReport opts (optsToFilterSpec opts d) j- where opts = defreportopts{empty_=True}---- | Return a similarity measure, from 0 to 1, for two strings.--- This is Simon White's letter pairs algorithm from--- http://www.catalysoft.com/articles/StrikeAMatch.html--- with a modification for short strings.-compareStrings :: String -> String -> Double-compareStrings "" "" = 1-compareStrings (_:[]) "" = 0-compareStrings "" (_:[]) = 0-compareStrings (a:[]) (b:[]) = if toUpper a == toUpper b then 1 else 0-compareStrings s1 s2 = 2.0 * fromIntegral i / fromIntegral u- where- i = length $ intersect pairs1 pairs2- u = length pairs1 + length pairs2- pairs1 = wordLetterPairs $ uppercase s1- pairs2 = wordLetterPairs $ uppercase s2-wordLetterPairs = concatMap letterPairs . words-letterPairs (a:b:rest) = [a,b] : letterPairs (b:rest)-letterPairs _ = []--compareDescriptions :: [Char] -> [Char] -> Double-compareDescriptions s t = compareStrings s' t'- where s' = simplify s- t' = simplify t- simplify = filter (not . (`elem` "0123456789"))--transactionsSimilarTo :: Journal -> [String] -> String -> [(Double,Transaction)]-transactionsSimilarTo j apats s =- sortBy compareRelevanceAndRecency- $ filter ((> threshold).fst)- [(compareDescriptions s $ tdescription t, t) | t <- ts]- where- compareRelevanceAndRecency (n1,t1) (n2,t2) = compare (n2,tdate t2) (n1,tdate t1)- ts = jtxns $ filterJournalTransactionsByAccount apats j- threshold = 0--runInteraction :: Journal -> InputT IO a -> IO a-runInteraction j m = do- let cc = completionCache j- runInputT (setComplete (accountCompletion cc) defaultSettings) m--runInteractionDefault :: InputT IO a -> IO a-runInteractionDefault m = do- runInputT (setComplete noCompletion defaultSettings) m---- A precomputed list of all accounts previously entered into the journal.-type CompletionCache = [AccountName]--completionCache :: Journal -> CompletionCache-completionCache j = -- Only keep unique account names.- Set.toList $ Set.fromList- [paccount p | t <- jtxns j, p <- tpostings t]--accountCompletion :: CompletionCache -> CompletionFunc IO-accountCompletion cc = completeWord Nothing- "" -- don't break words on whitespace, since account names- -- can contain spaces.- $ \s -> return $ map simpleCompletion- $ filter (s `isPrefixOf`) cc
+ Hledger/Cli/Anchor.hs view
@@ -0,0 +1,265 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-|+Links from report cells to hledger-web's register: for hledger-web's own+report pages, and for HTML and FODS output with --base-url. A figure+links to the register that derives it, an account name to the account's+register, a period heading to the register for that period.+-}+module Hledger.Cli.Anchor (+ LinkOpts(..),+ defaultLinkOpts,+ linkParams,+ valueParam,+ composeAnchor,+ composeAnchorWith,+ accountParams,+ dateTerm,+ removeDates,+ removeInacct,+ withLink,+ setAccountAnchor,+ setAccountAnchorWith,+ dateCell,+ dateSpanCell,+ dateSpanCellWith,+ totalDateSpanCell,+ headerDateSpanCell,+ renderPeriodHeading,+ amountPhrase,+ ) where++import Data.Text qualified as Text+import Data.Text (Text)+import Data.Time (Day)+import Data.Maybe (fromMaybe)++import Text.URI qualified as Uri+import Text.URI.QQ qualified as UriQQ++import Hledger.Write.Spreadsheet qualified as Spr+import Hledger.Write.Spreadsheet (headerCell)+import Hledger.Utils.IO (error')+import Hledger.Utils.Text (quoteForQuery)+import Hledger.Data.Dates (showDateSpan, showDateSpanFull, showDateSpanForQuery, showDate, nulldatespan)+import Hledger.Data.Types (DateSpan(..))+import Hledger.Data.Valuation (ConversionOp(..), ValuationType(..))+import Hledger.Reports.ReportOptions (PeriodTitles(..), BalanceAccumulation(..))+++-- | What a report's register links need to know about the report,+-- besides its query and the base url.+data LinkOpts = LinkOpts {+ loAccum :: BalanceAccumulation,+ -- ^ With historical balances, the register starts from the balance+ -- before the period, so that it ends on the figure in the cell.+ loSpan :: DateSpan,+ -- ^ The whole report span. A cumulative figure's register runs from its start.+ loDate2 :: Bool,+ -- ^ Does the report use secondary dates ? Then so must the register.+ loIncludesSubs :: Bool,+ -- ^ Does the row's figure include subaccounts, or not (subs=0) ?+ loNegated :: Bool,+ -- ^ Are the figures shown with the opposite sign to the register's ?+ loValue :: Maybe Text+ -- ^ The register's value parameter, for figures converted to cost+ -- or to market value (see 'valueParam').+}++defaultLinkOpts :: LinkOpts+defaultLinkOpts = LinkOpts PerPeriod nulldatespan False True False Nothing++-- | The query parameters a link carries besides q: the register's+-- accumulation mode, when it is not the register's default, and how it+-- converts amounts, when the report converts them.+linkParams :: LinkOpts -> [(Text, Text)]+linkParams lo =+ [("accum", "historical") | loAccum lo == Historical] +++ [("value", v) | Just v <- [loValue lo]]++-- | The value parameter that asks hledger-web's register to convert+-- amounts as a report does, mirroring --value's WHEN[,COMM] syntax:+-- "cost" for -B, "end" for -V, "end,COMM" for -X COMM, "then", "now",+-- or a date for the other valuations. A register converting them the+-- same way ends on the figure a link was clicked on. Cost combined+-- with a valuation has none, and such links open the register as it is.+valueParam :: Maybe ConversionOp -> Maybe ValuationType -> Maybe Text+valueParam conv val =+ case (conv == Just ToCost, val) of+ (True, Nothing) -> Just "cost"+ (True, Just _) -> Nothing+ (False, Nothing) -> Nothing+ (False, Just vt) -> Just $ case vt of+ AtEnd mc -> "end" <> comm mc+ AtThen mc -> "then" <> comm mc+ AtNow mc -> "now" <> comm mc+ AtDate d mc -> showDate d <> comm mc+ where comm = maybe "" ("," <>)++-- | The span a figure's register covers: the period, or, for a+-- cumulative figure, the report's start to the period's end.+linkSpan :: LinkOpts -> DateSpan -> DateSpan+linkSpan lo spn@(DateSpan _ e) =+ case loAccum lo of+ Cumulative -> let DateSpan s _ = loSpan lo in DateSpan s e+ _ -> spn++-- | The query parameters naming the account a link's register is for:+-- with its subaccounts, or with subs=0, without them. A depth 0+-- report's "..." row, all accounts in one, names none: its register+-- is the register of everything.+accountParams :: Bool -> Text -> [(Text, Text)]+accountParams _ "..." = []+accountParams includesSubs acct = ("account", acct) : [("subs", "0") | not includesSubs]++-- | A date: term for the span (date2: for a report using secondary+-- dates), or none for the unbounded span.+dateTerm :: Bool -> DateSpan -> [Text]+dateTerm date2 spn =+ [(if date2 then "date2:" else "date:") <> t | let t = showDateSpanForQuery spn, not $ Text.null t]++registerQueryUrl :: [(Text, Text)] -> [Text] -> Text+registerQueryUrl params query =+ Uri.render $+ [UriQQ.uri|register|] {+ Uri.uriQuery =+ [Uri.QueryParam [UriQQ.queryKey|q|] (queryValue q) | not $ Text.null q]+ ++ [Uri.QueryParam (queryKey k) (queryValue v) | (k, v) <- params]+ }+ where+ q = Text.unwords $ map quoteForQuery $ filter (not . Text.null) query+ queryKey = fromMaybe (error' "register URI query construction failed") . Uri.mkQueryKey+ queryValue = fromMaybe (error' "register URI query construction failed") . Uri.mkQueryValue++{- |+>>> composeAnchor Nothing ["date:2024"]+""+>>> composeAnchor (Just "") ["date:2024"]+"register?q=date:2024"+>>> composeAnchor (Just "/") ["date:2024"]+"/register?q=date:2024"+>>> composeAnchor (Just "foo") ["date:2024"]+"foo/register?q=date:2024"+>>> composeAnchor (Just "foo/") ["date:2024"]+"foo/register?q=date:2024"+-}+composeAnchor :: Maybe Text -> [Text] -> Text+composeAnchor = composeAnchorWith []++{- | Like 'composeAnchor', with query parameters after q.++>>> composeAnchorWith [("accum","historical")] (Just "") ["date:2024"]+"register?q=date:2024&accum=historical"+-}+composeAnchorWith :: [(Text, Text)] -> Maybe Text -> [Text] -> Text+composeAnchorWith _ Nothing _ = mempty+composeAnchorWith params (Just baseUrl) query =+ baseUrl <>+ (if all (('/'==) . snd) $ Text.unsnoc baseUrl then "" else "/") <>+ registerQueryUrl params query++-- cf. Web.Widget.Common+removeDates :: [Text] -> [Text]+removeDates =+ filter (\term_ ->+ not $ Text.isPrefixOf "date:" term_ || Text.isPrefixOf "date2:" term_)++-- | Drop the terms naming an account for the register. A link names+-- the account it is for, and the register reads only the first such term.+removeInacct :: [Text] -> [Text]+removeInacct =+ filter (\term_ ->+ not $ Text.isPrefixOf "inacct:" term_ || Text.isPrefixOf "inacctonly:" term_)++-- | Give a cell a link and its title, unless the link is empty (no base url).+withLink :: Text -> Text -> Spr.Cell border text -> Spr.Cell border text+withLink anchor title cell+ | Text.null anchor = cell+ | otherwise = cell {Spr.cellAnchor = anchor, Spr.cellTitle = title}++-- | The title of a link from a figure to the register that derives it,+-- with a note when the report shows figures with the opposite sign.+amountPhrase :: LinkOpts -> Bool -> Text+amountPhrase lo isTotal =+ (case (loAccum lo, isTotal) of+ (Historical, False) -> "Show the transactions behind this balance"+ (Historical, True) -> "Show the transactions behind this total"+ (_, False) -> "Show the transactions that make up this amount"+ (_, True) -> "Show the transactions that make up this total")+ <> (if loNegated lo then ", which the register shows with the opposite sign" else "")++-- | A column heading for the period, linking to the register for it.+-- The link's date term is the span as a period expression, which can+-- differ from the heading text: a query reads the end date of+-- 2025-01-15..2025-02-14 as exclusive, and reads no week names.+headerDateSpanCell ::+ Bool -> PeriodTitles -> Maybe Text -> [Text] -> DateSpan -> Spr.Cell () Text+headerDateSpanCell date2 ph base query spn =+ withLink+ (composeAnchor base $ dateTerm date2 spn ++ removeDates (removeInacct query))+ "Show the transactions in this period" $+ headerCell $ renderPeriodHeading ph spn++-- | A cell showing a period in an account's row, linking to the+-- account's register for that period.+dateSpanCellWith ::+ (Spr.Lines border) =>+ LinkOpts -> PeriodTitles -> Maybe Text -> [Text] -> Text -> DateSpan -> Spr.Cell border Text+dateSpanCellWith lo ph base query acct spn =+ withLink+ (composeAnchorWith (accountParams (loIncludesSubs lo) acct ++ linkParams lo) base $+ dateTerm (loDate2 lo) (linkSpan lo spn) ++ removeDates (removeInacct query))+ "Show transactions affecting this account in this period" $+ Spr.defaultCell $ renderPeriodHeading ph spn++dateSpanCell ::+ (Spr.Lines border) =>+ PeriodTitles -> Maybe Text -> [Text] -> Text -> DateSpan -> Spr.Cell border Text+dateSpanCell = dateSpanCellWith defaultLinkOpts++-- | A cell showing a date in an account's row, linking to the account's+-- register for that day.+dateCell ::+ (Spr.Lines border) =>+ Maybe Text -> [Text] -> Text -> Day -> Spr.Cell border Text+dateCell base query acct d =+ withLink+ (composeAnchorWith (accountParams True acct) base $+ ("date:" <> showDate d) : removeDates (removeInacct query))+ "Show transactions affecting this account on this date" $+ Spr.defaultCell $ showDate d++-- | A cell for a period in a totals row, linking to the register of+-- everything in the report's query, restricted by the given terms (a+-- section's account types, say), for that period.+totalDateSpanCell ::+ (Spr.Lines border) =>+ LinkOpts -> PeriodTitles -> Maybe Text -> [Text] -> [Text] -> DateSpan -> Spr.Cell border Text+totalDateSpanCell lo ph base terms query spn =+ withLink+ (composeAnchorWith (linkParams lo) base $+ terms ++ dateTerm (loDate2 lo) (linkSpan lo spn) ++ removeDates (removeInacct query))+ (amountPhrase lo True) $+ Spr.defaultCell $ renderPeriodHeading ph spn++-- | Render a DateSpan as a period heading according to the requested style.+renderPeriodHeading :: PeriodTitles -> DateSpan -> Text+renderPeriodHeading PTDates = showDateSpanFull+renderPeriodHeading PTCompact = showDateSpan++-- | Link an account's cell to the account's register, restricted to the+-- given query. The query says which dates; the link options say whether+-- subaccounts are included and how the register accumulates.+setAccountAnchorWith ::+ LinkOpts -> Maybe Text -> [Text] -> Text -> Spr.Cell border text -> Spr.Cell border text+setAccountAnchorWith lo base query acct =+ withLink+ (composeAnchorWith (accountParams (loIncludesSubs lo) acct ++ linkParams lo) base $+ removeInacct query)+ (if loIncludesSubs lo+ then "Show transactions affecting this account and subaccounts"+ else "Show transactions affecting this account but not subaccounts")++setAccountAnchor ::+ Maybe Text -> [Text] -> Text -> Spr.Cell border text -> Spr.Cell border text+setAccountAnchor = setAccountAnchorWith defaultLinkOpts
+ Hledger/Cli/Anon.hs view
@@ -0,0 +1,61 @@+{-|++Instances for obfuscating sensitive data (mainly text, not numbers) in various types.++Currently this is deterministic and does not provide much privacy.+It has been moved to a hidden --obfuscate flag, with the old --anon flag+now raising an error. See https://github.com/hledgerorg/hledger/issues/2133 .++-}++module Hledger.Cli.Anon+ ( Anon(..)+ , anonAccount+ )+where++import Control.Arrow (first)+import Data.Hashable (hash)+import Data.Word (Word32)+import Numeric (showHex)+import Data.Text qualified as T++import Hledger.Data+import Data.Map (mapKeys)++class Anon a where+ -- | Consistent converter to structure with sensitive data anonymized+ anon :: a -> a++instance Anon Journal where+ -- Apply the anonymisation transformation on a journal after finalisation+ anon j = j { jtxns = map anon . jtxns $ j+ , jitems = [] -- verbatim source text, may contain anything+ , jparseparentaccounts = map anonAccount $ jparseparentaccounts j+ , jparsealiases = [] -- already applied+ , jparseoptaliases = [] -- already applied+ , jdeclaredaccounts = map (first anon) $ jdeclaredaccounts j+ , jdeclaredaccounttags = mapKeys anon $ jdeclaredaccounttags j+ , jdeclaredaccounttypes = (map anon) <$> jdeclaredaccounttypes j+ }++instance Anon Posting where+ anon p = p { paccount = anonAccount . paccount $ p+ , pcomment = T.empty+ , ptransaction = fmap anon . ptransaction $ p -- Note that this will be overridden+ , poriginal = anon <$> poriginal p+ }++instance Anon Transaction where+ anon txn = txnTieKnot $ txn { tpostings = map anon . tpostings $ txn+ , tdescription = anon . tdescription $ txn+ , tcode = anon . tcode $ txn+ , tcomment = T.empty+ , tprecedingcomment = T.empty+ }++-- | Anonymize account name preserving hierarchy+anonAccount :: AccountName -> AccountName+anonAccount = T.intercalate (T.pack ":") . map anon . T.splitOn (T.pack ":")++instance Anon T.Text where anon = T.pack . flip showHex "" . (fromIntegral :: Int -> Word32) . hash
− Hledger/Cli/Balance.hs
@@ -1,180 +0,0 @@-{-|--A ledger-compatible @balance@ command.--ledger's balance command is easy to use but not easy to describe-precisely. In the examples below we'll use sample.journal, which has the-following account tree:--@- assets- bank- checking- saving- cash- expenses- food- supplies- income- gifts- salary- liabilities- debts-@--The balance command shows accounts with their aggregate balances.-Subaccounts are displayed indented below their parent. Each balance is the-sum of any transactions in that account plus any balances from-subaccounts:--@- $ hledger -f sample.journal balance- $-1 assets- $1 bank:saving- $-2 cash- $2 expenses- $1 food- $1 supplies- $-2 income- $-1 gifts- $-1 salary- $1 liabilities:debts-@--Usually, the non-interesting accounts are elided or omitted. Above,-@checking@ is omitted because it has no subaccounts and a zero balance.-@bank@ is elided because it has only a single displayed subaccount-(@saving@) and it would be showing the same balance as that ($1). Ditto-for @liabilities@. We will return to this in a moment.--The --depth argument can be used to limit the depth of the balance report.-So, to see just the top level accounts:--@-$ hledger -f sample.journal balance --depth 1- $-1 assets- $2 expenses- $-2 income- $1 liabilities-@--This time liabilities has no displayed subaccounts (due to --depth) and-is not elided.--With one or more account pattern arguments, the balance command shows-accounts whose name matches one of the patterns, plus their parents-(elided) and subaccounts. So with the pattern o we get:--@- $ hledger -f sample.journal balance o- $1 expenses:food- $-2 income- $-1 gifts- $-1 salary---------------------- $-1-@--The o pattern matched @food@ and @income@, so they are shown. Unmatched-parents of matched accounts are also shown (elided) for context (@expenses@).--Also, the balance report shows the total of all displayed accounts, when-that is non-zero. Here, it is displayed because the accounts shown add up-to $-1.--Also, non-interesting accounts may be elided. Here's an imperfect-description of the ledger balance command's eliding behaviour:-\"Interesting\" accounts are displayed on their own line. An account less-deep than the report's max depth, with just one interesting subaccount,-and the same balance as the subaccount, is non-interesting, and prefixed-to the subaccount's line, unless (hledger's) --no-elide is in effect.-An account with a zero inclusive balance and less than two interesting-subaccounts is not displayed at all, unless --empty is in effect.---}--module Hledger.Cli.Balance (- balance- ,accountsReportAsText- ,tests_Hledger_Cli_Balance-) where--import Data.List-import Data.Maybe-import Test.HUnit--import Hledger-import Prelude hiding (putStr)-import Hledger.Utils.UTF8 (putStr)-import Hledger.Cli.Format-import qualified Hledger.Cli.Format as Format-import Hledger.Cli.Options----- | Print a balance report.-balance :: CliOpts -> Journal -> IO ()-balance CliOpts{reportopts_=ropts} j = do- d <- getCurrentDay- let lines = case formatFromOpts ropts of- Left err -> [err]- Right _ -> accountsReportAsText ropts $ accountsReport ropts (optsToFilterSpec ropts d) j- putStr $ unlines lines---- | Render a balance report as plain text suitable for console output.-accountsReportAsText :: ReportOpts -> AccountsReport -> [String]-accountsReportAsText opts (items, total) = concat lines ++ t- where- lines = case formatFromOpts opts of- Right f -> map (accountsReportItemAsText opts f) items- Left err -> [[err]]- t = if no_total_ opts- then []- else ["--------------------"- -- TODO: This must use the format somehow- ,padleft 20 $ showMixedAmountWithoutPrice total- ]--{--This implementation turned out to be a bit convoluted but implements the following algorithm for formatting:--- If there is a single amount, print it with the account name directly:-- Otherwise, only print the account name on the last line.-- a USD 1 ; Account 'a' has a single amount- EUR -1- b USD -1 ; Account 'b' has two amounts. The account name is printed on the last line.--}--- | Render one balance report line item as plain text.-accountsReportItemAsText :: ReportOpts -> [FormatString] -> AccountsReportItem -> [String]-accountsReportItemAsText opts format (_, accountName, depth, Mixed amounts) =- case amounts of- [] -> []- [a] -> [formatAccountsReportItem opts (Just accountName) depth a format]- (as) -> multiline as- where- multiline :: [Amount] -> [String]- multiline [] = []- multiline [a] = [formatAccountsReportItem opts (Just accountName) depth a format]- multiline (a:as) = (formatAccountsReportItem opts Nothing depth a format) : multiline as--formatAccountsReportItem :: ReportOpts -> Maybe AccountName -> Int -> Amount -> [FormatString] -> String-formatAccountsReportItem _ _ _ _ [] = ""-formatAccountsReportItem opts accountName depth amount (fmt:fmts) =- s ++ (formatAccountsReportItem opts accountName depth amount fmts)- where- s = case fmt of- FormatLiteral l -> l- FormatField ljust min max field -> formatField opts accountName depth amount ljust min max field--formatField :: ReportOpts -> Maybe AccountName -> Int -> Amount -> Bool -> Maybe Int -> Maybe Int -> Field -> String-formatField opts accountName depth total ljust min max field = case field of- Format.Account -> formatValue ljust min max $ maybe "" (accountNameDrop (drop_ opts)) accountName- Format.DepthSpacer -> case min of- Just m -> formatValue ljust Nothing max $ replicate (depth * m) ' '- Nothing -> formatValue ljust Nothing max $ replicate depth ' '- Format.Total -> formatValue ljust min max $ showAmountWithoutPrice total- _ -> ""--tests_Hledger_Cli_Balance = TestList- [- ]
+ Hledger/Cli/Chart.hs view
@@ -0,0 +1,615 @@+{-|+Turning reports into charts ("Hledger.Write.Chart"), and the --chart option.++Each adapter here chooses a useful default chart for its report,+so that charts just work without configuration (see doc/SPEC-charts.md, "Smart defaults").+-}++{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}++module Hledger.Cli.Chart (+ chartFlag,+ balanceChartFlag,+ compoundChartFlag,+ chartWidthFlag,+ ChartArg(..),+ parseChartArg,+ chartArg,+ chartArgFor,+ chartRequested,+ chartAsTextForOpts,+ writeChart,+ multiBalanceReportAsChart,+ balanceReportAsChart,+ compoundBalanceReportAsChart,+ accountTransactionsReportAsChart,+ postingsReportAsChart,+ unitAmount,+) where++import Data.List (elemIndex, find, intercalate, isPrefixOf, nub, partition, sort, sortOn, transpose)+import Data.List.Extra (nubSort, splitOn, trim)+#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif+import Data.Map qualified as M+import Data.Maybe (fromMaybe, isJust, mapMaybe)+import Data.Ord (Down(..))+import Data.Set qualified as S+import Control.Applicative ((<|>))+import Control.Monad (when)+import Data.Char (isDigit, toUpper)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Lazy qualified as TL+import Data.Time (Day)+import GHC.IO.Encoding (getLocaleEncoding, textEncodingName)+import Safe (atMay, headMay, readMay)+import System.Console.CmdArgs.Explicit (Flag, flagOpt, flagReq)+import Text.Printf (printf)++import Hledger+import Hledger.Cli.CliOptions (CliOpts(..), outputFormatFromOpts, outputFormats)+import Hledger.Cli.Utils (unsupportedOutputFormatError, writeOutputLazyText)+import Hledger.Utils.I18n qualified as I18n+import Hledger.Write.Chart+import Hledger.Write.Chart.Svg (chartAsSvg, chartAsSvgWith)+import Hledger.Write.Chart.Text+import Hledger.Write.Csv (printCSV, printTSV)+import Hledger.Write.Html (htmlAsLazyText, nl)+import Text.Blaze.Html5 ((!))+import Text.Blaze.Html5 qualified as H+import Text.Blaze.Html5.Attributes qualified as A+++-- | The chart kinds that --chart accepts: auto (the default chart for the report),+-- or diverging or grouped (the bar layout for reports with several groups of accounts, ie compound reports' sections;+-- diverging is the default). A kind that doesn't apply to a report is ignored.+chartKinds :: [String]+chartKinds = ["auto", "diverging", "grouped"]++-- | The words that --chart accepts before its SCALE amounts, in any order: a chart kind (see 'chartKinds'),+-- and net, which draws the total or net (as a line or marks), which charts otherwise leave out (text charts still show it as a number).+chartWords :: [String]+chartWords = chartKinds ++ ["net"]++-- | What --chart's value says: a chart kind, whether to draw the total or net, and scale amounts.+data ChartArg = ChartArg+ { caKind :: String+ , caNet :: Bool+ , caScales :: [Amount]+ }++-- | The --chart[=net,SCALE] option, for commands that can show a chart.+-- It also accepts a KIND, like 'compoundChartFlag', but it is ignored, so not mentioned.+chartFlag :: Flag RawOpts+chartFlag = chartFlagWith "net,SCALE" ""++-- | The --chart[=KIND,net,SCALE] option, for the balance command, whose charts can group accounts by type.+balanceChartFlag :: Flag RawOpts+balanceChartFlag = chartFlagWith "KIND,net,SCALE"+ "KIND: grouped (a bar per account type, side by side). "++-- | The --chart[=KIND,net,SCALE] option, for compound balance commands, whose sections a chart can arrange.+compoundChartFlag :: Flag RawOpts+compoundChartFlag = chartFlagWith "KIND,net,SCALE"+ "KIND: diverging (sections above and below zero; the default) or grouped (sections side by side). "++chartFlagWith :: String -> String -> Flag RawOpts+chartFlagWith metavar kindhelp = flagOpt "auto" ["chart"] setchart metavar $+ "show a chart: instead of the table (txt), above it (html), or as data (csv, tsv, json). "+ ++ kindhelp+ ++ "net: also draw the net total (a line, or marks in text charts). "+ ++ "SCALE: the amount that fills the chart (eg 1000 or 1000 USD; one per commodity), for comparable charts."+ where+ setchart s opts = either Left (const $ Right $ setopt "chart" s opts) $ parseChartArg M.empty s++-- | Parse the value of --chart: comma-separated parts, which are optional words (an optional chart kind, default auto,+-- and net, in any order), followed by optional scale amounts (see 'setChartScales'), read with these commodity styles+-- (so that eg 10.000 EUR is ten thousand when EUR is written with a decimal comma).+-- Since commas separate the parts, a comma between digits (a decimal comma, or a digit group mark) is an error.+parseChartArg :: M.Map CommoditySymbol AmountStyle -> String -> Either String ChartArg+parseChartArg styles s+ | or [isDigit a && b == ',' && isDigit c | (a, b, c) <- zip3 s (drop 1 s) (drop 2 s)] = Left $+ "--chart's SCALE amounts should be written without a comma (commas separate them; use . as decimal mark, eg 2.5 BTC,"+ ++ " and leave out digit group marks or use spaces, eg 10000 EUR or 10 000 EUR), but this was not: " ++ s+ | otherwise = do+ let (ws, rest) = span (`elem` chartWords) $ filter (not . null) $ map trim $ splitOn "," s+ kind <- case filter (`elem` chartKinds) ws of+ [] -> Right "auto"+ [k] -> Right k+ ks -> Left $ "--chart's KIND should be given once, but these were given: " ++ intercalate ", " ks+ scales <- mapM scale rest+ Right ChartArg{caKind = kind, caNet = "net" `elem` ws, caScales = scales}+ where+ scale p+ | p `elem` chartWords = Left $ "--chart's KIND and net should come before any SCALE amounts, but this did not: " ++ p+ | Right a <- parseamountWithStyles styles p, aquantity a /= 0 = Right a+ | otherwise = Left $ "--chart's value should be a chart KIND (" ++ intercalate ", " chartKinds+ ++ ") and/or net, and/or non-zero SCALE amounts after them, separated by commas (and written without digit group marks), but this part was not: " ++ p++-- | What --chart's value says, reading its amounts with these commodity styles (by default, an auto chart).+chartArg :: M.Map CommoditySymbol AmountStyle -> CliOpts -> ChartArg+chartArg styles = either (const $ ChartArg "auto" False []) id . parseChartArg styles . fromMaybe "" . maybestringopt "chart" . rawopts_++-- | What --chart's value says for this chart, reading its amounts with the chart's commodity styles.+chartArgFor :: CliOpts -> Chart -> ChartArg+chartArgFor opts chart = chartArg (M.fromList [(acommodity u, astyle u) | Panel{pnUnit = u} <- chPanels chart]) opts++-- | Was a chart requested, with --chart or an output format that can only show charts (svg) ?+chartRequested :: CliOpts -> Bool+chartRequested opts = isJust (maybestringopt "chart" $ rawopts_ opts) || outputFormatFromOpts opts == "svg"++-- | The --width option, for commands that can show a chart.+chartWidthFlag :: Flag RawOpts+chartWidthFlag = flagReq ["width","w"] setwidth "N"+ "with --chart: draw the chart N characters wide (default: the terminal width)"+ where+ setwidth s opts = case readMay s :: Maybe Int of+ Just n | n > 0 -> Right $ setopt "width" s opts+ _ -> Left "--width should be a positive whole number"++-- | Draw a chart as text, as the command line options say:+-- --width characters wide or the terminal width, with colour if enabled+-- (exact 24-bit colours, like SVG charts', if the terminal advertises support for them, otherwise the terminal's basic colours),+-- and with unicode block characters if the system's text encoding is UTF-8 (otherwise ASCII).+-- Also warns if the chart has many panels (one per commodity).+chartAsTextForOpts :: CliOpts -> Chart -> IO TL.Text+chartAsTextForOpts CliOpts{width_, available_width_, reportspec_} chart = do+ unicode <- ("UTF-8" `isPrefixOf`) . map toUpper . textEncodingName <$> getLocaleEncoding+ let npanels = length $ chPanels chart+ when (npanels > maxPanels) $ warnIO $ printf+ ("this chart has %d panels, one per commodity. To show fewer, convert to one commodity (eg -X USD)\n"+ <> "or select some (eg cur:USD).")+ npanels+ truecolour <- supportsTrueColor+ let colourmode+ | not $ color_ $ _rsReportOpts reportspec_ = NoColour+ | truecolour = RgbColour (terminalIsLight == Just False) -- light variants unless the background is known to be dark+ | otherwise = BasicColour+ return $ styledLinesAsText colourmode $ chartAsStyledLines (TextChartOpts width unicode) chart+ where+ width = fromMaybe available_width_ (width_ >>= readMay)+ maxPanels = 8 :: Int++-- | Write a chart in the output format and to the destination selected by the command line options:+-- as text (txt), as an SVG image (svg), as the chart's data (csv, tsv, json),+-- or as an SVG image above the report's html, collapsed, if that is provided (html).+-- Other formats give an error (before the chart is computed).+writeChart :: CliOpts -> Maybe TL.Text -> Chart -> IO ()+writeChart opts mreporthtml chart = do+ render <- case fmt of+ "txt" -> return $ chartAsTextForOpts opts . withnet+ "svg" -> return $ return . chartAsSvg . withnet+ "html" | Just reporthtml <- mreporthtml ->+ -- without the dark variant, since our html is always light+ return $ \c -> return $ chartAsSvgWith False (withnet c) <> collapsedHtml (I18n.tr trans "Report details") reporthtml+ "csv" -> return $ return . printCSV . chartAsCsv+ "tsv" -> return $ return . printTSV . chartAsCsv+ "json" -> return $ return . (<>"\n") . toJsonText+ _ | fmt `elem` outputFormats -> error' $ "--chart does not yet support " ++ fmt ++ " output; try txt, svg, html, csv, tsv or json" -- PARTIAL:+ | otherwise -> error' $ unsupportedOutputFormatError fmt -- PARTIAL:+ render (setChartLayout barlayout $ setChartScales scales chart) >>= writeOutputLazyText opts+ where+ fmt = outputFormatFromOpts opts+ trans = translations_ $ _rsReportOpts $ reportspec_ opts+ ChartArg{caKind = kind, caNet = net, caScales = scales} = chartArgFor opts chart+ -- charts draw the total or net only with --chart=net (otherwise text charts show it only as a number, and chart data always has it)+ withnet = if net then id else chartWithoutTotalMarks+ barlayout = case kind of+ "grouped" -> Just Grouped+ "diverging" -> Just Diverging+ _ -> Nothing++-- | Some html (eg a report's table) in a collapsed section with the given label, which can be clicked to show it.+-- Its report title is hidden, since the chart above shows the same title.+collapsedHtml :: Text -> TL.Text -> TL.Text+collapsedHtml label html = htmlAsLazyText $ do+ H.style $ H.preEscapedText $ T.concat+ [ "details.hledger-details{font:14px/1.5 system-ui,-apple-system,\"Segoe UI\",sans-serif;font-variant-numeric:tabular-nums}"+ , "details.hledger-details>summary{width:fit-content;margin:8px 0;padding:2px 10px;border:1px solid #e1e0d9;border-radius:6px;color:#52514e;cursor:pointer}"+ , "details.hledger-details>summary:hover{background:#f3f2ee;color:#0b0b0b}"+ , "details.hledger-details .report-title{display:none}"+ ]+ nl+ H.details ! A.class_ "hledger-details" $ do+ H.summary $ H.toHtml label+ nl+ H.preEscapedLazyText html+ nl++-- | The most series to show in each section of a compound report chart: four accounts and "other"+-- (fewer than the type's 'maxTints', to keep these charts simple).+maxSectionSeries :: Int+maxSectionSeries = 5++-- | The most series to show in one panel. Beyond this, the smallest series are combined into one "other" series.+maxSeries :: Int+maxSeries = 8++-- | Chart a multi-period balance report.+--+-- Period changes (flows) are drawn as stacked bars, end balances (stocks, with --cumulative or --historical) as lines;+-- either way, the total is a line.+-- There is one panel per commodity, most-used commodity first.+-- In tree mode, each account's own amounts are charted, excluding its displayed subaccounts', so nothing is counted twice.+-- The total is omitted with -N, with --percent (where it is always 100), and when there is only one series.+-- Each series' group is its main account type (assets, liabilities, equity, revenues, expenses; then accounts of no known type),+-- so that the grouped layout (--chart=grouped) draws a bar per type, side by side, with the amounts' own signs.+multiBalanceReportAsChart :: (AccountName -> Maybe AccountType) -> ReportOpts -> Text -> MultiBalanceReport -> Chart+multiBalanceReportAsChart accttype ropts@ReportOpts{balanceaccum_, balancecalc_, accountlistmode_, no_total_, percent_, translations_} title+ (PeriodicReport spans rows totals) =+ Chart+ { chTitle = title+ -- with no report interval (a grouped chart of the whole report period), the title names the period+ , chXAxis = XPeriods [(s, if interval_ ropts == NoInterval then "" else reportPeriodName ropts spans s) | s <- spans]+ , chPanels = mapMaybe panel $ commoditiesByUse cells+ , chNotes = []+ }+ where+ flow = balanceaccum_ == PerPeriod+ mark = if flow then MarkBar else MarkLine+ rows' = if accountlistmode_ == ALTree then ownAmountRows rows else rows+ cells = concatMap prrAmounts rows+ allamts = concatMap amountsRaw cells+ panel c+ | null series = Nothing+ | otherwise = Just Panel+ { pnUnit = unit+ , pnSeries = [s{seGroup = fromMaybe 0 $ elemIndex (seriestype s) types} | s <- series] ++ total+ , pnGroupNames = map typename types+ , pnScale = Nothing+ , pnLayout = Diverging+ , pnCounts = balanceCalcIsCount balancecalc_+ , pnSummary = rowSummaries ropts unit totals+ , pnValueLabels = []+ }+ where+ unit = unitAmount c allamts+ series = limitSeries maxSeries translations_ mark+ [ (accountLabel accttype $ prrName r, qs) | r <- rows', let qs = map (quantityIn c) (prrAmounts r), any (/= 0) qs ]+ totalqs = map (quantityIn c) $ prrAmounts totals+ total =+ [ Series (plainLabel $ I18n.tr translations_ "Total") SeriesTotal MarkLine (map Just totalqs) 0 0+ | length series > 1, not no_total_, not percent_ ]+ -- the main account types of this panel's series, in the usual order, with no known type last+ seriestype = fmap mainAccountType . lbType . seLabel+ types = [t | t <- map Just [Asset, Liability, Equity, Revenue, Expense] ++ [Nothing], t `elem` map seriestype series]+ typename t = case t of+ Just Asset -> tr "Assets"+ Just Liability -> tr "Liabilities"+ Just Equity -> tr "Equity"+ Just Revenue -> tr "Revenues"+ Just Expense -> tr "Expenses"+ -- TRANSLATORS: in a balance chart grouped by account type, the group of accounts with no known type.+ _ -> tr "Other"+ tr = I18n.tr translations_++-- | Chart a single-period balance report, as one bar per account (horizontal, since the accounts are categories).+-- There is one panel per commodity, most-used commodity first;+-- accounts with no amount in a panel's commodity have no value (a gap) there.+-- Unlike stacked charts, all rows are shown, with the report's indentation in tree mode.+-- The total, which belongs to no row (so is not drawn, even with --chart=net), is shown below the chart, as in the table;+-- not with -N or --percent.+balanceReportAsChart :: (AccountName -> Maybe AccountType) -> ReportOpts -> Text -> BalanceReport -> Chart+balanceReportAsChart accttype ReportOpts{balancecalc_, no_total_, percent_, translations_} title (items, total) =+ Chart+ { chTitle = title+ , chXAxis = XCategories [ChartLabel full short indent (accttype full) True [] | (full, short, indent, _) <- items]+ , chPanels = map panel $ commoditiesByUse cells+ , chNotes = []+ }+ where+ cells = [ma | (_, _, _, ma) <- items]+ allamts = concatMap amountsRaw cells+ panel c = Panel+ { pnUnit = unit+ , pnSeries = [Series (plainLabel $ I18n.tr translations_ "Balance") SeriesItem MarkBar+ [ if any ((== c) . acommodity) (amountsRaw ma) then Just (quantityIn c ma) else Nothing+ | (_, _, _, ma) <- items ] 0 0]+ , pnGroupNames = []+ , pnScale = Nothing+ , pnLayout = Diverging+ , pnCounts = balanceCalcIsCount balancecalc_+ , pnSummary = [Summary SummaryTotal (I18n.trc translations_ "column heading" "Total") (summaryAmount unit total) | not no_total_, not percent_]+ , pnValueLabels = []+ }+ where unit = unitAmount c allamts++-- | Chart a compound balance report (balancesheet, incomestatement, cashflow..): its sections' accounts, and the net total.+--+-- Amounts are shown as their contribution to the net total: positive for sections that add to it (eg revenues, assets),+-- negative for sections that subtract from it (eg expenses, liabilities). (The report's tables show both as positive.)+-- So bars above zero increase the net and bars below zero reduce it; eg a refund, which is a negative expense, is drawn above zero.+-- At each period, all sections' accounts are stacked in one diverging bar, positive amounts above zero and negative ones below+-- (the diverging layout, the default); or with --chart=grouped, each section's accounts are stacked in a bar of their own, side by side.+-- See 'setChartLayout', which also re-signs the data for the grouped layout.+-- Each series has its section (as its group) and the section's usual sign, so that renderers can show contra amounts (eg a refund) distinctly.+-- The net total is a line, for changes (eg incomestatement) as well as end balances (eg balancesheet),+-- so that all charts show their totals the same way.+-- A single-period report is drawn the same way, with one period. With -1 (depth 1), each section is a single bar.+-- There is one panel per commodity, most-used commodity first. Each section has at most 'maxSectionSeries' series,+-- the smallest accounts being combined into an "other" series. In tree mode, each account's own amounts are charted.+-- The net total is omitted with -N and with --percent.+--+-- The second argument gives each section's account type, if known (eg from the report's query for it); accounts with no+-- type of their own get their section's, for colouring. An account shown as "..." (eg with depth 0) is labelled with its section's title.+compoundBalanceReportAsChart :: (AccountName -> Maybe AccountType) -> [Maybe AccountType] -> ReportOpts -> CompoundPeriodicReport DisplayName MixedAmount -> Chart+compoundBalanceReportAsChart accttype sectiontypes ropts@ReportOpts{balancecalc_, accountlistmode_, no_total_, percent_, translations_}+ (CompoundPeriodicReport title spans subreports totals) =+ Chart+ { chTitle = title+ , chXAxis = XPeriods [(s, if length spans == 1 then "" else reportPeriodName ropts spans s) | s <- spans] -- the title names a single period+ , chPanels = mapMaybe panel $ commoditiesByUse cells+ , chNotes = []+ }+ where+ -- each section's sign (1 if it adds to the net total, -1 if it subtracts from it), and its account rows+ -- (in tree mode, with only their own amounts, so that nothing is counted twice)+ sections = [ ((t, sectype), if increasestotal then 1 else -1, if accountlistmode_ == ALTree then ownAmountRows (prRows r) else prRows r)+ | ((t, r, increasestotal), sectype) <- zip subreports (sectiontypes ++ repeat Nothing) ]+ -- an account's label, with its section's type if it has none, or its section's title if it's "..."+ sectionAccountLabel (t, sectype) r+ | lbFull l == "..." = ChartLabel t t 0 sectype True []+ | otherwise = l{lbType = lbType l <|> sectype}+ where l = accountLabel accttype $ prrName r+ -- a section's usual sign, for showing contra amounts; cash (cf's section) has none, since it flows both ways as usual+ usualSign (_, sectype) sign = if sectype == Just Cash then 0 else round sign+ nettotals = prrAmounts totals+ showtotal = not no_total_ && not percent_+ -- the table's "Net:" label, without the colon+ netlabel = T.dropWhileEnd (`elem` [':', '\xff1a']) $ I18n.tr translations_ "Net:"+ cells = concat [concatMap prrAmounts rows | (_, _, rows) <- sections] ++ nettotals+ allamts = concatMap amountsRaw cells+ panel c+ | null series = Nothing+ | otherwise = Just Panel+ { pnUnit = unit+ , pnSeries = series +++ [ Series (plainLabel netlabel) SeriesTotal MarkLine (map Just netqs) 0 0+ | showtotal ]+ , pnGroupNames = [t | (t, _, _) <- subreports]+ , pnScale = Nothing+ , pnLayout = Diverging+ , pnCounts = balanceCalcIsCount balancecalc_+ , pnSummary = rowSummaries ropts unit totals+ , pnValueLabels = []+ }+ where+ unit = unitAmount c allamts+ netqs = map (quantityIn c) nettotals+ series = concat+ [ [ s{seGroup = k, seSign = usualSign section sign} | s <- limitSeries maxSectionSeries translations_ MarkBar accts ]+ | (k, (section, sign, rows)) <- zip [0 ..] sections+ , let accts = [ (sectionAccountLabel section r, qs) | r <- rows, let qs = map ((* sign) . quantityIn c) (prrAmounts r), any (/= 0) qs ]+ ]++-- | Chart an account register (aregister): the balance after each transaction+-- (or the running total or average, as the report shows), as a line over time.+-- The arguments are the title, the account's name, and a function giving a transaction's date in the register.+-- There is one panel per commodity, most-used commodity first.+accountTransactionsReportAsChart :: (AccountName -> Maybe AccountType) -> Text -> AccountName -> (Transaction -> Day) -> AccountTransactionsReport -> Chart+accountTransactionsReportAsChart accttype title acct txndate items =+ Chart+ { chTitle = title+ , chXAxis = XDates [txndate t | (t, _, _, _, _, _) <- items]+ , chPanels = map panel $ commoditiesByUse bals+ , chNotes = []+ }+ where+ bals = [b | (_, _, _, _, _, b) <- items]+ allamts = concatMap amountsRaw bals+ panel c = Panel+ { pnUnit = unitAmount c allamts+ , pnSeries = [Series (ChartLabel acct acct 0 (accttype acct) True []) SeriesItem MarkLine (map (Just . quantityIn c) bals) 0 0]+ , pnGroupNames = []+ , pnScale = Nothing+ , pnLayout = Diverging+ , pnCounts = False+ , pnSummary = []+ , pnValueLabels = []+ }++-- | Chart a postings report (register).+-- With a report interval, each account's amount in each period is drawn as stacked bars, with the period's total as a line+-- (like a multi-period balance report; at most 'maxSeries' series, the smallest combined into "other").+-- Otherwise, the running total (or average) after each posting is drawn as a line over time;+-- and with postings to several accounts (and not --average), each account's own running total (from the report start) is drawn too,+-- in its account type's colour, with the overall running total in ink.+-- There is one panel per commodity, most-used commodity first.+--+-- The second argument gives the accounts' balances before the report period, if the running total includes them+-- (with --historical; see 'postingsReportStartBalances'), so that each account's running total starts from its balance.+postingsReportAsChart :: (AccountName -> Maybe AccountType) -> M.Map AccountName MixedAmount -> ReportOpts -> Text -> PostingsReport -> Chart+postingsReportAsChart accttype startbals ropts@ReportOpts{average_, translations_} title items+ | null periods =+ let totals = [t | (_, _, _, _, t) <- items]+ totalamts = concatMap amountsRaw totals+ totalseries c role = Series ((plainLabel $ I18n.tr translations_ "Total"){lbType = commontype}) role MarkLine (map (Just . quantityIn c) totals) 0 0+ -- with postings to several accounts (and not --average), each account's running total as a line, and the overall running total;+ -- otherwise just the running total (labelled with the account, if there's one, so that it has the account's colour)+ linespanel c+ | average_ = Panel (unitAmount c totalamts) [totalseries c SeriesItem] [] Nothing Diverging False [] []+ | [a] <- runningTotalAccounts c = Panel (unitAmount c totalamts) [(totalseries c SeriesItem){seLabel = ChartLabel a a 0 (accttype a) True []}] [] Nothing Diverging False [] []+ | length (runningTotalAccounts c) < 2 = Panel (unitAmount c totalamts) [totalseries c SeriesItem] [] Nothing Diverging False [] []+ | otherwise = Panel (unitAmount c totalamts) (accountRunningTotals c ++ [totalseries c SeriesTotal]) [] Nothing Diverging False [] []+ in Chart+ { chTitle = title+ , chXAxis = XDates [postingDateOrDate2 (whichDate ropts) p | p <- postings]+ , chPanels = map linespanel $ commoditiesByUse totals+ , chNotes = []+ }+ | otherwise =+ Chart+ { chTitle = title+ , chXAxis = XPeriods [(s, reportPeriodName ropts{balanceaccum_ = PerPeriod} spans s) | s <- spans]+ , chPanels = mapMaybe panel $ commoditiesByUse cells+ , chNotes = []+ }+ where+ postings = [p | (_, _, _, p, _) <- items]+ -- Running totals (from the report start) of the postings' accounts in one commodity, as lines:+ -- for at most 'maxSeries' accounts, the largest by total absolute posting amount (in name order), and the rest combined as "other".+ -- (Only these are computed, since there can be many accounts and postings.)+ -- Each account starts from its balance before the report period, if any.+ accountRunningTotals c =+ [ Series (ChartLabel a a 0 (accttype a) True []) SeriesItem MarkLine (runningTotal (== a)) 0 0 | a <- kept ]+ ++ [ Series (otherLabel translations_ (length othergroups) grp){lbType = accttype . fst =<< headMay grp} SeriesOther MarkLine+ (runningTotal (`S.member` S.fromList (map fst grp))) 0 0+ | grp <- othergroups ]+ where+ sizes = M.toList $ accountSizes c+ (keptis, othergroupis) = chooseSeries maxSeries [(mainAccountType <$> accttype a, q) | (a, q) <- sizes]+ kept = map fst $ mapMaybe (atMay sizes) keptis+ othergroups = map (mapMaybe (atMay sizes)) othergroupis+ runningTotal match =+ map Just $ drop 1 $ scanl (+) (sum [startIn c a | a <- M.keys startbals, match a])+ [if match (paccount p) then quantityIn c (pamount p) else 0 | p <- postings]+ -- the accounts with postings, or a starting balance, in this commodity, with their total absolute amount (for ranking)+ accountSizes c = M.filter (/= 0) $ M.unionWith (+)+ (M.fromListWith (+) [(paccount p, abs $ quantityIn c $ pamount p) | p <- postings])+ (M.fromList [(a, abs q) | a <- M.keys startbals, let q = startIn c a, q /= 0])+ runningTotalAccounts c = M.keys $ accountSizes c+ startIn c a = maybe 0 (quantityIn c) $ M.lookup a startbals+ -- the main account type of all the postings' accounts, if they have one+ commontype = case nubSort [mainAccountType t | (_, _, _, p, _) <- items, Just t <- [accttype $ paccount p]] of+ [t] | all (isJust . accttype . paccount) [p | (_, _, _, p, _) <- items] -> Just t+ _ -> Nothing+ periods = nubSort [prd | (_, Just prd, _, _, _) <- items]+ spans = map periodAsDateSpan periods+ -- each account's amount in each period+ acctamts :: M.Map AccountName (M.Map Period MixedAmount)+ acctamts = M.fromListWith (M.unionWith (<>)) [(paccount p, M.singleton prd (pamount p)) | (_, Just prd, _, p, _) <- items]+ rows = [(a, [M.findWithDefault nullmixedamt prd m | prd <- periods]) | (a, m) <- M.toList acctamts]+ cells = concatMap snd rows+ allamts = concatMap amountsRaw cells+ panel c+ | null series = Nothing+ | otherwise = Just Panel{pnUnit = unitAmount c allamts, pnSeries = series ++ total, pnGroupNames = [], pnScale = Nothing, pnLayout = Diverging, pnCounts = False, pnSummary = [], pnValueLabels = []}+ where+ series = limitSeries maxSeries translations_ MarkBar+ [ (ChartLabel a a 0 (accttype a) True [], qs) | (a, amts) <- rows, let qs = map (quantityIn c) amts, any (/= 0) qs ]+ totalqs = map sum $ transpose [map (quantityIn c) amts | (_, amts) <- rows]+ total =+ [ Series (plainLabel $ I18n.tr translations_ "Total") SeriesTotal MarkLine (map Just totalqs) 0 0+ | length series > 1 ]++-- Helpers++-- | Keep at most this many series. If there are more, keep the largest (by total absolute value) in their original order,+-- and combine the rest into a final "other" series.+limitSeries :: Int -> I18n.Translations -> Mark -> [(ChartLabel, [Quantity])] -> [Series]+limitSeries maxn t mark items =+ [ Series l SeriesItem mark (map Just qs) 0 0 | i <- kept, Just (l, qs) <- [items `atMay` i] ]+ ++ [ Series (otherLabel t (length othergroups) [(lbFull l, sum $ map abs qs) | (l, qs) <- grp]){lbType = lbType . fst =<< headMay grp} SeriesOther mark+ (map (Just . sum) $ transpose $ map snd grp) 0 0+ | grp <- map (mapMaybe (items `atMay`)) othergroups ]+ where+ (kept, othergroups) = chooseSeries maxn [(mainAccountType <$> lbType l, sum $ map abs qs) | (l, qs) <- items]++-- | Choose which of these items (given as their account type, if known, and size) to show as series of their own,+-- when at most n series can be shown: all of them if they fit; otherwise the largest, but at least the largest of each+-- account type, with the rest of each type to be combined into an "other" series (so accounts of different types,+-- eg assets and liabilities, are never combined). A type with just one item left over shows that item instead.+-- Returns the positions of the items to show (in order), and of each type's items to combine (each at least two).+chooseSeries :: Int -> [(Maybe AccountType, Quantity)] -> ([Int], [[Int]])+chooseSeries n items+ | length items <= n = (positions, [])+ | otherwise = (sort $ S.toList keptset ++ concat singles, multiples)+ where+ positions = [0 .. length items - 1]+ typeAt i = maybe Nothing fst (items `atMay` i)+ sizeAt i = maybe 0 snd (items `atMay` i)+ types = nub $ map typeAt positions+ ranked = sortOn (Down . sizeAt) positions+ -- the largest of each type, then more by size while they fit, with a series for each type's leftovers+ guaranteed = S.fromList [i | ty <- types, Just i <- [find ((== ty) . typeAt) ranked]]+ keptset = foldl' (\ks i -> let ks' = S.insert i ks in if fits ks' then ks' else ks) guaranteed ranked+ fits ks = S.size ks + length (filter (not . null) $ leftovers ks) <= n+ leftovers ks = [[i | i <- positions, typeAt i == ty, i `S.notMember` ks] | ty <- types]+ (singles, multiples) = partition ((== 1) . length) $ filter (not . null) $ leftovers keptset++-- | The label for an "other" series combining these accounts (given with their sizes), whose tooltips list them,+-- largest first, up to ten. When there are several "other" series, it names the accounts' common parent,+-- if they have one, to tell them apart.+otherLabel :: I18n.Translations -> Int -> [(AccountName, Quantity)] -> ChartLabel+otherLabel t nothers sized = label{lbTipLines = take maxlisted members ++ more}+ where+ maxlisted = 10+ members = map fst $ sortOn (Down . snd) sized+ nmore = length members - maxlisted+ -- TRANSLATORS: after the accounts listed in the tooltip of a chart's "other accounts" series, how many more it combines.+ more = [I18n.trn t nmore "…and {n} more" "…and {n} more" | nmore > 0]++ label+ | nothers > 1, not (T.null parent) = plainLabel $ T.replace "{parent}" parent $ I18n.trn t n "other {parent} ({n} account)" "other {parent} ({n} accounts)"+ | otherwise = plainLabel $ I18n.trn t n "other ({n} account)" "other ({n} accounts)"+ accts = map fst sized+ n = length accts+ parent = case map (T.splitOn ":") accts of+ [] -> ""+ p : ps -> T.intercalate ":" $ foldl' commonPrefix p ps+ commonPrefix a b = map fst $ takeWhile (uncurry (==)) $ zip a b++-- | In tree mode, a parent account's row includes the amounts of its displayed subaccounts' rows.+-- Subtract those, leaving each row with only its own amounts.+ownAmountRows :: [MultiBalanceReportRow] -> [MultiBalanceReportRow]+ownAmountRows rows = map own rows+ where+ fullname = displayFull . prrName+ names = S.fromList $ map fullname rows+ displayedParent r = find (`S.member` names) $ parentAccountNames $ fullname r+ children = M.fromListWith (++) [(p, [r]) | r <- rows, Just p <- [displayedParent r]]+ own r = case M.lookup (fullname r) children of+ Nothing -> r+ Just cs -> r{prrAmounts = foldl' (zipWith maMinus) (prrAmounts r) (map prrAmounts cs)}++-- | The commodities with non-zero quantities in these report cells,+-- those in the most cells first, then alphabetically.+-- (Cells are counted, not amounts, since a cell can hold several amounts of one commodity with different costs.)+commoditiesByUse :: [MixedAmount] -> [CommoditySymbol]+commoditiesByUse cells =+ map fst $ sortOn (\(c, n) -> (Down n, c)) $ M.toList $+ M.fromListWith (+) [(c, 1 :: Int) | ma <- cells, c <- S.toList $ maCommodities ma, quantityIn c ma /= 0]++-- | A unit for values in this commodity: an amount of it from the list (for its display style),+-- with zero quantity and no cost.+unitAmount :: CommoditySymbol -> [Amount] -> Amount+unitAmount c as = case find ((== c) . acommodity) as of+ Just a -> a{aquantity = 0, acost = Nothing, acostbasis = Nothing}+ Nothing -> nullamt{acommodity = c}++-- | With -T or -A: the total (in a chart of changes per period) and the average per period of the report's totals row,+-- in the given unit's commodity, labelled like the report table's columns.+-- In a chart of end balances, the average is of the period-end balances, and the total (the last balance) is left out.+-- Each keeps its own display style, eg an average of counts has a decimal place.+rowSummaries :: ReportOpts -> Amount -> PeriodicReportRow a MixedAmount -> [Summary]+rowSummaries ReportOpts{balanceaccum_, row_total_, average_, percent_, translations_} unit totals+ | percent_ = []+ | otherwise =+ [Summary SummaryTotal (heading "Total") (summaryAmount unit $ prrTotal totals) | row_total_, balanceaccum_ == PerPeriod]+ ++ [Summary SummaryAverage (heading "Average") (summaryAmount unit $ prrAverage totals) | average_]+ where+ heading = I18n.trc translations_ "column heading"++-- | A mixed amount's quantity in the given unit's commodity, as that unit, with the amount's own display style if it has one.+summaryAmount :: Amount -> MixedAmount -> Amount+summaryAmount unit ma = case [a | a <- amountsRaw ma, acommodity a == c] of+ a:_ -> unit{aquantity = quantityIn c ma, astyle = astyle a}+ [] -> unit+ where c = acommodity unit++-- | The total quantity of this commodity in a mixed amount, ignoring costs.+quantityIn :: CommoditySymbol -> MixedAmount -> Quantity+quantityIn c ma = sum [aquantity a | a <- amountsRaw ma, acommodity a == c]++-- | A label for an account (or accounts, eg a depth-clipped one), from a report row's name.+-- A "..." row (all accounts, eg with depth 0) is labelled as not an account, like a total, so that alone it is drawn neutral.+accountLabel :: (AccountName -> Maybe AccountType) -> DisplayName -> ChartLabel+accountLabel accttype DisplayName{displayFull, displayName, displayIndent} =+ ChartLabel displayFull displayName displayIndent (accttype displayFull) (displayFull /= "...") []++-- | A label for something other than an account, eg a total.+plainLabel :: Text -> ChartLabel+plainLabel t = ChartLabel t t 0 Nothing False []
+ Hledger/Cli/CliOptions.hs view
@@ -0,0 +1,1022 @@+{-|++Common cmdargs modes and flags, a command-line options type, and+related utilities used by hledger commands.++-}++{-# LANGUAGE CPP #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE PackageImports #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE TypeFamilies #-}+{-# LANGUAGE TypeOperators #-}+{-# LANGUAGE NamedFieldPuns #-}++module Hledger.Cli.CliOptions (+ progname,+ prognameandversion,+ prognameandversionnoarch,+ binaryinfo,++ -- * cmdargs flags & modes+ inputflags,+ reportflags,+ helpflags,+ terminalflags,+ helpflagstitle,+ flattreeflags,+ confflags,+ hiddenflags,+ hiddenflagsformainmode,+ -- outputflags,+ outputFormatFlag,+ outputFileFlag,+ outputViewFlag,+ viewRequested,+ generalflagsgroup1,+ generalflagsgroup2,+ generalflagsgroup3,+ mkgeneralflagsgroups1,+ mkgeneralflagsgroups2,+ mkgeneralflagsgroups3,+ cligeneralflagsgroups1,+ cligeneralflagsgroups2,+ cligeneralflagsgroups3,+ defMode,+ defCommandMode,+ addonCommandMode,+ hledgerCommandMode,+ argsFlag,+ showModeUsage,+ withAliases,+ likelyExecutablesInPath,+ builtinLanguageCodes,++ -- * CLI options+ CliOpts(..),+ HasCliOpts(..),+ defcliopts,+ getHledgerCliOpts,+ getHledgerCliOpts',+ rawOptsToCliOpts,+ generalRawOpts,+ insertRawOpts,+ cliOptsDropArgs,+ journalCreatingCommandNames,+ journalIgnoringCommandNames,+ argsMarkRunCommands,+ runCommandsMarker,+ outputFormats,+ defaultOutputFormat,+ CommandHelpStr,+ parseCommandHelp,++ -- possibly these should move into argsToCliOpts+ -- * CLI option accessors+ -- | These do the extra processing required for some options.+ journalFilePathFromOpts,+ journalFilePathFromOptsNoDefault,+ rulesFilePathFromOpts,+ outputFileFromOpts,+ outputFormatFromOpts,+ filePathExtension,+ defaultWidth,+ replaceNumericFlags,+ ensureDebugFlagHasVal,+ -- | For register:+ registerWidthsFromOpts,++ -- * Other utils+ topicForMode,+ DeclarablesSelector(..),+ declarablesSelectorFromOpts,+ findMatchedByArgument,++-- -- * Convenience re-exports+-- module Data.String.Here,+-- module System.Console.CmdArgs.Explicit,+)+where++import Control.Exception qualified as C+import Control.Monad (when)+import Data.Char+import Data.Default+import Data.List.Extra (intercalate, nubSort)+import Data.List.NonEmpty qualified as NE (NonEmpty, fromList, nonEmpty)+import Data.List.Split (splitOn)+import Data.Maybe+--import Data.String.Here+-- import Data.Text (Text)+import Data.Text qualified as T+import Data.Void (Void)+import Safe+import String.ANSI+import System.Console.CmdArgs hiding (Default,def)+import System.Console.CmdArgs.Explicit+import System.Console.CmdArgs.Text+import System.Directory+import System.Environment+import System.Exit (exitSuccess)+import System.FilePath+import System.Info (os)+import Text.Megaparsec+import Text.Megaparsec.Char++import Hledger.Utils.I18n (builtinLanguages, shortLangTag, translationsForLangOption)+import Hledger+import Hledger.Cli.DocFiles+import Hledger.Cli.GitInfo (gitInfo)+import Hledger.Cli.Version+import Data.Time.Clock.POSIX (POSIXTime)+import Data.List (dropWhileEnd, find, isPrefixOf, isSuffixOf)+import Data.Function ((&))+++-- | The name of this program's executable.+progname :: ProgramName+progname = "hledger"++-- | Generate the version string for this program.+prognameandversion :: String+prognameandversion =+ versionStringWith+ gitInfo+#ifdef GHCDEBUG+ True+#else+ False+#endif+ progname+ packageversion++-- | Just the program name and version, without the machine architecture.+prognameandversionnoarch :: String+prognameandversionnoarch = takeWhile (/= ',') prognameandversion++binaryinfo :: HledgerBinaryInfo+Right binaryinfo = parseHledgerVersion prognameandversion+-- ui and web use nullbinaryinfo for a parse failure here to silence an inexhaustive pattern warning.+-- I can't reproduce that warning right now, so here I've stuck with the original approach,+-- which will force a compile error if prognameandversion is ever malformed, eg from unexpected+-- git output.++-- Common options.+-- keep synced: the docs macro in doc/common.m4++-- | Common input-related flags: --file, --rules, --conf, --alias...+inputflags :: [Flag RawOpts]+inputflags = [+ flagReq ["file","f"] (\s opts -> Right $ setopt "file" s opts) "[FMT:]FILE" $ unwords [+ "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."+ ]+ ,flagReq ["rules"] (\s opts -> Right $ setopt "rules" s opts) "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." -- see also hiddenflags++ ,flagReq ["alias"] (\s opts -> Right $ setopt "alias" s opts) "A=B|/RGX/=RPL" "transform account names from A to B, or by replacing regular expression matches"+ ,flagNone ["auto"] (setboolopt "auto") "generate extra postings by applying auto posting rules (\"=\") to all transactions"+ ,flagOpt "" ["forecast"] (\s opts -> Right $ setopt "forecast" s opts) "PERIOD" (unwords+ [ "Generate extra transactions from periodic rules (\"~\"),"+ , "from after the latest ordinary transaction until 6 months from now. Or, during the specified PERIOD (the equals is required)."+ , "Auto posting rules will also be applied to these transactions."+ , "In hledger-ui, also make future-dated transactions visible at startup."+ ])+ ,flagNone ["ignore-assertions"] (setboolopt "ignore-assertions") "don't check balance assertions by default"+ ,flagNone ["ignore-lots"] (setboolopt "ignore-lots") "don't track lots: skip lot checks, inferred cost bases and gain postings"+ ,flagNone ["I"] (setboolopt "ignore-assertions" . setboolopt "ignore-lots")+ "shortcut for --ignore-assertions --ignore-lots"+ ,flagReq ["txn-tolerance"] (\s opts -> Right $ setopt "txn-tolerance" s opts) "..." (unlines [+ "how much imbalance to allow in transactions:"+ ,"'entry': - the entry's precision (default)"+ ,"'display': - display precision (legacy)"+ ])+ ,flagNone ["infer-costs"] (setboolopt "infer-costs") "infer costs from conversion equity postings"+ ,flagNone ["infer-equity"] (setboolopt "infer-equity") "infer conversion equity postings from costs"+ ,flagNone ["infer-imbalance"] (setboolopt "infer-imbalance") "add postings showing tolerated imbalances"+ -- history of this flag so far, lest we be confused:+ -- originally --infer-value+ -- 2021-02 --infer-market-price added, --infer-value deprecated+ -- 2021-09+ -- --infer-value hidden+ -- --infer-market-price renamed to --infer-market-prices, old spelling still works+ -- ReportOptions{infer_value_} renamed to infer_prices_, BalancingOpts{infer_prices_} renamed to infer_transaction_prices_+ -- some related prices command changes+ -- --costs deprecated and hidden, uses --infer-market-prices instead+ -- --inverted-costs renamed to --infer-reverse-prices+ ,flagNone ["infer-market-prices"] (setboolopt "infer-market-prices") "infer market prices from costs"+ ,flagReq ["pivot"] (\s opts -> Right $ setopt "pivot" s opts) "TAGNAME" "use a different field or tag as account names"+ ,flagNone ["strict","s"] (setboolopt "strict") "do extra error checks (and override -I)"+ ]++-- | Common report-related flags: --period, --cost, etc.+reportflags :: [Flag RawOpts]+reportflags = [++ -- report period, interval, dates+ flagReq ["begin","b"] (\s opts -> Right $ setopt "begin" s opts) "DATE" "include postings/transactions on/after this date"+ ,flagReq ["end","e"] (\s opts -> Right $ setopt "end" s opts) "DATE" "include postings/transactions before this date (with a report interval, will be adjusted to following subperiod end)"+ ,flagNone ["daily","D"] (setboolopt "daily") "set report interval: 1 day"+ ,flagNone ["weekly","W"] (setboolopt "weekly") "set report interval: 1 week"+ ,flagNone ["monthly","M"] (setboolopt "monthly") "set report interval: 1 month"+ ,flagNone ["quarterly","Q"] (setboolopt "quarterly") "set report interval: 1 quarter"+ ,flagNone ["yearly","Y"] (setboolopt "yearly") "set report interval: 1 year"+ ,flagReq ["period","p"] (\s opts -> Right $ setopt "period" s opts) "PERIODEXP" "set begin date, end date, and/or report interval, with more flexibility"+ ,flagReq ["today"] (\s opts -> Right $ setopt "today" s opts) "DATE" "override today's date (affects relative dates)"+ ,flagNone ["date2"] (setboolopt "date2") "match/use secondary dates instead (deprecated)" -- see also hiddenflags++ -- status/realness/zero/depth filters+ ,flagNone ["unmarked","U"] (setboolopt "unmarked") "include only unmarked postings/transactions"+ ,flagNone ["pending","P"] (setboolopt "pending") "include only pending postings/transactions"+ ,flagNone ["cleared","C"] (setboolopt "cleared") "include only cleared postings/transactions\n(-U/-P/-C can be combined)"+ ,flagNone ["real","R"] (setboolopt "real") "include only non-virtual postings"+ ,flagNone ["empty","E"] (setboolopt "empty") "Show zero items, which are normally hidden.\nIn hledger-ui & hledger-web, do the opposite."+ ,flagReq ["depth"] (\s opts -> Right $ setopt "depth" s opts) "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."++ -- valuation+ ,flagNone ["B","cost"] (setboolopt "B") "convert amounts to their cost basis ({}), or else their cost/sale amount (@/@@)"+ -- ^ no "valuation mode:" prefix for this one, it's not mutually exclusive+ ,flagNone ["V","market"] (setboolopt "V")+ (unwords+ [valuationprefix ++ "show amounts converted to market value at period end(s) in their default valuation commodity."+ ,"Short for --value=end."+ ])+ ,flagReq ["X","exchange"] (\s opts -> Right $ setopt "X" s opts) "COMM"+ (unwords+ [valuationprefix ++ "show amounts converted to market value at period end(s) in the specified commodity."+ ,"Short for --value=end,COMM."+ ])+ ,flagReq ["value"] (\s opts -> Right $ setopt "value" s opts) "WHEN[,COMM]"+ (unlines+ [valuationprefix ++ "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."+ ])++ -- display+ ,flagNone ["lots"] (setboolopt "lots") "show lot subaccounts and other lot details"+ ,flagReq ["commodity-style", "c"] (\s opts -> Right $ setopt "commodity-style" s opts) "S"+ "Override a commodity's display style.\nEg: -c '$1000.' or -c '1.000,00 EUR'"+ ,flagOpt "yes" ["pretty"] (\s opts -> Right $ setopt "pretty" s opts) "YN"+ "Use box-drawing characters in text output? The optional 'y'/'yes' or 'n'/'no' arg requires =."+ ,flagReq ["title"] (\s opts -> Right $ setopt "title" s opts) "T"+ "set or customise a report title"+ ,flagReq ["subreport-titles"] (\s opts -> Right $ setopt "subreport-titles" s opts) "TS"+ "customise subreport headings in compound reports (|-separated)"+ ,flagReq ["period-titles"] (\s opts -> Right $ setopt "period-titles" s opts) "OPT" $ unlines+ ["customise headings in periodic reports:"+ ,"'compact': readable period names when possible"+ ,"'dates': exact dates/date ranges always"+ ]+ ]+ where+ valuationprefix = "valuation mode: "++helpflags :: [Flag RawOpts]+helpflags = [+ flagNone ["?"] (setboolopt "quickref") "show the hledger quick reference"+ ,flagNone ["help","h"] (setboolopt "help") "show this command's usage help"+ ,flagNone ["info"] (setboolopt "info") "show this command's manual with info"+ ,flagNone ["man"] (setboolopt "man") "show this command's manual with man"+ ,flagNone ["webman"] (setboolopt "webman") "show this command's manual on the web"+ ,flagNone ["examples"] (setboolopt "examples") "show examples for this command"+ ,flagNone ["version"] (setboolopt "version") "show version information"+ ,flagOpt "" ["test"] (\s opts -> Right $ setopt "test" s opts) "PATTERN" "run built-in tests (those matching PATTERN) and exit"+ ,flagReq ["write-lang"] (\s opts -> Right $ setopt "write-lang" s opts) "LANG"+ "write LANG's PO file to the config directory, for editing translations, and exit"+ -- flagOpt would be more correct for --debug, showing --debug[=LVL] rather than --debug=[LVL] in help.+ -- But flagReq plus special handling in Cli.hs makes the = optional, removing a source of confusion.+ ,flagReq ["debug"] (\s opts -> Right $ setopt "debug" s opts) "[1-9]" "show this much debug output (default: 1)"+ ] -- XXX why are these duplicated in defCommandMode below ?+ <> terminalflags++-- Low-level flags affecting terminal output.+-- These are included in helpflags so they appear everywhere.+terminalflags = [+ flagReq ["pager"] (\s opts -> Right $ setopt "pager" s opts) "YN"+ "use a pager when needed ? y/yes (default) or n/no"++ -- keep synced with hledger-lib:colorOption:+ ,flagReq ["color","colour"] (\s opts -> Right $ setopt "color" s opts) "YNA"+ "use ANSI color ? y/yes, n/no, or auto (default)"+ ,flagReq ["lang"] (\s opts -> Right $ setopt "lang" s opts) "LANG"+ ("select the user interface language:\n"+ ++ intercalate ", " [T.unpack l ++ if l == "en" then " (default)" else "" | l <- builtinLanguageCodes]+ ++ ", or auto")+ ]++-- | The languages with a built-in catalog, plus English, as the shortest tags that+-- select them, for --lang's help (eg zh rather than zh-Hans, but pt-BR, since pt+-- would not select it).+builtinLanguageCodes :: [T.Text]+builtinLanguageCodes = map shortLangTag builtinLanguages++-- | Flags for selecting flat/tree mode, used for reports organised by account.+-- With a True argument, shows some extra help about inclusive/exclusive amounts.+flattreeflags :: Bool -> [Flag RawOpts]+flattreeflags showamounthelp = [+ flagNone ["flat","l"] (setboolopt "flat")+ (prefix ++ "show accounts as a flat list (default)"+ ++ if showamounthelp then ". Amounts exclude subaccount amounts, except where the account is depth-clipped." else "")+ ,flagNone ["tree","t"] (setboolopt "tree")+ (prefix ++ "show accounts as a tree" ++ if showamounthelp then ". Amounts include subaccount amounts." else "")+ ]+ where+ prefix = "list/tree mode: "++-- | hledger CLI's --conf/--no-conf flags.+confflags = [+ flagReq ["conf"] (\s opts -> Right $ setopt "conf" s opts) "CONFFILE"+ "Use extra options defined in this config file. If not specified, searches upward and in XDG config dir for hledger.conf (or .hledger.conf in $HOME)."+ ,flagNone ["no-conf","n"] (setboolopt "no-conf") "ignore any config file"+ ]++-- | Common legacy flags that are accepted but not shown in --help, when running the main mode.+hiddenflagsformainmode :: [Flag RawOpts]+hiddenflagsformainmode = [+ flagNone ["effective","aux-date"] (setboolopt "date2") "Ledger-compatible aliases for --date2"+ ,flagNone ["infer-value"] (setboolopt "infer-market-prices") "legacy flag that was renamed"+ ,flagNone ["pretty-tables"] (setopt "pretty" "always") "legacy flag that was renamed"+ ,flagNone ["anon"] (setboolopt "anon") "deprecated, renamed to --obfuscate" -- #2133, handled by anonymiseByOpts+ ,flagNone ["obfuscate"] (setboolopt "obfuscate") "slightly obfuscate hledger's output. Warning, does not give privacy. Formerly --anon." -- #2133, handled by maybeObfuscate+ ,flagNone ["old-timeclock", "timeclock-old"] (setboolopt "oldtimeclock") "don't pair timeclock entries by account name"+ ,flagNone ["old-glob"] (setboolopt "oldglob") "deprecated, no longer used as of 1.50.4" -- #2498+ ,flagReq ["rules-file"] (\s opts -> Right $ setopt "rules" s opts) "RULESFILE" "was renamed to --rules"+ ,flagReq ["txn-balancing"] (\s opts -> Right $ setopt "txn-tolerance" (txnBalancingToTolerance s) opts) "..." "was renamed to --txn-tolerance"+ ]+ where+ -- --txn-balancing's values, translated to --txn-tolerance's (others are passed through, to be rejected there)+ txnBalancingToTolerance "old" = "display"+ txnBalancingToTolerance "exact" = "entry"+ txnBalancingToTolerance s = s++-- Hidden flags accepted but not shown, when running subcommand or addon command modes.+-- Here we add the confflags, so their presence won't cause an error,+hiddenflags :: [Flag RawOpts]+hiddenflags = hiddenflagsformainmode ++ confflags++-- | Common output-related flags: --output-file, --output-format...++-- outputflags = [outputFormatFlag, outputFileFlag]++outputFormatFlag :: [String] -> Flag RawOpts+outputFormatFlag fmts = flagReq+ ["output-format","O"] (\s opts -> Right $ setopt "output-format" s opts) "FMT"+ ("select the output format. Supported formats:\n" ++ intercalate ", " fmts ++ ".")++-- This has special support in hledger-lib:outputFileOption, keep synced+outputFileFlag :: Flag RawOpts+outputFileFlag = flagReq+ ["output-file","o"] (\s opts -> Right $ setopt "output-file" s opts) "FILE"+ "write output to FILE. A file extension matching one of the above formats selects that format."++-- | --view: write the output to a file and open it with the system's default viewer for that kind of file.+outputViewFlag :: Flag RawOpts+outputViewFlag = flagNone ["view"] (setboolopt "view")+ "write output to FILE, or to view.FMT in hledger's cache directory, and open it in the system's default viewer for its format (eg a web browser for html). The default format is html."++argsFlag :: FlagHelp -> Arg RawOpts+argsFlag = flagArg (\s opts -> Right $ setopt "args" s opts)++generalflagstitle :: String+generalflagstitle = "\nGeneral flags"++-- Several subsets of the standard general flags, as a single list. Old API used by some addons.+generalflagsgroup1, generalflagsgroup2, generalflagsgroup3 :: (String, [Flag RawOpts])+generalflagsgroup1 = (generalflagstitle, inputflags ++ reportflags ++ helpflags)+generalflagsgroup2 = (generalflagstitle, inputflags ++ helpflags)+generalflagsgroup3 = (generalflagstitle, helpflags)++-- Helpers to make several subsets of the standard general flags, in separate groups. The help flags are parameterised. 2024.+mkgeneralflagsgroups1, mkgeneralflagsgroups2, mkgeneralflagsgroups3 :: [Flag RawOpts] -> [(String, [Flag RawOpts])]+mkgeneralflagsgroups1 helpflags' = [+ (inputflagstitle, inputflags)+ ,(outputflagstitle, reportflags)+ ,(helpflagstitle, helpflags')+ ]+mkgeneralflagsgroups2 helpflags' = [+ (inputflagstitle, inputflags)+ ,(helpflagstitle, helpflags')+ ]+mkgeneralflagsgroups3 helpflags' = [+ (helpflagstitle, helpflags')+ ]++inputflagstitle = "\nGeneral input flags"+outputflagstitle = "\nGeneral output flags (affecting some commands)"+helpflagstitle = "\nGeneral help flags"++-- Several subsets of the standard general flags plus CLI help flags, as separate groups.+cligeneralflagsgroups1, cligeneralflagsgroups2, cligeneralflagsgroups3 :: [(String, [Flag RawOpts])]+cligeneralflagsgroups1 = mkgeneralflagsgroups1 helpflags+cligeneralflagsgroups2 = mkgeneralflagsgroups2 helpflags+cligeneralflagsgroups3 = mkgeneralflagsgroups3 helpflags+++-- cmdargs mode constructors++-- | An empty cmdargs mode to use as a template.+-- Modes describe the top-level command, ie the program, or a subcommand,+-- telling cmdargs how to parse a command line and how to+-- generate the command's usage text.+defMode :: Mode RawOpts+defMode = Mode {+ modeNames = [] -- program/command name(s)+ ,modeHelp = "" -- short help for this command+ ,modeHelpSuffix = [] -- text displayed after the usage+ ,modeGroupFlags = Group { -- description of flags accepted by the command+ groupNamed = [] -- named groups of flags+ ,groupUnnamed = [] -- ungrouped flags+ ,groupHidden = [] -- flags not displayed in the usage+ }+ ,modeArgs = ([], Nothing) -- description of arguments accepted by the command+ ,modeValue = def -- value returned when this mode is used to parse a command line+ ,modeCheck = Right -- whether the mode's value is correct+ ,modeReform = const Nothing -- function to convert the value back to a command line arguments+ ,modeExpandAt = True -- expand @ arguments for program ?+ ,modeGroupModes = toGroup [] -- sub-modes+ }++-- | A cmdargs mode suitable for a hledger built-in command+-- with the given names (primary name + optional aliases).+-- The usage message shows [QUERY] as argument.+defCommandMode :: [Name] -> Mode RawOpts+defCommandMode names = defMode {+ modeNames=names+ ,modeGroupFlags = Group {+ groupNamed = []+ ,groupUnnamed = [+ flagNone ["help"] (setboolopt "help") "show command-line help"+ ,flagNone ["man"] (setboolopt "man") "show this program's user manual with man"+ ,flagNone ["info"] (setboolopt "info") "show this program's user manual with info"+ ]+ ,groupHidden = [] -- flags not displayed in the usage+ }+ ,modeArgs = ([], Just $ argsFlag "[QUERY]")+ ,modeValue=setopt "command" (headDef "" names) def+ }++-- | A cmdargs mode representing the hledger add-on command with the+-- given name, providing hledger's common input/reporting/help flags.+-- Just used when invoking addons.+addonCommandMode :: Name -> Mode RawOpts+addonCommandMode nam = (defCommandMode [nam]) {+ modeHelp = ""+ -- XXX not needed ?+ -- fromMaybe "" $ lookup (stripAddonExtension name) [+ -- ("addon" , "dummy add-on command for testing")+ -- ,("addon2" , "dummy add-on command for testing")+ -- ,("addon3" , "dummy add-on command for testing")+ -- ,("addon4" , "dummy add-on command for testing")+ -- ,("addon5" , "dummy add-on command for testing")+ -- ,("addon6" , "dummy add-on command for testing")+ -- ,("addon7" , "dummy add-on command for testing")+ -- ,("addon8" , "dummy add-on command for testing")+ -- ,("addon9" , "dummy add-on command for testing")+ -- ]+ ,modeGroupFlags = Group {+ groupUnnamed = []+ ,groupHidden = hiddenflags+ ,groupNamed = cligeneralflagsgroups1+ }+ }++-- | A command's name, optional official abbreviation, and help preamble & postamble,+-- as a specially formatted single string. Used to generate the CLI help, and also+-- the command's doc in the hledger manual. See parseCommandHelp for the format.+type CommandHelpStr = String++-- | A command's documentation. Used both as part of CLI help, and as+-- part of the hledger manual. See parseCommandHelpStr.+data CommandHelp = CommandHelp {+ cmdName :: Name -- the official command name+ ,mcmdShortName :: Maybe Name -- optional official name abbreviation+ ,cmdHelpPreamble :: String -- help preamble, shown before flags help+ ,cmdHelpPostamble :: String -- help postamble, shown after flags help+} deriving (Show)++-- | Build a cmdarg mode for a hledger command,+-- from a help template and flag/argument specifications.+-- Reduces boilerplate a little, though the complicated cmdargs+-- flag and argument specs are still required.+hledgerCommandMode :: CommandHelpStr -> [Flag RawOpts] -> [(String, [Flag RawOpts])]+ -> [Flag RawOpts] -> ([Arg RawOpts], Maybe (Arg RawOpts)) -> Mode RawOpts+hledgerCommandMode helpstr unnamedflaggroup namedflaggroups hiddenflaggroup argsdescr =+ case parseCommandHelp helpstr of+ Nothing -> error' $ "could not parse command doc:\n"++helpstr++"\n" -- PARTIAL:+ Just CommandHelp{cmdName, mcmdShortName, cmdHelpPreamble, cmdHelpPostamble} ->+ (defCommandMode $ cmdName : maybeToList mcmdShortName) {+ modeHelp = cmdHelpPreamble+ ,modeHelpSuffix = lines cmdHelpPostamble+ ,modeGroupFlags = Group {+ groupUnnamed = unnamedflaggroup+ ,groupNamed = namedflaggroups+ ,groupHidden = hiddenflaggroup+ }+ ,modeArgs = argsdescr+ }++-- | Parse a command's embedded help text (@Somecommand.txt@).+-- That text is generated by @Shake cmdhelp@ from the command's doc source (@Somecommand.md@).+-- @Somecommand.md@ should be formatted as follows:+--+-- - First line: the command name, as a markdown heading.+--+-- - Optional third line: the command's official abbreviated name, parenthesised.+--+-- - From third or fifth line to a @```flags@ line: the command help preamble.+-- Usually one sentence or paragraph; any blank lines will not be rendered.+--+-- - A fenced code block beginning with @```flags@, containing a @Flags:@ line,+-- followed by a snapshot of the command-specific flags help as generated by cmdargs+-- or "none" if there are no command-specific flags.+-- This should contain no blank lines (no extra newlines in the cmdargs command mode help strings).+-- This is shown as-is in manuals, and regenerated at runtime for --help output.+--+-- - Any remaining lines: the command help postamble.+--+-- (Note the difference between+-- @Somecommand.md@, which is the markdown source file, and+-- @Somecommand.txt@, which is the plain text file generated by @Shake cmdhelp@,+-- which this function parses.)+--+parseCommandHelp :: CommandHelpStr -> Maybe CommandHelp+parseCommandHelp t =+ case lines t of+ [] -> Nothing+ (l1:_:l3raw:ls) -> Just $ CommandHelp cmdname (if null cmdalias then Nothing else Just cmdalias) preamble postamble+ where+ cmdname = l1+ -- pandoc's plain writer appends a trailing space after a single-character+ -- parenthetical (eg "(h) "), so strip trailing whitespace before matching.+ l3 = dropWhileEnd isSpace l3raw+ (cmdalias, rest) =+ if "(" `isPrefixOf` l3 && ")" `isSuffixOf` l3+ then (drop 1 $ init l3, ls)+ else ([], l3raw:ls)+ (preamblels, rest2) = break (== "Flags:") $ dropWhile null rest+ postamblels = dropWhile null $ dropWhile (not.null) rest2+ preamble = unlines $ reverse $ dropWhile null $ reverse preamblels+ postamble = unlines postamblels+ _ -> Nothing -- error' "misformatted command help text file"++-- | Get a mode's usage message as a nicely wrapped string.+showModeUsage :: Mode a -> String+showModeUsage =+ highlightHelp .+ (showText defaultWrap :: [Text] -> String) .+ (helpText [] HelpFormatDefault :: Mode a -> [Text])++-- | Add some ANSI decoration to cmdargs' help output.+highlightHelp+ | not useColorOnStdoutUnsafe = id -- XXX unsafe boldening help headings - seems to work, even respecting config file+ | otherwise = unlines . zipWith (curry f) [1..] . lines+ where+ f (n,l)+ | n==1 = bold l+ | isHelpHeading l = bold l+ | otherwise = l+ -- keep synced with Hledger.Cli.mainmode:+ isHelpHeading l = isAlphaNum (headDef ' ' l) && (lastDef ' ' l == ':')+ -- any s (`isPrefixOf` s) [+ -- "General input flags"+ -- ,"General reporting flags"+ -- ,"General help flags"+ -- ,"Flags"+ -- ,"General flags"+ -- ,"Examples"+ -- ]+-- | Get the most appropriate documentation topic for a mode.+-- Currently, that is either the hledger, hledger-ui or hledger-web+-- manual.+topicForMode :: Mode a -> Topic+topicForMode m+ | n == "hledger-ui" = "ui"+ | n == "hledger-web" = "web"+ | otherwise = "cli"+ where n = headDef "" $ modeNames m++-- | Add command aliases to the command's help string.+withAliases :: String -> [String] -> String+s `withAliases` [] = s+s `withAliases` as = s ++ " (" ++ intercalate ", " as ++ ")"+-- s `withAliases` (a:[]) = s ++ " (alias: " ++ a ++ ")"+-- s `withAliases` as = s ++ " (aliases: " ++ intercalate ", " as ++ ")"+++-- CliOpts++-- | Command line options, used in the @hledger@ package and above.+-- This is the \"opts\" used throughout hledger CLI code.+-- representing the options and arguments that were provided at+-- startup on the command-line.+data CliOpts = CliOpts {+ rawopts_ :: RawOpts+ ,command_ :: String+ ,file_ :: [FilePath]+ ,inputopts_ :: InputOpts+ ,reportspec_ :: ReportSpec+ ,output_file_ :: Maybe FilePath+ ,output_format_ :: Maybe String+ ,pageropt_ :: Maybe Bool -- ^ --pager+ ,coloropt_ :: Maybe YNA -- ^ --color. Controls use of ANSI color and ANSI styles.+ ,debug_ :: Int -- ^ debug level, set by @--debug[=N]@. See also 'Hledger.Utils.debugLevel'.+ ,no_new_accounts_ :: Bool -- add+ ,width_ :: Maybe String -- ^ the --width value provided, if any+ ,available_width_ :: Int -- ^ estimated usable screen width, based on+ -- 1. the width reported by the terminal, if supported+ -- 2. the default (80)+ ,progstarttime_ :: POSIXTime -- system POSIX time at start+ } deriving (Show)++instance Default CliOpts where def = defcliopts++defcliopts :: CliOpts+defcliopts = CliOpts+ { rawopts_ = def+ , command_ = ""+ , file_ = []+ , inputopts_ = definputopts+ , reportspec_ = def+ , output_file_ = Nothing+ , output_format_ = Nothing+ , pageropt_ = Nothing+ , coloropt_ = Nothing+ , debug_ = 0+ , no_new_accounts_ = False+ , width_ = Nothing+ , available_width_ = defaultWidth+ , progstarttime_ = 0+ }++-- | Default width for hledger console output, when not otherwise specified.+defaultWidth :: Int+defaultWidth = 80++-- | Replace any numeric flags (eg -2) with their long form (--depth 2),+-- as I'm guessing cmdargs doesn't support this directly.+replaceNumericFlags :: [String] -> [String]+replaceNumericFlags = map replace+ where+ replace ('-':ds) | not (null ds) && all isDigit ds = "--depth="++ds+ replace s = s++-- Convert a valueless --debug flag to one with a value.+-- See also the --debug flag definition in CliOptions.hs.+-- This makes an equals sign unnecessary with this optional-value flag.+ensureDebugFlagHasVal :: [String] -> [String]+ensureDebugFlagHasVal as = case break (=="--debug") as of+ (bs,"--debug":c:cs) | null c || not (all isDigit c) -> bs++"--debug=1" : ensureDebugFlagHasVal (c:cs)+ (bs,["--debug"]) -> bs++["--debug=1"]+ _ -> as++-- | Parse raw option string values to the desired final data types.+-- Any relative smart dates will be converted to fixed dates based on+-- today's date. Parsing failures will raise an error.+-- Also records the terminal width, if supported.+rawOptsToCliOpts :: RawOpts -> IO CliOpts+rawOptsToCliOpts rawopts = do+ currentDay <- getCurrentDay+ let+ day = case maybestringopt "today" rawopts of+ Nothing -> currentDay+ Just d -> either (const err) fromEFDay $ fixSmartDateStrEither' currentDay (T.pack d)+ where err = error' $ "Unable to parse date \"" ++ d ++ "\""+ command = stringopt "command" rawopts+ usecolor <- useColorOnStdout+ let iopts = rawOptsToInputOpts day usecolor rawopts+ rspec0 <- either error' pure $ rawOptsToReportSpec day usecolor rawopts -- PARTIAL:+ trs <- translationsForLangOption $ maybestringopt "lang" rawopts+ let rspec = rspec0{_rsReportOpts = (_rsReportOpts rspec0){translations_ = trs}}+ mtermwidth <- getTerminalWidth+ let availablewidth = fromMaybe defaultWidth mtermwidth+ return defcliopts {+ rawopts_ = rawopts+ ,command_ = command+ ,file_ = listofstringopt "file" rawopts+ ,inputopts_ = iopts+ ,reportspec_ = rspec+ ,output_file_ = maybestringopt "output-file" rawopts+ ,output_format_ = maybestringopt "output-format" rawopts+ ,pageropt_ = maybeynopt "pager" rawopts+ ,coloropt_ = maybeynaopt "color" rawopts+ ,debug_ = posintopt "debug" rawopts+ ,no_new_accounts_ = boolopt "no-new-accounts" rawopts -- add+ ,width_ = maybestringopt "width" rawopts+ ,available_width_ = availablewidth+ }++-- | The names of the general flags that run/repl propagate to the commands they run:+-- all input, output/report, and terminal flags. Excludes --file (handled separately, as+-- the default journal) and the help-action flags (which just show help and exit).+propagatedGeneralFlagNames :: [String]+propagatedGeneralFlagNames =+ filter (`notElem` (["file","f"] ++ helpactionflags))+ $ concatMap flagNames (inputflags ++ reportflags ++ helpflags)+ where helpactionflags = ["quickref","help","h","examples","info","man","webman","version","test","write-lang"]++-- | Extract the propagated general flags from these raw options, as a raw option+-- association list, for passing to run/repl subcommands.+generalRawOpts :: RawOpts -> [(String,String)]+generalRawOpts = collectopts $ \kv ->+ if fst kv `elem` propagatedGeneralFlagNames then Just kv else Nothing++-- | Prepend some extra raw options into a subcommand's options, as defaults that+-- the subcommand's own options take precedence over, recomputing the derived+-- CliOpts fields (inputopts_, file_, reportspec_..) so they stay consistent.+insertRawOpts :: [(String,String)] -> CliOpts -> IO CliOpts+insertRawOpts extraopts subopts = rawOptsToCliOpts $ overRawOpts (extraopts ++) (rawopts_ subopts)++-- | Drop the arguments ("args") from this CliOpts' rawopts field.+cliOptsDropArgs :: CliOpts -> CliOpts+cliOptsDropArgs copts@CliOpts{rawopts_} = copts{rawopts_ = dropRawOpt "args" rawopts_}++-- | Builtin commands that can operate on a nonexistent journal file, creating it+-- (add and import). These are dispatched specially, both at the CLI and in run/repl,+-- so a missing journal file is tolerated rather than an error.+journalCreatingCommandNames :: [String]+journalCreatingCommandNames = ["add","import"]++-- | Names of builtin commands which do not read the journal at all.+-- These are dispatched specially, both at the CLI and in run/repl, so they+-- never read or check the journal (help is handled by the CLI's help hub,+-- which also does not read the journal).+journalIgnoringCommandNames :: [String]+journalIgnoringCommandNames = ["help","init","setup"]++-- | The name of a hidden marker flag used internally by the run command to+-- recognise inline commands. run reads inline commands (rather than command+-- files) when its arguments contain a "--". But cmdargs consumes the first "--"+-- while parsing, so run can't detect it directly. Instead, before parsing we+-- insert this marker flag just before the first "--" (with 'argsMarkRunCommands');+-- cmdargs then parses it like any normal flag, leaving it in the options for run+-- to check. This replaces an older, more fragile workaround which duplicated the+-- first "--" so that one copy survived cmdargs.+runCommandsMarker :: String+runCommandsMarker = "_runcommands"++-- | If these arguments contain a "--" (run's inline-commands introducer), insert+-- the hidden 'runCommandsMarker' flag just before it, so the run command can tell+-- it was given inline commands rather than command files. See 'runCommandsMarker'.+argsMarkRunCommands :: [String] -> [String]+argsMarkRunCommands args'+ | "--" `elem` args' = let (as,bs) = break (=="--") args' in as <> ["--" <> runCommandsMarker] <> bs+ | otherwise = args'++-- | A helper for addon commands: this parses options and arguments from+-- the current command line using the given hledger-style cmdargs mode,+-- and returns a CliOpts. Or, with --help or -h present, it shows+-- the full help (in the pager if appropriate) and exits the program.+-- When --debug is present, also prints some debug output.+-- Note this is not used by the main hledger executable.+--+-- The full help is generated from the mode: the full usage description+-- generated by cmdargs (including all supported options), framed by whatever+-- pre- and postamble text the mode specifies. It's intended that this forms a+-- complete help document or manual. It's the same help shown by CMD -h at the+-- command line, keeping -h consistent everywhere (including in the repl).+--+-- Tips:+-- Empty lines in the pre/postamble are removed by cmdargs;+-- add a space character to preserve them.+--+getHledgerCliOpts' :: Mode RawOpts -> [String] -> IO CliOpts+getHledgerCliOpts' mode' args0 = do+ let rawopts = either usageError id $ process mode' args0+ opts <- rawOptsToCliOpts rawopts+ debugArgs args0 opts+ when (boolopt "help" $ rawopts_ opts) $ runPager longhelp >> exitSuccess+ return opts+ where+ longhelp = showModeUsage mode'+ -- A truncated help (preamble and usage up to the first "flags:" line, plus a+ -- pointer to the common options) was shown here before; disabled for now to+ -- keep -h showing the full help everywhere. To restore it, show this instead:+ -- shorthelp =+ -- unlines $+ -- (reverse $ dropWhile null $ reverse $ takeWhile (not . ("flags:" `isInfixOf`)) $ lines longhelp)+ -- ++ ["", " See also hledger -h for general hledger options."]+ -- | Print debug info about arguments and options if --debug is present.+ -- XXX use standard dbg helpers+ debugArgs :: [String] -> CliOpts -> IO ()+ debugArgs args1 opts =+ when ("--debug" `elem` args1) $ do+ progname' <- getProgName+ putStrLn $ "running: " ++ progname'+ putStrLn $ "raw args: " ++ show args1+ putStrLn $ "processed opts:\n" ++ show opts+ putStrLn $ "search query: " ++ show (_rsQuery $ reportspec_ opts)++getHledgerCliOpts :: Mode RawOpts -> IO CliOpts+getHledgerCliOpts mode' = do+ args' <- getArgs >>= expandArgsAt+ getHledgerCliOpts' mode' args'++-- CliOpts accessors++-- | Get the (tilde-expanded, absolute) journal file path from+-- 1. options, 2. an environment variable, or 3. the default.+-- Actually, returns one or more file paths. There will be more+-- than one if multiple -f options were provided.+-- File paths can have a READER: prefix naming a reader/data format.+journalFilePathFromOpts :: CliOpts -> IO (NE.NonEmpty String)+journalFilePathFromOpts opts = do+ mbpaths <- journalFilePathFromOptsNoDefault opts+ case mbpaths of+ Just paths -> return paths+ Nothing -> do+ f <- defaultExistingJournalPath+ return $ NE.fromList [f]++-- | Like journalFilePathFromOpts, but does not use defaultJournalPath+journalFilePathFromOptsNoDefault :: CliOpts -> IO (Maybe (NE.NonEmpty String))+journalFilePathFromOptsNoDefault opts = do+ d <- getCurrentDirectory+ case NE.nonEmpty $ file_ opts of+ Nothing -> return Nothing+ Just paths -> Just <$> mapM (expandPathPreservingPrefix d) paths++expandPathPreservingPrefix :: FilePath -> PrefixedFilePath -> IO PrefixedFilePath+expandPathPreservingPrefix d prefixedf = do+ let (p,f) = splitReaderPrefix prefixedf+ f' <- expandPathOrGlob d f+ return $ case p of+ Just p' -> (show p') ++ ":" ++ f'+ Nothing -> f'++-- | Get the expanded, absolute output file path specified by an+-- -o/--output-file options, or nothing, meaning stdout (also when the path is "-").+outputFileFromOpts :: CliOpts -> IO (Maybe FilePath)+outputFileFromOpts opts = do+ d <- getCurrentDirectory+ case output_file_ opts of+ Nothing -> return Nothing+ Just "-" -> return Nothing+ Just f -> Just <$> expandPath d f++defaultOutputFormat :: String+defaultOutputFormat = "txt"++-- | All the output formats known by any command, for outputFormatFromOpts.+-- To automatically infer it from -o/--output-file, it needs to be listed here.+outputFormats :: [String]+outputFormats = [defaultOutputFormat, "beancount", "csv", "json", "html", "ledger", "sql", "tsv", "fods", "svg"]++-- | Get the output format from the --output-format option,+-- otherwise from a recognised file extension in the --output-file option,+-- otherwise the default (txt).+outputFormatFromOpts :: CliOpts -> String+outputFormatFromOpts opts =+ case output_format_ opts of+ Just f -> f+ Nothing ->+ case filePathExtension <$> output_file_ opts of+ Just ext | ext `elem` outputFormats -> ext+ _ | viewRequested opts -> "html"+ _ -> defaultOutputFormat++-- | Was --view used, to show the output in the system's default viewer ?+viewRequested :: CliOpts -> Bool+viewRequested = boolopt "view" . rawopts_++-- -- | Get the file name without its last extension, from a file path.+-- filePathBaseFileName :: FilePath -> String+-- filePathBaseFileName = fst . splitExtension . snd . splitFileName++-- | Get the last file extension, without the dot, from a file path.+-- May return the null string.+filePathExtension :: FilePath -> String+filePathExtension = dropWhile (=='.') . snd . splitExtension . snd . splitFileName++-- | Get the (tilde-expanded) rules file path from options, if any.+rulesFilePathFromOpts :: CliOpts -> IO (Maybe FilePath)+rulesFilePathFromOpts opts = do+ d <- getCurrentDirectory+ maybe (return Nothing) (fmap Just . expandPath d) $ mrules_file_ $ inputopts_ opts++-- | Get the width in characters to use for the register command's console output,+-- and also the description column width if specified (following the main width, comma-separated).+-- The widths will be as follows:+-- @+-- no --width flag - overall width is the available width (or terminal width, or 80); description width is unspecified (auto)+-- --width W - overall width is W, description width is auto+-- --width W,D - overall width is W, description width is D+-- @+-- Will raise a parse error for a malformed --width argument.+registerWidthsFromOpts :: CliOpts -> (Int, Maybe Int)+registerWidthsFromOpts CliOpts{width_=Nothing, available_width_=w} = (w, Nothing)+registerWidthsFromOpts CliOpts{width_=Just s} =+ case runParser registerwidthp "(unknown)" s of+ Left e -> usageError $ "could not parse width option: "++errorBundlePretty e+ Right ws -> ws+ where+ registerwidthp :: (Stream s, Char ~ Token s) => ParsecT Void s m (Int, Maybe Int)+ registerwidthp = do+ totalwidth <- read `fmap` some digitChar+ descwidth <- optional (char ',' >> read `fmap` some digitChar)+ eof+ return (totalwidth, descwidth)++-- Some common ways to select items from a list of declarable things.+-- Used by the accounts, commodities, payees, tags commands, eg.+data DeclarablesSelector+ = Used+ | Declared+ | Undeclared+ | Unused+ | FindFirst -- ^ the first item matched by the first argument (--find)+ deriving (Show, Eq)++-- Get the flag of this kind from opts, or raise an error if there's more than one.+declarablesSelectorFromOpts :: CliOpts -> Maybe DeclarablesSelector+declarablesSelectorFromOpts CliOpts{rawopts_=rawopts} =+ case ( boolopt "used" rawopts+ , boolopt "declared" rawopts+ , boolopt "undeclared" rawopts+ , boolopt "unused" rawopts+ , boolopt "find" rawopts+ ) of+ (False, False, False, False, False) -> Nothing+ (True, False, False, False, False) -> Just Used+ (False, True, False, False, False) -> Just Declared+ (False, False, True, False, False) -> Just Undeclared+ (False, False, False, True, False) -> Just Unused+ (False, False, False, False, True ) -> Just FindFirst+ _ -> error' "please pick at most one of --used, --declared, --undeclared, --unused, --find"++-- | A helper for the --find mode offered by commands like accounts, commodities, payees, tags (see also 'DeclarablesSelector').+-- Interpret the first command argument found in rawopts as a case insensitive regular expression,+-- then return the first of the provided items that it matches;+-- or raise an error if there's no valid argument or no matched item.+-- This function's second argument describes the items' type, for the error message.+findMatchedByArgument :: RawOpts -> String -> [T.Text] -> T.Text+findMatchedByArgument rawopts itemtype items =+ let+ arg = headDef err $ listofstringopt "args" rawopts+ where err = error' $ "With --find, please provide a " ++ itemtype ++ " name or\n" +++ itemtype ++ " pattern (case-insensitive, infix, regexp) as first command argument."+ firstmatch = case toRegexCI $ T.pack arg of -- keep synced with aregister's matching+ Right re -> find (regexMatchText re)+ Left _ -> const Nothing+ in firstmatch items+ & fromMaybe (error' $ show arg ++ " did not match any " ++ itemtype ++ ".")++-- Other utils++-- None of https://hackage.haskell.org/package/directory-1.3.8.1/docs/System-Directory.html#g:5+-- do quite what we need (find all the executables in PATH with a filename prefix).+-- | Get all sorted unique filenames in the current user's PATH.+-- We do not currently filter out non-file objects or files without execute permission.+likelyExecutablesInPath :: IO [String]+likelyExecutablesInPath = do+ pathdirs <- splitOn pathsep `fmap` getEnvSafe "PATH"+ pathfiles <- concat `fmap` mapM getDirectoryContentsSafe pathdirs+ return $ nubSort pathfiles+ where pathsep = if os == "mingw32" then ";" else ":"+--+-- Exclude directories and files without execute permission:+-- this would do a stat for each hledger-* file found, which is probably ok.+-- But it needs file paths, not just file names.+--+-- exes' <- filterM doesFileExist exe'+-- exes'' <- filterM isExecutable exes'+-- return exes''+-- where isExecutable f = getPermissions f >>= (return . executable)++getEnvSafe :: String -> IO String+getEnvSafe v = getEnv v `C.catch` (\(_::C.IOException) -> return "") -- XXX should catch only isDoesNotExistError e++getDirectoryContentsSafe :: FilePath -> IO [String]+getDirectoryContentsSafe d =+ (filter (not . (`elem` [".",".."])) `fmap` getDirectoryContents d) `C.catch` (\(_::C.IOException) -> return [])++-- ** Lenses++makeHledgerClassyLenses ''CliOpts++instance HasInputOpts CliOpts where+ inputOpts = inputopts++instance HasBalancingOpts CliOpts where+ balancingOpts = inputOpts.balancingOpts++instance HasReportSpec CliOpts where+ reportSpec = reportspec++instance HasReportOptsNoUpdate CliOpts where+ reportOptsNoUpdate = reportSpec.reportOptsNoUpdate++instance HasReportOpts CliOpts where+ reportOpts = reportSpec.reportOpts+
+ Hledger/Cli/Commands.hs view
@@ -0,0 +1,940 @@+{-|+hledger's built-in commands, and helpers for printing the commands list.++New built-in commands should be added in four places below:+the export list, the import list, builtinCommands, commandsListSections.++-}++-- Note: commands list rendering is intensely sensitive to change,+-- very easy to break in ways that tests currently do not catch.++{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands (+ commands+ ,mainmode+ ,runUnitTests+ ,builtinCommands+ ,builtinCommandNames+ ,addonCommandNames+ ,knownAddonCommandNames+ ,findBuiltinCommand+ ,knownCommands+ ,CommandCategories(..)+ ,commandCategories+ ,printCommandsList+ ,tests_Hledger_Cli+ ,module Hledger.Cli.Commands.Accounts+ ,module Hledger.Cli.Commands.Activity+ ,module Hledger.Cli.Commands.Add+ ,module Hledger.Cli.Commands.Aregister+ ,module Hledger.Cli.Commands.Balance+ ,module Hledger.Cli.Commands.Balancesheet+ ,module Hledger.Cli.Commands.Balancesheetequity+ ,module Hledger.Cli.Commands.Cashflow+ ,module Hledger.Cli.Commands.Check+ ,module Hledger.Cli.Commands.Close+ ,module Hledger.Cli.Commands.Codes+ ,module Hledger.Cli.Commands.Commodities+ ,module Hledger.Cli.Commands.Descriptions+ ,module Hledger.Cli.Commands.Diff+ ,module Hledger.Cli.Commands.Files+ ,module Hledger.Cli.Commands.Get+ ,module Hledger.Cli.Commands.Help+ ,module Hledger.Cli.Commands.Holdings+ ,module Hledger.Cli.Commands.Import+ ,module Hledger.Cli.Commands.Incomestatement+ ,module Hledger.Cli.Commands.Init+ ,module Hledger.Cli.Commands.Notes+ ,module Hledger.Cli.Commands.Payees+ ,module Hledger.Cli.Commands.Prices+ ,module Hledger.Cli.Commands.Print+ ,module Hledger.Cli.Commands.Register+ ,module Hledger.Cli.Commands.Rewrite+ ,module Hledger.Cli.Commands.Roi+ ,module Hledger.Cli.Commands.Run+ ,module Hledger.Cli.Commands.Setup+ ,module Hledger.Cli.Commands.Stats+ ,module Hledger.Cli.Commands.Tags+ ,module Hledger.Cli.Commands.Transactions+) +where++import Data.Char (isSpace, toLower)+import Data.Either (isRight)+import Data.List+import Data.List.Extra (groupSortOn, nubOrdOn, nubSort)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Time.Calendar+import Safe (headErr, headMay, maximumDef)+import System.Console.CmdArgs.Explicit as C+import System.Environment (withArgs)+import System.FilePath (dropExtension, takeBaseName, takeExtension)+import Test.Tasty (defaultMain)+import Text.Megaparsec+import Text.Megaparsec.Char++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Conf (CommandAlias, CommandLine, confAliases, getConf')+import Hledger.Cli.Commands.Accounts+import Hledger.Cli.Commands.Activity+import Hledger.Cli.Commands.Add+import Hledger.Cli.Commands.Aregister+import Hledger.Cli.Commands.Balance+import Hledger.Cli.Commands.Balancesheet+import Hledger.Cli.Commands.Balancesheetequity+import Hledger.Cli.Commands.Cashflow+import Hledger.Cli.Commands.Check+import Hledger.Cli.Commands.Close+import Hledger.Cli.Commands.Codes+import Hledger.Cli.Commands.Commodities+import Hledger.Cli.Commands.Descriptions+import Hledger.Cli.Commands.Diff+import Hledger.Cli.Commands.Files+import Hledger.Cli.Commands.Get+import Hledger.Cli.Commands.Help+import Hledger.Cli.Commands.Holdings+import Hledger.Cli.Commands.Import+import Hledger.Cli.Commands.Incomestatement+import Hledger.Cli.Commands.Init+import Hledger.Cli.Commands.Notes+import Hledger.Cli.Commands.Payees+import Hledger.Cli.Commands.Prices+import Hledger.Cli.Commands.Print+import Hledger.Cli.Commands.Register+import Hledger.Cli.Commands.Rewrite+import Hledger.Cli.Commands.Roi+import Hledger.Cli.Commands.Run+import Hledger.Cli.Commands.Setup+import Hledger.Cli.Commands.Stats+import Hledger.Cli.Commands.Tags+import Hledger.Cli.Commands.Transactions+import Hledger.Cli.Utils (tests_Cli_Utils, openBrowserOn)+import Hledger.Cli.Commands.Quickref (showQuickref)+import Hledger.Cli.DocFiles (runTldrForPage)+import Data.Functor ((<&>), void)++-- | The cmdargs subcommand mode (for command-line parsing)+-- and IO action (for doing the command's work) for each builtin command.+-- Command actions take parsed CLI options and a (lazy) finalised journal.+builtinCommands :: [(Mode RawOpts, CliOpts -> Journal -> IO ())]+builtinCommands = [+ (accountsmode , accounts)+ ,(activitymode , activity)+ ,(addmode , add)+ ,(aregistermode , aregister)+ ,(balancemode , balance)+ ,(balancesheetequitymode , balancesheetequity)+ ,(balancesheetmode , balancesheet)+ ,(cashflowmode , cashflow)+ ,(checkmode , check)+ ,(closemode , close)+ ,(codesmode , codes)+ ,(commoditiesmode , commodities)+ ,(descriptionsmode , descriptions)+ ,(diffmode , diff)+ ,(filesmode , files)+ ,(getmode , getcmd)+ ,(helpmode , help)+ ,(holdingsmode , holdings)+ ,(importmode , importcmd)+ ,(incomestatementmode , incomestatement)+ ,(initmode , initcmd)+ ,(notesmode , notes)+ ,(payeesmode , payees)+ ,(pricesmode , prices)+ ,(printmode , print')+ ,(registermode , register)+ ,(rewritemode , rewrite)+ ,(roimode , roi)+ ,(runmode , runOrReplStub)+ ,(replmode , runOrReplStub)+ ,(setupmode , setup)+ ,(statsmode , stats)+ ,(tagsmode , tags)+ ,(transactionsmode , transactions)+ ]++-- | The overall cmdargs mode describing hledger's command-line options and subcommands.+-- The names of known addons are provided so they too can be recognised as commands.+mainmode addons = defMode {+ modeNames = [progname ++ " [COMMAND]"]+ ,modeArgs = ([], Just $ argsFlag "[ARGS]")+ ,modeHelp = unlines ["hledger's main command line interface. Run with no ARGS to see a quick reference, or `hledger help commands` to list commands."]+ ,modeGroupModes = Group {+ -- subcommands in the unnamed group, shown first:+ groupUnnamed = [+ ]+ -- subcommands in named groups:+ ,groupNamed = [+ ]+ -- subcommands handled but not shown in the help:+ ,groupHidden = map fst builtinCommands ++ map addonCommandMode addons+ }+ ,modeGroupFlags = Group {+ -- flags in named groups: (keep synced with Hledger.Cli.CliOptions.highlightHelp)+ groupNamed = cligeneralflagsgroups1+ -- flags in the unnamed group, shown last: (keep synced with dropUnsupportedOpts)+ ,groupUnnamed = confflags+ -- other flags handled but not shown in help:+ ,groupHidden = hiddenflagsformainmode+ }+ ,modeHelpSuffix = []+ }++-- | The help command: show some part of hledger's documentation, dispatching on+-- its first argument to a subtopic. Recognised subtopics are: quickref (the quick+-- reference card), commands (the commands list), usage [CMD] (command-line usage,+-- general or for CMD), manual [TOPIC] (the manual, optionally at TOPIC),+-- examples [CMD..] (brief tldr examples), and home/install/relnotes/docs/support/sponsor+-- (open the corresponding hledger.org page in a web browser).+-- With no argument it shows the quickref card; any other first argument is+-- treated as a manual topic.+help :: CliOpts -> Journal -> IO ()+help opts _+ -- With -l, always list matching manual topics, bypassing the special+ -- subcommands (commands, usage, examples, install, etc). A leading "manual"+ -- argument is the (now implicit) subcommand name, so it's consumed rather than+ -- treated as a topic; thus `help -l manual` behaves like `help manual -l`.+ | boolopt "help-l" (rawopts_ opts) = manual opts $ headMay $ case args of+ "manual":rest -> rest+ _ -> args+ | otherwise = case args of+ [] -> showQuickref+ "quickref":_ -> showQuickref+ "commands":_ -> commands opts nulljournal+ "usage":rest ->+ let usagemode = case rest of+ c:_ | Just (m,_) <- findBuiltinCommand c -> m+ _ -> mainmode []+ in runPager $ showModeUsage usagemode ++ "\n"+ "manual":rest -> manual opts (headMay rest)+ "examples":rest -> mapM_ runTldrForPage $+ if null rest then ["hledger"] else map ("hledger-"<>) rest+ "home":_ -> void $ openBrowserOn "https://hledger.org"+ "install":_ -> void $ openBrowserOn "https://hledger.org/install.html"+ "relnotes":_ -> void $ openBrowserOn "https://hledger.org/relnotes.html"+ "docs":_ -> void $ openBrowserOn "https://hledger.org/doc.html"+ "support":_ -> void $ openBrowserOn "https://hledger.org/support.html"+ "sponsor":_ -> void $ openBrowserOn "https://hledger.org/sponsor.html"+ _ -> manual opts (headMay args)+ where+ args = listofstringopt "args" (rawopts_ opts)++-- figlet -f FONTNAME hledger, then escape backslashes+_banner_slant = drop 1 [""+ -----------------------------------------80-------------------------------------+ ," __ __ __ "+ ," / /_ / /__ ____/ /___ ____ _____"+ ," / __ \\/ / _ \\/ __ / __ `/ _ \\/ ___/"+ ," / / / / / __/ /_/ / /_/ / __/ / "+ ,"/_/ /_/_/\\___/\\__,_/\\__, /\\___/_/ "+ ," /____/ "+ ]++_banner_smslant = drop 1 [""+ ," __ __ __ "+ ," / / / /__ ___/ /__ ____ ____"+ ," / _ \\/ / -_) _ / _ `/ -_) __/"+ ,"/_//_/_/\\__/\\_,_/\\_, /\\__/_/ "+ ," /___/ "+ ]++_banner_speed = drop 1 [""+ ,"______ ______ _________ "+ ,"___ /____ /__________ /______ _____________"+ ,"__ __ \\_ /_ _ \\ __ /__ __ `/ _ \\_ ___/"+ ,"_ / / / / / __/ /_/ / _ /_/ // __/ / "+ ,"/_/ /_//_/ \\___/\\__,_/ _\\__, / \\___//_/ "+ ," /____/ "+ ]++-- accent and gradientStr, used for the commands list and REPL banners, are in Hledger.Utils.IO.++-- | The three categories of command which the commands list can show:+-- the commands built in to hledger, the addon commands installed in PATH,+-- and the command aliases defined in the config file.+data CommandCategories = CommandCategories {+ showbuiltins_ :: Bool+ ,showaddons_ :: Bool+ ,showaliases_ :: Bool+ }++-- | Which command categories are selected by the --builtins, --addons and+-- --aliases flags in these options. Each of those flags limits the commands+-- list to one category; with none of them, all categories are shown.+commandCategories :: RawOpts -> CommandCategories+commandCategories rawopts+ | not (builtins || addons || cmdaliases) = CommandCategories True True True+ | otherwise = CommandCategories builtins addons cmdaliases+ where+ builtins = boolopt "builtins" rawopts+ addons = boolopt "addons" rawopts+ cmdaliases = boolopt "aliases" rawopts++-- | The builtin and known addon commands, with their standard abbreviation and+-- short description, in the sections and order in which the commands list shows them.+-- Each command line has the format+--+-- COMMAND (ABBREV) DESCRIPTION+--+-- prefixed with a space for a builtin command, or a + for a known addon command+-- (which is shown only when hledger-COMMAND is found in $PATH at runtime).+-- Each section is sorted alphabetically, except that setup comes first in MAINTENANCE.+--+-- Keep synced with builtinCommands above, the command docs (Commands/\*.md),+-- commands.m4, and hledger.m4.md -> Commands.+--+-- TODO: generate more of this automatically.+--+commandsListSections :: [(String, [String])]+commandsListSections = [+ -----------------------------------------80-------------------------------------+ ("USER INTERFACES",+ [" help (h) show documentation and examples"+ ," repl run multiple commands from an interactive prompt"+ ," run run multiple commands from a file or command line"+ ,"+ui run a terminal UI"+ ,"+web run a web UI"+ ])+ -----------------------------------------80-------------------------------------+ ,("ENTERING DATA",+ [" add add transactions using terminal prompts"+ ," get fetch transaction and price data for import"+ ,"+iadd add transactions using a TUI (hledger-iadd)"+ ," import add new transactions from other files, eg CSV files"+ ])+ -----------------------------------------80-------------------------------------+ ,("REPORTS",+ [" accounts (acc) account names"+ ," activity transaction or posting counts, as a bar chart"+ ," aregister (areg) an account's transactions & running balance"+ ," balance (bal) balance changes, end balances, gains, budgets & more"+ ," balancesheet (bs) assets, liabilities and net worth"+ ," balancesheetequity (bse) assets, liabilities and equity"+ ,"+bar simple balance/change bar charts for hledger 1" -- hledger-bar+ ," cashflow (cf) changes in liquid assets"+ ," codes transaction codes"+ ," commodities (comm) commodity/currency symbols"+ ," descriptions (desc) transaction descriptions"+ ," files input files used"+ ," holdings investment holdings and performance"+ ," incomestatement (is) revenues and expenses"+ ," notes the note part of transaction descriptions"+ ," payees the payee part of transaction descriptions"+ ,"+plot advanced matplotlib charts, as gui/svg/png/pdf" -- hledger-utils+ ," prices market prices"+ ," print transaction entries, or a whole exported journal"+ ," register (reg) matched postings & running total, across accounts"+ ," roi return on investments"+ ," stats journal statistics"+ ," tags tag names"+ ," transactions (tx) transactions, in compact one-line format"+ ])+ -----------------------------------------80-------------------------------------+ ,("MAINTENANCE",+ [" setup check your hledger installation"+ ," init create starter journal files"+ ," check check that your journal is valid"+ ,"+check-tagfiles check that files referenced in tag values exist" -- hledger-check-tagfiles+ ," diff compare an account's transactions in two journals"+ ,"+edit edit matched transactions with $EDITOR" -- hledger-utils+ ,"+git simple version control of the journal with git" -- hledger-git+ ,"+jj simple version control of the journal with jj" -- hledger-jj+ ])+ -----------------------------------------80-------------------------------------+ ,("GENERATING DATA",+ [" close generate transactions to zero/restore/assert balances"+ ,"+interest generate transactions transferring accrued interest" -- hledger-interest+ ," rewrite generate postings by rule, like print --auto"+ ])+ -----------------------------------------80-------------------------------------+ ]++-- | The canonical command names in the sections above, in the order they occur.+-- With a true argument, only the known addon command names.+commandsListCommandNames :: Bool -> [String]+commandsListCommandNames addonsonly =+ [ cmdname+ | (_, cmds) <- commandsListSections+ , prefixchar:cmd <- cmds+ , prefixchar `elem` '+':[' '|not addonsonly]+ , cmdname:_ <- [words cmd]+ ]++-- | Render the commands list, showing the selected categories of command:+-- the builtin commands and installed known addon commands from the sections above,+-- then the other installed addons, then the config file's command aliases.+-- A section with no commands to show is omitted.+commandsList :: CommandCategories -> [String] -> [(CommandAlias,CommandLine)] -> [String]+commandsList cats installedaddons cmdaliases =+ -- A one-line title heading, in the quickref style.+ titleLine "HLEDGER COMMANDS"+ : concatMap rendersection commandsListSections+ ++ otheraddonssection+ ++ aliasessection+ where+ rendersection (heading, cmds) = case concatMap selectcommand cmds of+ [] -> []+ cmds' -> bold' heading : cmds'++ -- Keep a command line only if it is in a selected category, replacing the+ -- category prefix with a space; a known addon must also be installed.+ selectcommand (prefixchar:cmd) = case prefixchar of+ ' ' | showbuiltins_ cats -> [' ':cmd]+ '+' | showaddons_ cats, isinstalled cmdname -> [' ':cmd]+ _ -> []+ where cmdname = takeWhile (not.isSpace) cmd+ selectcommand [] = []++ isinstalled cmdname+ | cmdname `elem` installedaddons = True+ | otherwise = dbg9With (const $ "hiding uninstalled addon: " <> cmdname) False++ -- The installed addons which have no slot above, listed in columns.+ -- The heading is always shown, since this is the catch-all addons section.+ otheraddonssection+ | not $ showaddons_ cats = []+ | otherwise = bold' "OTHER ADDONS" : map (' ':) (lines $ multicol 79 otheraddons)+ where otheraddons = installedaddons \\ knownAddonCommandNames++ -- The command aliases (custom commands) defined in the config file, if any.+ aliasessection+ | not (showaliases_ cats) || null cmdaliases = []+ | otherwise = bold' "ALIASES" :+ [" " <> padright aliasw a <> " = " <> def | (a,def) <- cmdaliases]+ where+ aliasw = maximumDef 0 $ map (length.fst) cmdaliases+ padright w s = s <> replicate (w - length s) ' '++-- | Display the commands list, limited to the categories selected by+-- --builtins/--addons/--aliases. Only the selected categories are looked up:+-- the addons in PATH, and the command aliases in the config file.+commands :: CliOpts -> Journal -> IO ()+commands opts _ = do+ installedaddons <- if showaddons_ cats then addonCommandNames else return []+ cmdaliases <-+ if not $ showaliases_ cats then return [] else do+ (conf,_) <- getConf' $ rawopts_ opts+ -- show each alias's effective (last) definition+ return $ reverse $ nubOrdOn fst $ reverse $ confAliases conf+ printCommandsList cats installedaddons cmdaliases+ where+ cats = commandCategories $ rawopts_ opts++{- | Print the commands list, with a pager if appropriate:+the selected categories of command, customised with the addons+installed in PATH and the command aliases defined in the config file.+-}+printCommandsList :: CommandCategories -> [String] -> [(CommandAlias,CommandLine)] -> IO ()+printCommandsList cats installedaddons cmdaliases =+ seq (length $ dbg8 "uninstalledknownaddons" $ knownaddons \\ installedaddons) $ -- for debug output+ seq (length $ dbg8 "installedknownaddons" $ knownaddons `intersect` installedaddons) $+ seq (length $ dbg8 "installedunknownaddons" $ installedaddons \\ knownaddons) $+ runPager $ unlines $ commandsList cats installedaddons cmdaliases+ where+ knownaddons = knownAddonCommandNames++-- | Canonical names of all commands which have a slot in the commands list, in alphabetical order.+-- These include the builtin commands and the known addon commands.+knownCommands :: [String]+knownCommands = nubSort $ commandsListCommandNames False++-- | All names and aliases of the builtin commands.+builtinCommandNames :: [String]+builtinCommandNames = concatMap (modeNames . fst) builtinCommands++-- | Look up a builtin command's mode and action by exact command name or alias.+findBuiltinCommand :: String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ()) +findBuiltinCommand cmdname = find (elem cmdname . modeNames . fst) builtinCommands ++{- | Canonical names of the known addon commands which have a slot in the commands list,+in alphabetical order.+-}+knownAddonCommandNames :: [String]+knownAddonCommandNames = nubSort $ commandsListCommandNames True++-- Search PATH for names of addon commands, that aren't shadowed by builtin commands.+addonCommandNames :: IO [String]+addonCommandNames = installedAddonCommandNames <&> filter (not . (`elem` builtinCommandNames) . dropExtension)++-- | Get the sorted unique canonical names of hledger addon commands+-- found in the current user's PATH. These are used in command line+-- parsing and to display the commands list.+--+-- Canonical addon names are the filenames of hledger-* executables in+-- PATH, without the "hledger-" prefix, and without the file extension+-- except when it's needed for disambiguation (see below).+--+-- When there are exactly two versions of an executable (same base+-- name, different extensions) that look like a source and compiled+-- pair (one has .exe, .com, or no extension), the source version will+-- be excluded (even if it happens to be newer). When there are three+-- or more versions (or two versions that don't look like a+-- source/compiled pair), they are all included, with file extensions+-- intact.+--+installedAddonCommandNames :: IO [String]+installedAddonCommandNames = do+ -- past bug generator+ as1 <- hledgerExecutablesInPath -- ["hledger-check","hledger-check-dates","hledger-check-dates.hs","hledger-check.hs","hledger-check.py"]+ let as2 = map stripPrognamePrefix as1 -- ["check","check-dates","check-dates.hs","check.hs","check.py"]+ let as3 = groupSortOn takeBaseName as2 -- [["check","check.hs","check.py"],["check-dates","check-dates.hs"]]+ let as4 = concatMap dropRedundantSourceVersion as3 -- ["check","check.hs","check.py","check-dates"]+ return as4++stripPrognamePrefix = drop (length progname + 1)++dropRedundantSourceVersion [f,g]+ | map toLower (takeExtension f) `elem` compiledExts = [f]+ | map toLower (takeExtension g) `elem` compiledExts = [g]+dropRedundantSourceVersion fs = fs++compiledExts = ["",".com",".exe"]++-- | Get the sorted unique filenames of all hledger-* executables in+-- the current user's PATH. These are files in any of the PATH directories,+-- named hledger-*, with either no extension (and no periods in the name)+-- or one of the addonExtensions.+-- We do not currently filter out non-file objects or files without execute permission.+hledgerExecutablesInPath :: IO [String]+hledgerExecutablesInPath = filter isHledgerExeName <$> likelyExecutablesInPath++isHledgerExeName :: String -> Bool+isHledgerExeName = isRight . parsewith hledgerexenamep . T.pack+ where+ hledgerexenamep = do+ _ <- string $ T.pack progname+ _ <- char '-'+ _ <- some $ noneOf ['.']+ optional (string "." >> choice' (map (string . T.pack) addonExtensions))+ eof++-- stripAddonExtension :: String -> String+-- stripAddonExtension = regexReplace re "" where re = "\\.(" ++ intercalate "|" addonExtensions ++ ")$"++addonExtensions :: [String]+addonExtensions =+ ["bat"+ ,"com"+ ,"exe"+ ,"hs"+ ,"js"+ ,"lhs"+ ,"lua"+ ,"php"+ ,"pl"+ ,"py"+ ,"rb"+ ,"rkt"+ ,"sh"+ ,"osh"+ ,"ysh"+ ]++-- | Run the hledger and hledger-lib packages' unit tests (for --test),+-- or just those whose names match the given tasty pattern, if it is non-empty.+-- Defined here for easy access to other modules' tests.+-- They run in a single thread: they take only milliseconds, and running them in parallel+-- occasionally crashes or hangs on aarch64 macOS, apparently from a GHC runtime bug+-- (seen with GHC 9.12 and 9.14; https://gitlab.haskell.org/ghc/ghc/-/issues/28001).+runUnitTests :: String -> IO ()+runUnitTests pat =+ withArgs ("--num-threads=1" : ["--pattern=" <> pat | not $ null pat]) $+ Test.Tasty.defaultMain $ testGroup "hledger" [+ tests_Hledger+ ,tests_Hledger_Cli+ ]++-- All unit tests for Hledger.Cli, defined here rather than+-- Hledger.Cli so runUnitTests can use them.+tests_Hledger_Cli = testGroup "Hledger.Cli" [+ tests_Cli_Utils+ ,tests_Commands+ ]++tests_Commands = testGroup "Commands" [+ tests_Balance+ ,tests_Register+ ,tests_Aregister+ ,tests_Init++ -- some more tests easiest to define here:++ ,testGroup "apply account directive" [+ testCase "works" $ do+ let+ ignoresourcepos j = j{jtxns=map (\t -> t{tsourcepos=nullsourcepospair}) (jtxns j), jitems=[]}+ sameParse str1 str2 = do+ j1 <- ignoresourcepos <$> readJournal'' str1 -- PARTIAL:+ j2 <- ignoresourcepos <$> readJournal'' str2 -- PARTIAL:+ j1 @?= j2{jlastreadtime=jlastreadtime j1, jfiles=jfiles j1} --, jparsestate=jparsestate j1}+ sameParse+ ("2008/12/07 One\n alpha $-1\n beta $1\n" <>+ "apply account outer\n2008/12/07 Two\n aigh $-2\n bee $2\n" <>+ "apply account inner\n2008/12/07 Three\n gamma $-3\n delta $3\n" <>+ "end apply account\n2008/12/07 Four\n why $-4\n zed $4\n" <>+ "end apply account\n2008/12/07 Five\n foo $-5\n bar $5\n"+ )+ ("2008/12/07 One\n alpha $-1\n beta $1\n" <>+ "2008/12/07 Two\n outer:aigh $-2\n outer:bee $2\n" <>+ "2008/12/07 Three\n outer:inner:gamma $-3\n outer:inner:delta $3\n" <>+ "2008/12/07 Four\n outer:why $-4\n outer:zed $4\n" <>+ "2008/12/07 Five\n foo $-5\n bar $5\n"+ )++ ,testCase "preserves \"virtual\" posting type" $ do+ j <- readJournal'' "apply account test\n2008/12/07 One\n (from) $-1\n (to) $1\n" -- PARTIAL:+ let p = headErr $ tpostings $ headErr $ jtxns j -- PARTIAL headErrs succeed because txns & postings provided+ paccount p @?= "test:from"+ preal p @?= VirtualPosting+ ]++ ,testCase "alias directive" $ do+ j <- readJournal'' "!alias expenses = equity:draw:personal\n1/1\n (expenses:food) 1\n" -- PARTIAL:+ let p = headErr $ tpostings $ headErr $ jtxns j -- PARTIAL headErrs succeed because txns & postings provided+ paccount p @?= "equity:draw:personal:food"++ ,testCase "Y default year directive" $ do+ j <- readJournal'' defaultyear_journal_txt -- PARTIAL:+ tdate (headErr $ jtxns j) @?= fromGregorian 2009 1 1 -- PARTIAL headErr succeeds because defaultyear_journal_txt has a txn++ ,testCase "ledgerAccountNames" $+ (ledgerAccountNames ledger7)+ @?=+ ["assets","assets:cash","assets:checking","assets:saving","equity","equity:opening balances",+ "expenses","expenses:food","expenses:food:dining","expenses:phone","expenses:vacation",+ "liabilities","liabilities:credit cards","liabilities:credit cards:discover"]++ -- ,testCase "journalCanonicaliseAmounts" ~:+ -- "use the greatest precision" ~:+ -- (map asprecision $ journalAmountAndPriceCommodities $ journalCanonicaliseAmounts $ journalWithAmounts ["1","2.00"]) @?= [2,2]++ -- don't know what this should do+ -- ,testCase "elideAccountName" ~: do+ -- (elideAccountName 50 "aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa"+ -- @?= "aa:aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa")+ -- (elideAccountName 20 "aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa:aaaaaaaaaaaaaaaaaaaa"+ -- @?= "aa:aa:aaaaaaaaaaaaaa")++ ,testCase "show dollars" $ showAmount (usd 1) @?= "$1.00"++ ,testCase "show hours" $ showAmount (hrs 1) @?= "1.00h"++ ]++-- test data++-- date1 = fromGregorian 2008 11 26+-- t1 = LocalTime date1 midday++{-+samplejournal = readJournal'' sample_journal_str++sample_journal_str = unlines+ ["; A sample journal file."+ ,";"+ ,"; Sets up this account tree:"+ ,"; assets"+ ,"; bank"+ ,"; checking"+ ,"; saving"+ ,"; cash"+ ,"; expenses"+ ,"; food"+ ,"; supplies"+ ,"; income"+ ,"; gifts"+ ,"; salary"+ ,"; liabilities"+ ,"; debts"+ ,""+ ,"2008/01/01 income"+ ," assets:bank:checking $1"+ ," income:salary"+ ,""+ ,"2008/06/01 gift"+ ," assets:bank:checking $1"+ ," income:gifts"+ ,""+ ,"2008/06/02 save"+ ," assets:bank:saving $1"+ ," assets:bank:checking"+ ,""+ ,"2008/06/03 * eat & shop"+ ," expenses:food $1"+ ," expenses:supplies $1"+ ," assets:cash"+ ,""+ ,"2008/12/31 * pay off"+ ," liabilities:debts $1"+ ," assets:bank:checking"+ ,""+ ,""+ ,";final comment"+ ]+-}++defaultyear_journal_txt :: Text+defaultyear_journal_txt = T.unlines+ ["Y2009"+ ,""+ ,"01/01 A"+ ," a $1"+ ," b"+ ]++-- write_sample_journal = writeFile "sample.journal" sample_journal_str++-- entry2_str = unlines+-- ["2007/01/27 * joes diner"+-- ," expenses:food:dining $10.00"+-- ," expenses:gifts $10.00"+-- ," assets:checking $-20.00"+-- ,""+-- ]++-- entry3_str = unlines+-- ["2007/01/01 * opening balance"+-- ," assets:cash $4.82"+-- ," equity:opening balances"+-- ,""+-- ,"2007/01/01 * opening balance"+-- ," assets:cash $4.82"+-- ," equity:opening balances"+-- ,""+-- ,"2007/01/28 coopportunity"+-- ," expenses:food:groceries $47.18"+-- ," assets:checking"+-- ,""+-- ]++-- periodic_entry1_str = unlines+-- ["~ monthly from 2007/2/2"+-- ," assets:saving $200.00"+-- ," assets:checking"+-- ,""+-- ]++-- periodic_entry2_str = unlines+-- ["~ monthly from 2007/2/2"+-- ," assets:saving $200.00 ;auto savings"+-- ," assets:checking"+-- ,""+-- ]++-- periodic_entry3_str = unlines+-- ["~ monthly from 2007/01/01"+-- ," assets:cash $4.82"+-- ," equity:opening balances"+-- ,""+-- ,"~ monthly from 2007/01/01"+-- ," assets:cash $4.82"+-- ," equity:opening balances"+-- ,""+-- ]++-- journal1_str = unlines+-- [""+-- ,"2007/01/27 * joes diner"+-- ," expenses:food:dining $10.00"+-- ," expenses:gifts $10.00"+-- ," assets:checking $-20.00"+-- ,""+-- ,""+-- ,"2007/01/28 coopportunity"+-- ," expenses:food:groceries $47.18"+-- ," assets:checking $-47.18"+-- ,""+-- ,""+-- ]++-- journal2_str = unlines+-- [";comment"+-- ,"2007/01/27 * joes diner"+-- ," expenses:food:dining $10.00"+-- ," assets:checking $-47.18"+-- ,""+-- ]++-- journal3_str = unlines+-- ["2007/01/27 * joes diner"+-- ," expenses:food:dining $10.00"+-- ,";intra-entry comment"+-- ," assets:checking $-47.18"+-- ,""+-- ]++-- journal4_str = unlines+-- ["include \"somefile\""+-- ,"2007/01/27 * joes diner"+-- ," expenses:food:dining $10.00"+-- ," assets:checking $-47.18"+-- ,""+-- ]++-- journal5_str = ""++-- journal6_str = unlines+-- ["~ monthly from 2007/1/21"+-- ," expenses:entertainment $16.23 ;netflix"+-- ," assets:checking"+-- ,""+-- ,"; 2007/01/01 * opening balance"+-- ,"; assets:saving $200.04"+-- ,"; equity:opening balances "+-- ,""+-- ]++-- journal7_str = unlines+-- ["2007/01/01 * opening balance"+-- ," assets:cash $4.82"+-- ," equity:opening balances "+-- ,""+-- ,"2007/01/01 * opening balance"+-- ," income:interest $-4.82"+-- ," equity:opening balances "+-- ,""+-- ,"2007/01/02 * ayres suites"+-- ," expenses:vacation $179.92"+-- ," assets:checking "+-- ,""+-- ,"2007/01/02 * auto transfer to savings"+-- ," assets:saving $200.00"+-- ," assets:checking "+-- ,""+-- ,"2007/01/03 * poquito mas"+-- ," expenses:food:dining $4.82"+-- ," assets:cash "+-- ,""+-- ,"2007/01/03 * verizon"+-- ," expenses:phone $95.11"+-- ," assets:checking "+-- ,""+-- ,"2007/01/03 * discover"+-- ," liabilities:credit cards:discover $80.00"+-- ," assets:checking "+-- ,""+-- ,"2007/01/04 * blue cross"+-- ," expenses:health:insurance $90.00"+-- ," assets:checking "+-- ,""+-- ,"2007/01/05 * village market liquor"+-- ," expenses:food:dining $6.48"+-- ," assets:checking "+-- ,""+-- ]++journal7 :: Journal+journal7 = nulljournal {jtxns =+ [+ txnTieKnot Transaction {+ tindex=0,+ tsourcepos=nullsourcepospair,+ tdate=fromGregorian 2007 01 01,+ tdate2=Nothing,+ tstatus=Unmarked,+ tcode="*",+ tdescription="opening balance",+ tcomment="",+ ttags=[],+ tpostings=+ ["assets:cash" `post` usd 4.82+ ,"equity:opening balances" `post` usd (-4.82)+ ],+ tprecedingcomment=""+ }+ ,+ txnTieKnot Transaction {+ tindex=0,+ tsourcepos=nullsourcepospair,+ tdate=fromGregorian 2007 02 01,+ tdate2=Nothing,+ tstatus=Unmarked,+ tcode="*",+ tdescription="ayres suites",+ tcomment="",+ ttags=[],+ tpostings=+ ["expenses:vacation" `post` usd 179.92+ ,"assets:checking" `post` usd (-179.92)+ ],+ tprecedingcomment=""+ }+ ,+ txnTieKnot Transaction {+ tindex=0,+ tsourcepos=nullsourcepospair,+ tdate=fromGregorian 2007 01 02,+ tdate2=Nothing,+ tstatus=Unmarked,+ tcode="*",+ tdescription="auto transfer to savings",+ tcomment="",+ ttags=[],+ tpostings=+ ["assets:saving" `post` usd 200+ ,"assets:checking" `post` usd (-200)+ ],+ tprecedingcomment=""+ }+ ,+ txnTieKnot Transaction {+ tindex=0,+ tsourcepos=nullsourcepospair,+ tdate=fromGregorian 2007 01 03,+ tdate2=Nothing,+ tstatus=Unmarked,+ tcode="*",+ tdescription="poquito mas",+ tcomment="",+ ttags=[],+ tpostings=+ ["expenses:food:dining" `post` usd 4.82+ ,"assets:cash" `post` usd (-4.82)+ ],+ tprecedingcomment=""+ }+ ,+ txnTieKnot Transaction {+ tindex=0,+ tsourcepos=nullsourcepospair,+ tdate=fromGregorian 2007 01 03,+ tdate2=Nothing,+ tstatus=Unmarked,+ tcode="*",+ tdescription="verizon",+ tcomment="",+ ttags=[],+ tpostings=+ ["expenses:phone" `post` usd 95.11+ ,"assets:checking" `post` usd (-95.11)+ ],+ tprecedingcomment=""+ }+ ,+ txnTieKnot Transaction {+ tindex=0,+ tsourcepos=nullsourcepospair,+ tdate=fromGregorian 2007 01 03,+ tdate2=Nothing,+ tstatus=Unmarked,+ tcode="*",+ tdescription="discover",+ tcomment="",+ ttags=[],+ tpostings=+ ["liabilities:credit cards:discover" `post` usd 80+ ,"assets:checking" `post` usd (-80)+ ],+ tprecedingcomment=""+ }+ ]+ }++ledger7 :: Ledger+ledger7 = ledgerFromJournal Any journal7
+ Hledger/Cli/Commands/Accounts.hs view
@@ -0,0 +1,158 @@+{-|++The @accounts@ command lists account names:++- in flat mode (default), it lists the full names of accounts posted to by matched postings,+ clipped to the specified depth, possibly with leading components dropped.++- in tree mode, it shows the indented short names of accounts posted to by matched postings,+ and their parents, to the specified depth.++-}++{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Accounts (+ accountsmode+ ,accounts+) where++import Data.List+import Data.Map qualified as M+import Data.Text qualified as T+import System.Console.CmdArgs.Explicit as C++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils (writeOutputWithTitle)+++-- | Command line options for this command.+accountsmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Accounts.txt")+ (+ [flagNone ["used","u"] (setboolopt "used") "list accounts used"+ ,flagNone ["declared","d"] (setboolopt "declared") "list accounts declared"+ ,flagNone ["undeclared"] (setboolopt "undeclared") "list accounts used but not declared"+ ,flagNone ["unused"] (setboolopt "unused") "list accounts declared but not used"+ ,flagNone ["find"] (setboolopt "find") "list the first account matched by the first argument (a case-insensitive infix regexp)"+ ,flagNone ["directives"] (setboolopt "directives") "show as account directives, for use in journals"+ ,flagNone ["locations"] (setboolopt "locations") "also show where accounts were declared, or first used"+ ,flagNone ["types"] (setboolopt "types") "also show account types when known"+ ,flagNone ["show-aliases"] (setboolopt "show-aliases") "also show account aliases declared with alias: tags"+ ]+ ++ flattreeflags False +++ [flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "flat mode: omit N leading account name parts"]+ )+ cligeneralflagsgroups1+ (hiddenflags +++ [flagNone ["positions"] (setboolopt "locations") "deprecated, use --locations instead"+ ])+ ([], Just $ argsFlag "[QUERY..]")++-- | The accounts command.+accounts :: CliOpts -> Journal -> IO ()+accounts opts@CliOpts{rawopts_=rawopts, reportspec_=ReportSpec{_rsQuery=query,_rsReportOpts=ropts}} j = do+ -- 1. identify the accounts we'll show+ let tree = tree_ ropts+ directives = boolopt "directives" rawopts+ locations = boolopt "locations" rawopts+ types = boolopt "types" rawopts+ showaliases = boolopt "show-aliases" rawopts+ -- Modified queries. These may not work with boolean queries (#2371).+ -- with --show-aliases, acct: terms also match account aliases (alias: tags)+ aliasq = if showaliases then transformQuery matchAliasToo else id+ where+ matchAliasToo (Acct r) = Or [Acct r, Tag (toRegexCI' "^alias$") (Just r)]+ matchAliasToo q = q+ -- a depth limit will clip and exclude account names later, but we don't want to exclude accounts at this stage+ nodepthq = dbg4 "nodepthq" $ aliasq $ filterQuery (not . queryIsDepth) query+ -- just the acct: part of the query will be reapplied later, after clipping+ acctq = dbg4 "acctq" $ aliasq $ filterQuery queryIsAcct query+ dep = dbg4 "depth" $ queryDepth $ filterQuery queryIsDepth query+ -- when finding accounts used by postings, we remove tags that were declared on the posting,+ -- so that a tag: query will match account tags and not posting tags.+ matchedused = dbg5 "matchedused" $ nub $ map paccount $ journalPostings $+ filterJournalPostings nodepthq $ journalPostingsKeepAccountTagsOnly j+ matcheddeclared = dbg5 "matcheddeclared" $+ nub $+ filter (matchesAccountExtra (journalAccountType j) (journalInheritedAccountTags j) nodepthq) $+ map fst $ jdeclaredaccounts j+ -- unused/undeclared subtract the full used/declared sets, not the query-filtered ones,+ -- so that eg a date: query can't make a declared account look undeclared.+ matchedundeclared = dbg5 "matchedundeclared" $ nub $ matchedused \\ alldeclared+ matchedunused = dbg5 "matchedunused" $ nub $ matcheddeclared \\ allused+ allused = map paccount $ journalPostings j+ alldeclared = map fst $ jdeclaredaccounts j+ found = dbg5 "matchedacct" $ findMatchedByArgument rawopts "account" $ journalAccountNamesDeclaredOrImplied j+ matchedall = matcheddeclared ++ matchedused+ accts = dbg5 "accts to show" $+ case declarablesSelectorFromOpts opts of+ Nothing -> matchedall+ Just Used -> matchedused+ Just Declared -> matcheddeclared+ Just Undeclared -> matchedundeclared+ Just Unused -> matchedunused+ Just FindFirst -> [found]++ -- 2. sort them by declaration order (then undeclared accounts alphabetically)+ -- within each group of siblings+ sortedaccts = sortAccountNamesByDeclaration j tree accts++ -- 2a. in tree mode, add parent accounts for tree structure context+ acctswithparents =+ if tree+ then dbg4 "acctswithparents" $+ sortAccountNamesByDeclaration j tree $ -- re-sort after adding parents+ expandAccountNames sortedaccts -- add all parent accounts+ else sortedaccts++ -- 3. if there's a depth limit, depth-clip and remove any no longer useful items+ clippedaccts =+ dbg4 "clippedaccts" $+ (if tree then id else filter (matchesAccountExtra (journalAccountType j) (journalInheritedAccountTags j) acctq)) $ -- in tree mode, keep parent accounts even if they don't match+ nub $ -- clipping can leave duplicates (adjacent, hopefully)+ filter (not . T.null) $ -- depth:0 can leave nulls+ map (clipAccountName dep) $ -- clip at depth if specified+ acctswithparents -- use expanded list instead of sortedaccts++ -- 4. print what remains as a list or tree, maybe applying --drop in the former case.+ -- Add various bits of info if enabled.+ let+ showKeyword = if directives then "account " else ""+ -- some contortions here to show types nicely aligned+ showName a = case accountlistmode_ ropts of+ ALTree -> indent <> accountLeafName droppedName+ ALFlat -> droppedName+ where+ indent = T.replicate (2 * (max 0 (accountNameLevel a - drop_ ropts) - 1)) " "+ droppedName = accountNameDrop (drop_ ropts) a+ -- the account's type (with --types), aliases (with --directives or --show-aliases) and declaration location (with --locations),+ -- as a comment+ showComment a = case typeitem ++ aliasitems ++ locationitem of+ [] -> ""+ items -> pad a <> " ; " <> T.intercalate ", " items+ where+ typeitem = ["type: " <> T.pack (show t) | types, Just t <- [journalAccountType j a]]+ aliasitems = ["alias: " <> v | directives || showaliases, (n, v) <- journalAccountTags j a, T.toLower n == "alias"]+ locationitem+ | locations = [case lookup a $ jdeclaredaccounts j of+ Just adi -> "declared at " <> T.pack (sourcePosFileLine $ adisourcepos adi) <>+ ", overall declaration order " <> T.pack (show $ adideclarationorder adi)+ Nothing -> "undeclared" <> maybe "" (", first used at " <>) (M.lookup a firstuses)]+ | otherwise = []+ -- The FILE:LINE where each account was first posted to, for --locations.+ -- (makePostingErrorExcerptByIndex's excerpt is not used, so it is not rendered.)+ firstuses = M.fromListWith (\_ earlier -> earlier)+ [ (paccount p, T.pack $ f ++ ":" ++ show l)+ | t <- jtxns j+ , (i,p) <- zip [0..] $ tpostings t+ , let (f, l, _, _) = makePostingErrorExcerptByIndex t i Nothing+ ]+ pad a = T.replicate (maxwidth - T.length (showName a)) " "+ maxwidth = maximum $ map (T.length . showName) clippedaccts++ writeOutputWithTitle opts $ T.unlines [showKeyword <> showName a <> showComment a | a <- clippedaccts]
+ Hledger/Cli/Commands/Accounts.txt view
@@ -0,0 +1,74 @@+accounts++(acc)++List the account names used or declared in the journal.++Flags:+ -u --used list accounts used+ -d --declared list accounts declared+ --undeclared list accounts used but not declared+ --unused list accounts declared but not used+ --find list the first account matched by the first+ argument (a case-insensitive infix regexp)+ --directives show as account directives, for use in journals+ --locations also show where accounts were declared, or first+ used+ --types also show account types when known+ --show-aliases also show account aliases declared with alias:+ tags+ -l --flat list/tree mode: show accounts as a flat list+ (default)+ -t --tree list/tree mode: show accounts as a tree+ --drop=N flat mode: omit N leading account name parts++This command lists account names - all of them by default, or just the+ones which have been used in transactions (-u/--used), or declared with+account directives (-d/--declared), or used but not declared+(--undeclared), or declared but not used (--unused), or just the first+one matched by a pattern (--find, returning a non-zero exit code if it+fails).++You can add query arguments to select a subset of transactions or+accounts. Note that transaction-specific query terms like date: will+exclude declared-but-unused accounts, which don't have that field.++With --directives, it shows valid account directives which could be+pasted into a journal file, including any account aliases as alias:+tags. This is useful together with --undeclared when updating your+account declarations to satisfy hledger check accounts.++With --locations, it also shows the file and line number of each+account's declaration, if any, and the account's overall declaration+order; these may be useful when troubleshooting account display order.+For an undeclared account, it shows where the account was first used+(posted to), if anywhere.++With --types, it also shows each account's type, if it's known. (See+Declaring accounts > Account types.)++With --show-aliases, it also shows each account's aliases, declared with+alias: tags. (Aliases from alias directives or --alias options are not+shown.) Also, account names in the query will match aliases too, so eg+hledger accounts --show-aliases chk shows the account(s) with an alias+containing chk.++It shows a flat list by default. With --tree, it uses indentation to+show the account hierarchy. In flat mode you can add --drop N to omit+the first few account name components. Account names can be+depth-clipped with depth:N or --depth N or -N.++Examples:++$ hledger accounts+assets:bank:checking+assets:bank:saving+assets:cash+expenses:food+expenses:supplies+income:gifts+income:salary+liabilities:debts++$ hledger accounts --undeclared --directives >> $LEDGER_FILE+$ hledger check accounts
+ Hledger/Cli/Commands/Activity.hs view
@@ -0,0 +1,60 @@+{-# LANGUAGE TemplateHaskell #-}++{-|++Show a bar chart of transaction counts per week, or other report interval.+With --postings, show posting counts by account instead;+this is a shortcut for @balance --count --chart -W@.++-}++module Hledger.Cli.Commands.Activity+where++import Data.Maybe (fromMaybe)+import System.Console.CmdArgs.Explicit (flagNone)++import Hledger+import Hledger.Cli.Chart (chartWidthFlag)+import Hledger.Cli.CliOptions+import Hledger.Cli.Commands.Balance (balance)++activitymode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Activity.txt")+ [ outputFormatFlag ["txt","svg","html","csv","tsv","json"]+ , outputFileFlag+ , outputViewFlag+ , chartWidthFlag+ , flagNone ["txns"] (setboolopt "txns") "count transactions, showing just the total (default)"+ , flagNone ["postings"] (setboolopt "postings") "count postings, showing each account's count"+ , flagNone ["sort-amount","S"] (setboolopt "sort-amount") "with --postings, sort accounts by posting count, largest first"+ , flagNone ["total","T"] (setboolopt "row-total") "show the total count, below the chart"+ , flagNone ["average","A"] (setboolopt "average") "show the average count per period, below the chart (and as a line in SVG charts)"+ ]+ cligeneralflagsgroups1+ hiddenflags+ ([], Just $ argsFlag "[QUERY]")++-- | Show a bar chart of the number of transactions per report interval (weekly by default),+-- as a single total (like depth 0), since a transaction's postings may be in several accounts.+-- Or with --postings, the number of postings, by account.+-- This runs the balance command with --count (or its transaction-counting equivalent) and --chart.+-- If both --txns and --postings are given, the last one wins.+activity :: CliOpts -> Journal -> IO ()+activity opts@CliOpts{rawopts_, reportspec_=rspec@ReportSpec{_rsReportOpts=ropts}} j = do+ rspec' <- either fail return $ updateReportSpec ropts' rspec+ balance opts+ { rawopts_ = setopt "chart" "auto" rawopts_+ , reportspec_ = rspec'+ } j+ where+ txns = fromMaybe True $ choiceopt countopt rawopts_+ where+ countopt "txns" = Just True+ countopt "postings" = Just False+ countopt _ = Nothing+ ropts' = ropts+ { balancecalc_ = if txns then CalcTransactionsCount else CalcPostingsCount+ , interval_ = if interval_ ropts == NoInterval then Weeks 1 else interval_ ropts+ , depth_ = if txns then DepthSpec (Just 0) [] else depth_ ropts+ }
+ Hledger/Cli/Commands/Activity.txt view
@@ -0,0 +1,88 @@+activity++Show a bar chart of transaction counts per week, or other report+interval.++Flags:+ -O --output-format=FMT select the output format. Supported formats:+ txt, svg, html, csv, tsv, json.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ --view write output to FILE, or to view.FMT in hledger's+ cache directory, and open it in the system's+ default viewer for its format (eg a web browser for+ html). The default format is html.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)+ --txns count transactions, showing just the total+ (default)+ --postings count postings, showing each account's count+ -S --sort-amount with --postings, sort accounts by posting count,+ largest first+ -T --total show the total count, below the chart+ -A --average show the average count per period, below the+ chart (and as a line in SVG charts)++The activity command shows how many transactions there are in each week+(or with a report interval, each day, month, quarter etc.), as a bar+chart. Each transaction is one character, unless there are too many to+fit, when the bars are scaled down. With query arguments, it counts only+the transactions which have at least one matched posting.++Or with --postings, it shows how many postings there are in each period,+with each account's postings stacked in its own colour. With query+arguments, it counts only the matched postings. This is a shortcut for+balance --count --chart, with a weekly interval by default, so it can+show charts in all the same ways: eg with -1 or other depth limit to+show less detail, -0 to show just the total count, without the accounts'+detail, -S/--sort-amount to show the accounts with most postings first.+(Transaction counts show just the total, since a transaction's postings+can be in several accounts.)++--txns selects transaction counts explicitly; if both --txns and+--postings are given, the last one wins.++Both kinds of chart can be shown in the usual ways, eg with -w/--width+to set the width, -T/--total and -A/--average to show the total count+and the average count per period below the chart (in graphical charts,+the average is also drawn as a dashed line), or -o FILE.svg (or -O svg)+for a graphical chart.++Examples:++$ hledger activity -M -T -A -w 40+Transaction counts in 2008:++Jan 1 █+Feb 0+Mar 0+Apr 0+May 0+Jun 3 ███+Jul 0+Aug 0+Sep 0+Oct 0+Nov 0+Dec 1 █++Total 5, Average 0.4++$ hledger activity -M --postings -1 -w 40+Posting counts in 2008:++▓ assets █ expenses ░ income+▒ liabilities++Jan 2 ▓░+Feb 0+Mar 0+Apr 0+May 0+Jun 7 ▓▓▓▓██░+Jul 0+Aug 0+Sep 0+Oct 0+Nov 0+Dec 2 ▓▒
+ Hledger/Cli/Commands/Add.hs view
@@ -0,0 +1,632 @@+{-|+A history-aware, tab-completing interactive add command to help with data entry.+-}++{-# OPTIONS_GHC -fno-warn-missing-signatures -fno-warn-unused-do-bind #-}+{-# LANGUAGE FlexibleContexts #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE PackageImports #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE TypeOperators #-}++module Hledger.Cli.Commands.Add (+ addmode+ ,add+ ,appendToJournalFileOrStdout+ ,journalAddTransaction+ ,journalFileTextAfterAppends+)+where++import Control.Concurrent (forkIO, killThread)+import Control.Concurrent.MVar (newEmptyMVar, putMVar, readMVar)+import Control.Exception as E+import Control.Monad (unless, when)+import Control.Monad.Trans.Class+import Control.Monad.State.Strict (evalState, evalStateT)+import Control.Monad.Trans (liftIO)+import Data.Char (toUpper, toLower)+import Data.Either (isRight)+import Data.Functor.Identity (Identity(..))+import Data.List (isPrefixOf, nub)+import Data.Maybe (fromJust, fromMaybe, isJust)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.IO qualified as T+import Data.Text.Lazy qualified as TL+import Data.Text.Lazy.IO qualified as TL+import Data.Time.Calendar (Day, toGregorian)+import Data.Time.Format (formatTime, defaultTimeLocale)+import Lens.Micro ((^.))+import Safe (headDef, headMay, atMay, lastMay)+import System.Console.CmdArgs.Explicit (flagNone)+import System.Console.Haskeline (runInputT, defaultSettings, setComplete)+import System.Console.Haskeline.Completion (CompletionFunc, completeWord, isFinished, noCompletion, simpleCompletion)+import System.Console.Wizard (Wizard, defaultTo, line, output, outputLn, retryMsg, linePrewritten, nonEmpty, parser, run)+import System.Console.Wizard.Haskeline+import System.Directory (doesFileExist)+import System.FilePath (takeDirectory)+import System.IO (hPutStr, hPutStrLn, stderr)+import Text.Megaparsec+import Text.Megaparsec.Char+import Text.Printf++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Commands.Print (layoutFlag, layoutFromRawOpts)+import Hledger.Cli.Commands.Register (postingsReportAsText)+import Hledger.Cli.Utils (journalCheckChange, journalSimilarTransaction)+++addmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Add.txt")+ [flagNone ["no-new-accounts"] (setboolopt "no-new-accounts") "don't allow creating new accounts"+ ,layoutFlag+ ]+ [generalflagsgroup2]+ confflags+ ([], Just $ argsFlag "[-f JOURNALFILE] [DATE [DESCRIPTION [ACCOUNT1 [ETC..]]]]]")++data AddState = AddState {+ asOpts :: CliOpts -- ^ command line options+ ,asArgs :: [String] -- ^ command line arguments remaining to be used as defaults+ ,asToday :: Day -- ^ today's date+ ,asDefDate :: Day -- ^ the default date to use for the next transaction+ ,asJournal :: Journal -- ^ the journal we are adding to+ ,asSimilarTransaction :: Maybe Transaction -- ^ the old transaction most similar to the new one being entered+ ,asPostings :: [Posting] -- ^ the new postings entered so far+ ,asInferredAmounts :: [Maybe MixedAmount]+ -- ^ posting amounts inferred from balance assignments, if any, corresponding to asPostings.+ -- Stored so subsequent amount prompts can offer the inferred amount's negation as a default.+} deriving (Show)++defAddState = AddState {+ asOpts = defcliopts+ ,asArgs = []+ ,asToday = nulldate+ ,asDefDate = nulldate+ ,asJournal = nulljournal+ ,asSimilarTransaction = Nothing+ ,asPostings = []+ ,asInferredAmounts = []+}++data AddStep =+ GetDate+ | GetDescription (Day, Text)+ | GetPosting TxnData (Maybe Posting)+ | GetAccount TxnData+ | GetAmount TxnData String+ | Confirm Transaction++data TxnData = TxnData {+ txnDate :: Day+ , txnCode :: Text+ , txnDesc :: Text+ , txnCmnt :: Text+} deriving (Show)++type Comment = (Text, [Tag], Maybe Day, Maybe Day)++data PrevInput = PrevInput {+ prevDateAndCode :: Maybe String+ , prevDescAndCmnt :: Maybe String+ , prevAccount :: [String]+ , prevAmountAndCmnt :: [String]+} deriving (Show)++data RestartTransactionException = RestartTransactionException deriving (Show)+instance Exception RestartTransactionException++-- data ShowHelpException = ShowHelpException deriving (Show)+-- instance Exception ShowHelpException++-- | Read multiple transactions from the console, prompting for each+-- field, and append them to the journal file. If the journal came+-- from stdin, this command has no effect.+add :: CliOpts -> Journal -> IO ()+add opts j+ | journalFilePath j == "-" = return ()+ | otherwise = do+ hPutStrLn stderr $ "Adding transactions to journal file " <> journalFilePath j+ showHelp+ let today = opts^.rsDay+ state = defAddState{asOpts=opts+ ,asArgs=listofstringopt "args" $ rawopts_ opts+ ,asToday=today+ ,asDefDate=today+ ,asJournal=j+ }+ addTransactionsLoop state `E.catch` (\(_::UnexpectedEOF) -> putStr "")++showHelp = hPutStr stderr $ unlines [+ "Any command line arguments will be used as defaults."+ ,"Use tab key to complete, readline keys to edit, enter to accept defaults."+ ,"An optional (CODE) may follow transaction dates."+ ,"An optional ; COMMENT may follow descriptions or amounts."+ ,"If you make a mistake, enter < at any prompt to go one step backward."+ ,"To end a transaction, enter . when prompted."+ ,"To quit, enter . at a date prompt or press control-d or control-c."+ ]++-- | Loop reading transactions from the console, prompting, validating+-- and appending each one to the journal file, until end of input or+-- ctrl-c (then raise an EOF exception). If provided, command-line+-- arguments are used as defaults; otherwise defaults come from the+-- most similar recent transaction in the journal.+addTransactionsLoop :: AddState -> IO ()+addTransactionsLoop state@AddState{..} = (do+ let defaultPrevInput = PrevInput{prevDateAndCode=Nothing, prevDescAndCmnt=Nothing, prevAccount=[], prevAmountAndCmnt=[]}+ mt <- runInputT (setComplete noCompletion defaultSettings) (System.Console.Wizard.run $ haskeline $ transactionWizard defaultPrevInput state [])+ case mt of+ Nothing -> error' "Could not interpret the input, restarting" -- caught below causing a restart, I believe -- PARTIAL:+ -- The transaction, and the journal as it will be read with it added (checked by the wizard).+ Just (t, checkedj) -> do+ j <- if debug_ asOpts > 0+ then do hPutStrLn stderr "Skipping journal add due to debug mode."+ return asJournal+ else do _ <- journalAddTransaction asJournal asOpts t+ hPutStrLn stderr "Saved."+ return checkedj+ hPutStrLn stderr "Starting the next transaction (. or ctrl-D/ctrl-C to quit)"+ addTransactionsLoop state{asJournal=j, asDefDate=tdate t}+ )+ `E.catch` (\(_::RestartTransactionException) ->+ hPutStrLn stderr "Restarting this transaction." >> addTransactionsLoop state)++-- | Interact with the user to get a Transaction,+-- and the journal as it will be read with the transaction added to its file.+transactionWizard :: PrevInput -> AddState -> [AddStep] -> Wizard Haskeline (Transaction, Journal)+transactionWizard previnput state [] = transactionWizard previnput state [GetDate]+transactionWizard previnput state@AddState{..} stack@(currentStage : _) = case currentStage of+ GetDate -> dateWizard previnput state >>= \case+ Just (efd, code) -> do+ let+ date = fromEFDay efd+ state' = state{ asArgs = drop 1 asArgs+ , asDefDate = date+ }+ dateAndCodeString = formatTime defaultTimeLocale yyyymmddFormat date+ ++ T.unpack (if T.null code then "" else " (" <> code <> ")")+ yyyymmddFormat = "%Y-%m-%d"+ transactionWizard previnput{prevDateAndCode=Just dateAndCodeString} state' (GetDescription (date, code) : stack)+ Nothing ->+ transactionWizard previnput state stack++ GetDescription (date, code) -> descriptionWizard previnput state >>= \case+ Just (desc, comment) -> do+ let mbaset = journalSimilarTransaction asOpts asJournal desc+ state' = state+ { asArgs = drop 1 asArgs+ , asPostings = []+ , asInferredAmounts = []+ , asSimilarTransaction = mbaset+ }+ descAndCommentString = T.unpack $ desc <> (if T.null comment then "" else " ; " <> comment)+ previnput' = previnput{prevDescAndCmnt=Just descAndCommentString}+ when (isJust mbaset) . liftIO $ do+ hPutStrLn stderr "Using this similar transaction for defaults:"+ T.hPutStr stderr $ showTransactionWithLayout (layoutFromRawOpts $ rawopts_ asOpts) (fromJust mbaset)+ transactionWizard previnput' state' ((GetPosting TxnData{txnDate=date, txnCode=code, txnDesc=desc, txnCmnt=comment} Nothing) : stack)+ Nothing ->+ transactionWizard previnput state (drop 1 stack)++ GetPosting txndata@TxnData{..} p -> case (asPostings, p) of+ ([], Nothing) ->+ transactionWizard previnput state (GetAccount txndata : stack)+ (_, Just _) ->+ transactionWizard previnput state (GetAccount txndata : stack)+ (_, Nothing) -> do+ let t = nulltransaction{tdate=txnDate+ ,tstatus=Unmarked+ ,tcode=txnCode+ ,tdescription=txnDesc+ ,tcomment=txnCmnt+ ,tpostings=asPostings+ }+ bopts = balancingopts_ (inputopts_ asOpts)+ case balanceTransactionInJournal t asJournal bopts of+ Right t' ->+ transactionWizard previnput state (Confirm t' : stack)+ Left err -> do+ liftIO (hPutStrLn stderr $ "\n" ++ (capitalize err) ++ ", please re-enter.")+ -- Back up one step: re-prompt for the next account, keeping postings entered so far.+ transactionWizard previnput state (GetAccount txndata : drop 1 stack)++ GetAccount txndata -> accountWizard previnput state >>= \case+ Just account+ | account `elem` [".", ""] ->+ case (asPostings, postingsAreBalanced asJournal asPostings) of+ ([],_) -> liftIO (hPutStrLn stderr "Please enter some postings first.") >> transactionWizard previnput state stack+ (_,False) -> liftIO (hPutStrLn stderr "Please enter more postings to balance the transaction.") >> transactionWizard previnput state stack+ (_,True) -> transactionWizard previnput state (GetPosting txndata Nothing : stack)+ | otherwise -> do+ let prevAccount' = replaceNthOrAppend (length asPostings) account (prevAccount previnput)+ transactionWizard previnput{prevAccount=prevAccount'} state{asArgs=drop 1 asArgs} (GetAmount txndata account : stack)+ Nothing -> do+ let notPrevAmountAndNotGetDesc stage = case stage of+ GetAmount _ _ -> False+ GetDescription _ -> False+ _ -> True+ transactionWizard previnput state{asPostings=init asPostings, asInferredAmounts=init asInferredAmounts} (dropWhile notPrevAmountAndNotGetDesc stack)++ GetAmount txndata account -> amountWizard previnput state >>= \case+ Just (mamt, assertion, (comment, tags, pdate1, pdate2)) -> do+ let mixedamt = maybe missingmixedamt mixedAmount mamt+ p = nullposting{paccount=T.pack $ stripbrackets account+ ,pamount=mixedamt+ ,pcomment=T.dropAround isNewline comment+ ,preal=accountNamePostingType $ T.pack account+ ,pbalanceassertion = assertion+ ,pdate=pdate1+ ,pdate2=pdate2+ ,ptags=tags+ }+ amountAndCommentString = showMixedAmountOneLine mixedamt ++ T.unpack (if T.null comment then "" else " ;" <> comment)+ prevAmountAndCmnt' = replaceNthOrAppend (length asPostings) amountAndCommentString (prevAmountAndCmnt previnput)+ -- Include a dummy posting to balance the unfinished transation in assertion checking+ dummytxn = nulltransaction{tpostings = asPostings ++ [p, post "" missingamt]+ ,tdate = txnDate txndata+ ,tdescription = txnDesc txndata }+ bopts = balancingopts_ (inputopts_ asOpts)+ isbalanceassignment = mixedamt==missingmixedamt && isJust assertion+ -- Balance the transaction in context of the whole journal,+ -- filling any balance assignment, and checking all the journal's balance assertions.+ etxn = balanceTransactionInJournal dummytxn asJournal bopts++ case etxn of+ Left err -> do+ liftIO (hPutStrLn stderr err)+ transactionWizard previnput state (GetAmount txndata account : stack)+ Right balanced -> do+ -- For a balance-assignment posting, remember the amount the balancer+ -- inferred, so the next posting's default can use it.+ let minferredamterredamt+ | isbalanceassignment = pamount <$> tpostings balanced `atMay` length asPostings+ | otherwise = Nothing+ state' = state{asPostings=asPostings++[p]+ ,asInferredAmounts=asInferredAmounts++[minferredamterredamt]+ ,asArgs=drop 1 asArgs}+ transactionWizard previnput{prevAmountAndCmnt=prevAmountAndCmnt'} state' (GetPosting txndata (Just posting) : stack)+ Nothing -> transactionWizard previnput state (drop 1 stack)++ Confirm t -> do+ let txt = showTransactionWithLayout (layoutFromRawOpts $ rawopts_ asOpts) t+ output $ T.unpack txt+ -- Check that the journal will be readable with this added, as the next read will check it+ -- (lots, strict checks, etc). This can take a while with a large journal, so it runs+ -- in the background while the user reads the entry and answers.+ (waitForCheck, cancelCheck) <- liftIO $ startJournalCheck asOpts (journalFilePath asJournal) txt+ y <- let def = "y" in+ retryMsg "Please enter y or n." $+ parser ((fmap (\c -> if c == '<' then Nothing else Just c)) . headMay . map toLower . strip) $+ defaultTo' def $ nonEmpty $+ line $ green' $ printf "Save this transaction to the journal ?%s: " (showDefault def)+ case y of+ Just 'y' -> liftIO waitForCheck >>= \case+ Right j -> return (t, j)+ Left err -> do+ -- Not saved; back up one step, as with <, to let the user correct it.+ liftIO $ hPutStrLn stderr $ "\n" ++ err ++ "\nThis transaction can't be saved, please correct it."+ transactionWizard previnput state (drop 2 stack)+ Just _ -> liftIO cancelCheck >> throw RestartTransactionException+ Nothing -> liftIO cancelCheck >> transactionWizard previnput state (drop 2 stack)+ where+ replaceNthOrAppend n newElem xs = take n xs ++ [newElem] ++ drop (n + 1) xs++-- | Interact with the user to get a transaction date (accepting smart dates), maybe followed by a " (CODE)". +-- Returns the date and the code, or nothing if the input was "<".+dateWizard :: PrevInput -> AddState -> Wizard Haskeline (Maybe (EFDay, Text))+dateWizard PrevInput{..} AddState{..} = do+ let def = headDef (T.unpack $ showDate asDefDate) asArgs+ retryMsg "A valid hledger smart date is required. Eg: 2022-08-30, 8/30, 30, yesterday." $+ parser (parseSmartDateAndCode asToday) $+ withCompletion (dateCompleter def) $+ defaultTo' def $ nonEmpty $+ maybeExit $+ -- maybeShowHelp $+ linePrewritten (green' $ printf "Date%s: " (showDefault def)) (fromMaybe "" prevDateAndCode) ""+ where+ parseSmartDateAndCode refdate s = if s == "<" then return Nothing else either (const Nothing) (\(d,c) -> return $ Just (fixSmartDate refdate d, c)) edc+ where+ edc = runParser (dateandcodep <* eof) "" $ T.pack $ lowercase s+ dateandcodep :: SimpleTextParser (SmartDate, Text)+ dateandcodep = do+ d <- smartdate+ c <- optional codep+ skipNonNewlineSpaces+ eof+ return (d, fromMaybe "" c)+ -- defday = fixSmartDate today $ fromparse $ (parse smartdate "" . lowercase) defdate+ -- datestr = showDate $ fixSmartDate defday smtdate++-- | Interact with the user to get a transaction description, maybe followed by a "; COMMENT".+-- Returns the possibly empty description and comment, or nothing if the input is "<".+descriptionWizard :: PrevInput -> AddState -> Wizard Haskeline (Maybe (Text, Text))+descriptionWizard PrevInput{..} AddState{..} = do+ let def = headDef "" asArgs+ s <- withCompletion (descriptionCompleter asJournal def) $+ defaultTo' def $ nonEmpty $+ linePrewritten (green' $ printf "Description%s: " (showDefault def)) (fromMaybe "" prevDescAndCmnt) ""+ if s == "<"+ then return Nothing+ else do+ let (desc,comment) = (T.pack $ strip a, T.pack $ strip $ dropWhile (==';') b) where (a,b) = break (==';') s+ return $ Just (desc, comment)++-- | Interact with the user to get an account name, possibly enclosed in "()" or "[]".+-- Returns the account name, or nothing if the input is "<".+accountWizard :: PrevInput -> AddState -> Wizard Haskeline (Maybe String)+accountWizard PrevInput{..} AddState{..} = do+ let pnum = length asPostings + 1+ historicalp = fmap ((!! (pnum - 1)) . (++ (repeat nullposting)) . tpostings) asSimilarTransaction+ historicalacct = case historicalp of Just p -> showAccountName Nothing (preal p) (paccount p)+ Nothing -> ""+ def = headDef (T.unpack historicalacct) asArgs+ endmsg | canfinish && null def = " (or . or enter to finish this transaction)"+ | canfinish = " (or . to finish this transaction)"+ | otherwise = ""+ retryMsg "A valid hledger account name is required. Eg: assets:cash, expenses:food:eating out." $+ parser (parseAccountOrDotOrNull def canfinish) $+ withCompletion (accountCompleter asJournal def) $+ defaultTo' def $ -- nonEmpty $+ linePrewritten (green' $ printf "Account %d%s%s: " pnum (endmsg::String) (showDefault def)) (fromMaybe "" $ prevAccount `atMay` length asPostings) ""+ where+ canfinish = not (null asPostings) && postingsAreBalanced asJournal asPostings+ parseAccountOrDotOrNull :: String -> Bool -> String -> Maybe (Maybe String)+ parseAccountOrDotOrNull _ _ "<" = dbg' $ Just Nothing+ parseAccountOrDotOrNull _ _ "." = dbg' $ Just $ Just "." -- . always signals end of txn+ parseAccountOrDotOrNull "" True "" = dbg' $ Just $ Just "" -- when there's no default and txn is balanced, "" also signals end of txn+ parseAccountOrDotOrNull def@(_:_) _ "" = dbg' $ Just $ Just def -- when there's a default, "" means use that+ parseAccountOrDotOrNull _ _ s = dbg' $ fmap (Just . T.unpack) $+ either (const Nothing) validateAccount $+ flip evalState asJournal $ runParserT (accountnamep <* eof) "" (T.pack s) -- otherwise, try to parse the input as an accountname+ where+ validateAccount :: Text -> Maybe Text+ validateAccount t | no_new_accounts_ asOpts && notElem t (journalAccountNamesDeclaredOrImplied asJournal) = Nothing+ | otherwise = Just t+ dbg' = id -- strace++-- | Interact with the user to get an amount and/or a balance assertion, maybe followed by a "; COMMENT".+-- Returns the amount, balance assertion, and/or comment, or nothing if the input is "<".+amountWizard :: PrevInput -> AddState -> Wizard Haskeline (Maybe (Maybe Amount, Maybe BalanceAssertion, Comment))+amountWizard previnput@PrevInput{..} state@AddState{..} = do+ let pnum = length asPostings + 1+ (mhistoricalp,followedhistoricalsofar) =+ case asSimilarTransaction of+ Nothing -> (Nothing,False)+ Just Transaction{tpostings=ps} ->+ ( if length ps >= pnum then Just (ps !! (pnum-1)) else Nothing+ , all sameamount $ zip asPostings ps+ )+ where+ sameamount (p1,p2) = mixedAmountUnstyled (pamount p1) == mixedAmountUnstyled (pamount p2)+ def | (d:_) <- asArgs = d+ | Just hp <- mhistoricalp, followedhistoricalsofar = showamt $ pamount hp+ | pnum > 1 && not (mixedAmountLooksZero balancingamt) = showamt balancingamtfirstcommodity+ | otherwise = ""+ retryMsg "A valid hledger amount is required. Eg: 1, $2, 3 EUR, \"4 red apples\"." $+ parser' parseAmountAndComment $+ withCompletion (amountCompleter def) $+ defaultTo' def $+ nonEmpty $+ linePrewritten (green' $ printf "Amount %d%s: " pnum (showDefault def)) (fromMaybe "" $ prevAmountAndCmnt `atMay` length asPostings) ""+ where+ -- Custom parser that combines with Wizard to use IO via outputLn+ parser' f a = a >>= \input ->+ case f input of+ Left err -> do+ outputLn (customErrorBundlePretty err)+ amountWizard previnput state+ Right res -> pure res+ parseAmountAndComment s = + if s == "<" then Right Nothing else + Just <$> runParser + (evalStateT (amountandcommentp <* eof) nodefcommodityj)+ ""+ (T.pack s)+ nodefcommodityj = asJournal{jparsedefaultcommodity=Nothing}+ amountandcommentp :: JournalParser Identity (Maybe Amount, Maybe BalanceAssertion, Comment)+ amountandcommentp = do+ mamt <- optional amountp+ lift skipNonNewlineSpaces+ massertion <- optional balanceassertionp+ com <- T.pack <$> fromMaybe "" `fmap` optional (char ';' >> many anySingle)+ case rtp (postingcommentp (let (y,_,_) = toGregorian asDefDate in Just y)) (T.cons ';' com) of+ Left err -> fail $ customErrorBundlePretty err+ -- Keep our original comment string from the user to add to the journal+ Right (_, tags, date1', date2') -> return $ (mamt, massertion, (com, tags, date1', date2'))+ balancingamt = maNegate . sumPostings $ filter isReal asPostings'+ where+ -- Postings entered so far, with any amounts from balance assignments filled in+ asPostings' =+ [ case minferredamt of+ Just a -> p{pamount = a}+ Nothing -> p+ | (p, minferredamt) <- zip asPostings (asInferredAmounts ++ repeat Nothing)+ ]+ balancingamtfirstcommodity = mixed . take 1 $ amounts balancingamt+ -- Note, apply the journal's commodity display styles so default+ -- inputs match the journal's format even when summing amounts+ -- that were entered with different or missing styles (#2645).+ -- displayForceDecimalMark ensures that if there are digit group marks,+ -- a decimal mark will also be shown to avoid ambiguity and misparsing (#2656).+ -- will be shown if needed to avoid ambiguity with a digit group mark+ -- NoRounding ensures all significant digits are shown.+ showamt = wbUnpack+ . showMixedAmountB defaultFmt{displayForceDecimalMark=True}+ . styleAmounts (journalCommodityStylesWith NoRounding asJournal)+ . mixedAmountSetPrecision+ -- what should this be ?+ -- 1 maxprecision (show all decimal places or none) ?+ -- 2 maxprecisionwithpoint (show all decimal places or .0 - avoids some but not all confusion with thousands separators) ?+ -- 3 canonical precision for this commodity in the journal ?+ -- 4 maximum precision entered so far in this transaction ?+ -- 5 3 or 4, whichever would show the most decimal places ?+ -- I think 1 or 4, whichever would show the most decimal places+ NaturalPrecision+ --+ -- let -- (amt,comment) = (strip a, strip $ dropWhile (==';') b) where (a,b) = break (==';') amtcmt+ -- a = fromparse $ runParser (amountp <|> return missingamt) (jparsestate asJournal) "" amt+ -- awithoutjps = fromparse $ runParser (amountp <|> return missingamt) mempty "" amt+ -- defamtaccepted = Just (showAmount a) == mdefamt+ -- as2 = if defamtaccepted then as1 else as1{asHistoricalPostings=Nothing}+ -- mdefaultcommodityapplied = if acommodity a == acommodity awithoutjps then Nothing else Just $ acommodity a+ -- when (isJust mdefaultcommodityapplied) $+ -- liftIO $ hPutStrLn stderr $ printf "using default commodity (%s)" (fromJust mdefaultcommodityapplied)++-- Completion helpers++dateCompleter :: String -> CompletionFunc IO+dateCompleter = completer ["today","tomorrow","yesterday"]++-- Offer payees declared, payees used, or full descriptions used.+descriptionCompleter :: Journal -> String -> CompletionFunc IO+descriptionCompleter j = completer (map T.unpack $ nub $ journalPayeesDeclaredOrUsed j ++ journalDescriptions j)++accountCompleter :: Journal -> String -> CompletionFunc IO+accountCompleter j = completer (map T.unpack $ journalAccountNamesDeclaredOrImplied j)++amountCompleter :: String -> CompletionFunc IO+amountCompleter = completer []++-- | Generate a haskeline completion function from the given+-- completions and default, that case insensitively completes with+-- prefix matches, or infix matches above a minimum length, or+-- completes the null string with the default.+completer :: [String] -> String -> CompletionFunc IO+completer completions def = completeWord Nothing "" completionsFor+ where+ simpleCompletion' s = (simpleCompletion s){isFinished=False}+ completionsFor "" = return [simpleCompletion' def]+ completionsFor i = return (map simpleCompletion' ciprefixmatches)+ where+ ciprefixmatches = [c | c <- completions, i `isPrefixOf` c]+ -- mixed-case completions require haskeline > 0.7.1.2+ -- ciprefixmatches = [c | c <- completions, lowercase i `isPrefixOf` lowercase c]++--------------------------------------------------------------------------------++-- utilities++maybeExit = parser (\s -> if s == "." then throw UnexpectedEOF else Just s)++-- maybeShowHelp :: Wizard Haskeline String -> Wizard Haskeline String+-- maybeShowHelp wizard = maybe (liftIO showHelp >> wizard) return $+-- parser (\s -> if s=="?" then Nothing else Just s) wizard++defaultTo' = flip defaultTo++withCompletion f = withSettings (setComplete f defaultSettings)++showDefault "" = ""+showDefault s = " [" ++ s ++ "]"++-- | Balance and check a transaction with awareness of the whole journal it will be added to.+-- This means add it to the journal, balance it, calculate any balance assignments in it,+-- then maybe check all the journal's balance assertions,+-- then return the now fully balanced and checked transaction, or an error message.+balanceTransactionInJournal :: Transaction -> Journal -> BalancingOpts -> Either String Transaction+balanceTransactionInJournal t j bopts = do+ -- Add the transaction at the end of the journal, as the add command will.+ let j' = j{jtxns = jtxns j ++ [t]}+ -- Use the journal's account types so the balancer can identify+ -- Gain postings and exclude them from balancing (#2572).+ bopts' = bopts{account_types_ = jaccounttypes j}+ -- Try to balance and check the whole journal, and specifically the new transaction.+ Journal{jtxns=ts} <- journalBalanceTransactions bopts' j'+ -- Extract the balanced & checked transaction.+ maybe+ (Left "balanceTransactionInJournal: unexpected empty journal") -- should not happen+ Right+ (lastMay ts)++postingsAreBalanced :: Journal -> [Posting] -> Bool+postingsAreBalanced j ps = isRight $ balanceSingleTransaction bopts nulltransaction{tpostings = ps}+ where bopts = defbalancingopts{account_types_ = jaccounttypes j}++-- | In a background thread, check that the journal will be readable with this text+-- appended to this file, as the next read with these options will check it (see 'journalCheckChange').+-- Returns an action that waits for the result (the journal as that read gives it, or its error message),+-- and an action that cancels the check.+startJournalCheck :: CliOpts -> FilePath -> Text -> IO (IO (Either String Journal), IO ())+startJournalCheck opts f txt = do+ result <- newEmptyMVar+ tid <- forkIO $ do+ -- Any exception becomes an error message, so the wait always ends.+ r <- E.try $ do+ newtxt <- journalFileTextAfterAppends f [txt]+ evaluate =<< runExceptT (journalCheckChange opts f newtxt)+ putMVar result $ either (\(e::SomeException) -> Left $ show e) id r+ return (readMVar result, killThread tid)++-- | Append this transaction to the journal's file and transaction list.+journalAddTransaction :: Journal -> CliOpts -> Transaction -> IO Journal+journalAddTransaction j@Journal{jtxns=ts} opts t = do+ let f = journalFilePath j+ showtxn = showTransactionWithLayout (layoutFromRawOpts $ rawopts_ opts)+ appendToJournalFileOrStdout f $ showtxn t+ -- unelided shows all amounts explicitly, in case there's a price, cf #283+ when (debug_ opts > 0) $ do+ putStrLn $ printf "\nAdded transaction to %s:" f+ TL.putStrLn =<< registerFromString (showtxn t)+ return j{jtxns=ts++[t]}++-- | Append a string, typically one or more transactions, to a journal+-- file, or if the file is "-", dump it to stdout.+-- Tries to avoid adding excess whitespace.+-- Also, this also does a quick append test before the actual append,+-- to avoid data loss in case of filesystems with broken append (see ensureFilesystemCanAppend).+--+-- XXX This writes unix line endings (\n), some at least,+-- even if the file uses dos line endings (\r\n), which could leave+-- mixed line endings in the file. See also writeFileWithBackupIfChanged.+--+appendToJournalFileOrStdout :: FilePath -> Text -> IO ()+appendToJournalFileOrStdout f s+ | f == "-" = T.putStr $ appendedText s+ | otherwise = do+ ensureJournalFileExists f+ let dir = takeDirectory f+ ok <- ensureFilesystemCanAppend dir+ unless ok $ error' $ unlines+ [ "Cannot safely append to journal; aborting to avoid data loss."+ , "The filesystem at " <> show dir <> " does not honor O_APPEND."+ , "This can happen eg with FAT/exFAT and Android shared-storage / FUSE mounts."+ , "Please move the journal file to a reliable filesystem and try again."+ ]+ appendFile f $ T.unpack $ appendedText s++-- | The whole text a journal file will have after 'appendToJournalFileOrStdout'+-- appends each of these texts to it: its current text (none if it doesn't exist yet),+-- then the appended texts. Useful for checking appends before doing them (see 'journalCheckChange').+journalFileTextAfterAppends :: FilePath -> [Text] -> IO Text+journalFileTextAfterAppends f ss = do+ old <- doesFileExist f >>= \e -> if e then readFilePortably f else pure ""+ return $ old <> foldMap appendedText ss++-- | The text that 'appendToJournalFileOrStdout' actually appends:+-- the given text, after a blank line, ending with one newline.+appendedText :: Text -> Text+appendedText s = "\n" <> ensureOneNewlineTerminated s++-- | Replace a string's 0 or more terminating newlines with exactly one.+ensureOneNewlineTerminated :: Text -> Text+ensureOneNewlineTerminated = (<>"\n") . T.dropWhileEnd (=='\n')++-- | Convert a string of journal data into a register report.+registerFromString :: T.Text -> IO TL.Text+registerFromString s = do+ j <- readJournal'' s+ return . postingsReportAsText opts $ postingsReport rspec j+ where+ ropts = defreportopts{empty_=True}+ rspec = defreportspec{_rsReportOpts=ropts}+ opts = defcliopts{reportspec_=rspec}++capitalize :: String -> String+capitalize "" = ""+capitalize (c:cs) = toUpper c : cs
+ Hledger/Cli/Commands/Add.txt view
@@ -0,0 +1,101 @@+add++Add new transactions to a journal file, with interactive prompting.++Flags:+ --no-new-accounts don't allow creating new accounts+ --layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 - right-align amounts, as in hledger 1+ COL - align decimal marks at column COL+ (default: 53)++Many hledger users edit their journals directly with a text editor, or+generate them from CSV. For more interactive data entry, there is the+add command, which prompts interactively on the console for new+transactions, and appends them to the main journal file (which should be+in journal format). Existing transactions are not changed. This is one+of the few hledger commands that writes to the journal file (see also+import).++To use it, just run hledger add and follow the prompts. You can add as+many transactions as you like; when you are finished, enter . or press+control-d or control-c to exit.++Features:++- add tries to provide useful defaults, using the most similar (by+ description) and nearest-dated transaction (filtered by the query, if+ any) as a template.+- You can also set the initial defaults with command line arguments.+- Readline-style edit keys can be used during data entry.+- The tab key will auto-complete whenever possible - accounts,+ payees/descriptions, dates (yesterday, today, tomorrow). If the input+ area is empty, it will insert the default value.+- A parenthesised transaction code may be entered following a date.+- Comments and tags may be entered following a description or amount.+- If you make a mistake, enter < at any prompt to go one step backward.+- Before saving a transaction, add checks that the journal will still be+ readable with it added, as the next read with the same options will+ check it (eg balance assertions must pass, lots must be valid, and+ with --strict, the strict checks must pass). If not, it shows the+ error and goes one step backward, so you can correct the entry. (With+ a large journal this check may take a moment; it runs while you are+ deciding whether to save.)+- Input prompts are displayed in a different colour when the terminal+ supports it.++Notes:++- If you enter a number with no commodity symbol, and you have declared+ a default commodity with a D directive, you might expect add to add+ this symbol for you. It does not do this; we assume that if you are+ using a D directive you prefer not to see the commodity symbol+ repeated on amounts in the journal.+- add creates entries in journal format; it won't work with timeclock or+ timedot files.+- There is a known issue on Windows if this hledger version is built+ from stackage: the prompts will show ANSI junk instead of colours+ (#2410). You can avoid this by using official hledger release binaries+ or by building it with haskeline >=0.8.4; or by running add with+ --color=no, perhaps configured in your config file.++Examples:++- Record new transactions, saving to the default journal file:++ hledger add++- Add transactions to 2024.journal, but also load 2023.journal for+ completions:++ hledger add --file 2024.journal --file 2023.journal++- Provide answers for the first four prompts:++ hledger add today 'best buy' expenses:supplies '$20'++There is a detailed tutorial at https://hledger.org/add.html.++add and balance assertions++You can add a balance assertion by writing AMOUNT = BALANCE when asked+for an amount. Eg 100 = 500.++Also, each time you enter a new amount, hledger re-checks all balance+assertions in the journal and rejects the new amount if it would make+any of them fail. You can run add with -I or --ignore-assertions to+disable balance assertion checking.++add and balance assignments++Adding a new balance assignment+When entering a posting amount, you can write a = BALANCEAMOUNT balance+assignment (or ==, =*, ==*) instead. The posting amount required to+produce this balance will be calculated automatically. (Since 1.51)++Adding a posting dated before an existing balance assignment+add won't let you add a posting dated earlier than an existing balance+assignment in that account. (Because it calculates balance assignments+only once at startup, converting them to assertions, so adding the new+amount causes an assertion failure.) To work around this, run add with+balance assertions ignored: hledger add -I.
+ Hledger/Cli/Commands/Aregister.hs view
@@ -0,0 +1,359 @@+{-|++The @aregister@ command lists a single account's transactions,+like the account register in hledger-ui and hledger-web,+and unlike the register command which lists postings across multiple accounts.++-}++{-# LANGUAGE CPP #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Aregister (+ aregistermode+ ,aregister+ -- ,showPostingWithBalanceForVty+ ,tests_Aregister+) where++import Data.Default (def)+import Data.List (find, nub)+import Data.Maybe (fromMaybe)+import Data.Text (Text)+import Data.Foldable (for_)+import Data.Map qualified as Map+import Data.Text qualified as T+import Data.Text.Lazy qualified as TL+import Data.Text.Lazy.Builder qualified as TB+import Control.Monad (unless, when)+import Safe (readMay)+import System.Console.CmdArgs.Explicit (flagNone, flagReq)+import System.IO qualified as IO+import Text.Blaze.Html5 ((!), preEscapedToHtml)+import Text.Blaze.Html5 qualified as H+import Text.Blaze.Html5.Attributes qualified as A+import Text.Tabular.AsciiWide hiding (render)++import Hledger+import Hledger.Cli.Chart (accountTransactionsReportAsChart, chartFlag, chartRequested, writeChart)+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils+import Hledger.Write.Csv (CSV, printCSV, printTSV)+import Hledger.Write.Html (formatRow, formatTitle, htmlAsLazyText, nl, toHtml)+import Hledger.Write.Html.Attribute (tableStylesheet)+import Hledger.Write.Ods (printFods)+import Hledger.Write.Spreadsheet qualified as Spr++aregistermode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Aregister.txt")+ ([+ flagNone ["txn-dates"] (setboolopt "txn-dates") + "filter strictly by transaction date, not posting date. Warning: this can show a wrong running balance."+ ,flagNone ["no-elide"] (setboolopt "no-elide") "don't show only 2 commodities per amount"+ ,flagNone ["cumulative"] (setboolopt "cumulative")+ (accumprefix ++ "show running total from report start date")+ ,flagNone ["historical","H"] (setboolopt "historical")+ (accumprefix ++ "show historical running total/balance (includes postings before report start date) (default)")+ ,flagNone ["average","A"] (setboolopt "average")+ "show running average of transaction amounts instead of balance (implies --empty and, unless -H is used, --cumulative)"+ ,flagNone ["related","r"] (setboolopt "related") "show the other accounts in each transaction (default)"+ ,flagNone ["matched"] (setboolopt "matched") "show the matched accounts (this account or its subaccounts) instead"+ ,flagNone ["invert"] (setboolopt "invert") "display all amounts with reversed sign"+ ,flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "omit N leading account name parts"+ ,flagReq ["heading"] (\s opts -> Right $ setopt "heading" s opts) "YN"+ "show heading row above table: yes (default) or no"+ ,flagReq ["width","w"] (\s opts -> Right $ setopt "width" s opts) "N"+ ("set output width (default: " +++#ifdef mingw32_HOST_OS+ show defaultWidth+#else+ "terminal width"+#endif+ ++ "). -wN,M sets description width as well."+ )+ ,flagNone ["align-all"] (setboolopt "align-all") "guarantee alignment across all lines (slower)"+ ,outputFormatFlag ["txt","html","csv","tsv","json","svg"]+ ,outputFileFlag+ ,outputViewFlag+ ,chartFlag+ ])+ cligeneralflagsgroups1+ hiddenflags+ ([], Just $ argsFlag "ACCTPAT [QUERY]")+ where+ accumprefix = "accumulation mode: "++-- based on Hledger.UI.RegisterScreen:++-- | Print an account register report for a specified account.+aregister :: CliOpts -> Journal -> IO ()+aregister opts@CliOpts{rawopts_=rawopts,reportspec_=rspec} j = do+ -- the first argument specifies the account, any remaining arguments are a filter query+ let help = "aregister needs an ACCTPAT argument to select an account"+ (apat,querystr) <- case listofstringopt "args" rawopts of+ [] -> error' $ help <> ".\nPlease provide an account name or a (case-insensitive, infix, regexp) pattern."+ (a:as) -> return (a, map T.pack as)+ let+ -- keep synced with findMatchedByArgument's matching+ acct = fromMaybe (error' $ help <> ", but " ++ show apat++" did not match any account.") -- PARTIAL:+ . firstMatch $ journalAccountNamesDeclaredOrImplied j+ firstMatch = case toRegexCI $ T.pack apat of+ Right re -> find (regexMatchText re)+ Left _ -> const Nothing+ -- gather report options+ inclusive = True -- tree_ ropts+ thisacctq = Acct $ (if inclusive then accountNameToAccountRegex else accountNameToAccountOnlyRegex) acct+ ropts = _rsReportOpts rspec+ ropts' = ropts {+ -- ignore any depth limit, as in postingsReport; allows register's total to match balance reports (cf #1468)+ depth_=DepthSpec Nothing []+ -- historical by default, or cumulative with --average (averaging over the report period, like register)+ , balanceaccum_ =+ case balanceaccum_ ropts of+ PerPeriod | average_ ropts -> Cumulative+ | otherwise -> Historical+ ba -> ba+ -- with --average, show all transactions, since they all affect the average+ , empty_ = empty_ ropts || average_ ropts+ , querystring_ = querystr+ }+ wd = whichDate ropts'+ -- and regenerate the ReportSpec, making sure to use the above+ rspec' <- either fail return $ updateReportSpec ropts' rspec+ let+ -- run the report+ -- TODO: need to also pass the queries so we can choose which date to render - move them into the report ?+ items = accountTransactionsReport rspec' j thisacctq+ items' =+ styleAmounts (journalCommodityStylesWith HardRounding j) $+ (if empty_ ropts' then id else filter (not . mixedAmountLooksZero . fifth6)) $+ reverse items+ -- select renderer+ render | fmt=="txt" = accountTransactionsReportAsText opts (_rsQuery rspec') thisacctq+ | fmt=="html" = accountTransactionsReportAsHTML opts (_rsQuery rspec') thisacctq+ | fmt=="csv" = printCSV . accountTransactionsReportAsCsv opts hd wd (_rsQuery rspec') thisacctq+ | fmt=="tsv" = printTSV . accountTransactionsReportAsCsv opts hd wd (_rsQuery rspec') thisacctq+ | fmt=="fods" =+ printFods IO.localeEncoding . Map.singleton "Aregister" .+ (,) (1,0) .+ accountTransactionsReportAsSpreadsheet opts oneLineNoCostFmt hd wd (_rsQuery rspec') thisacctq+ | fmt=="json" = toJsonText+ | otherwise = error' $ unsupportedOutputFormatError fmt -- PARTIAL:+ where+ hd = headingopt opts+ fmt = outputFormatFromOpts opts++ if chartRequested opts+ then writeChart opts (Just $ render items') $+ accountTransactionsReportAsChart (journalAccountType j) (accountTransactionsReportTitle opts (_rsQuery rspec') thisacctq) acct+ (transactionRegisterDate wd (_rsQuery rspec') thisacctq) items'+ else writeOutputLazyText opts $ render items'++accountTransactionsReportAsCsv ::+ CliOpts -> Bool -> WhichDate -> Query -> Query -> AccountTransactionsReport -> CSV+accountTransactionsReportAsCsv opts hd wd reportq thisacctq atr =+ case accountTransactionsReportAsSpreadsheet opts machineFmt hd wd reportq thisacctq atr of+ [] -> []+ rows@(headerrow : _) -> Spr.rawTableContent $ titleRows headerrow ++ rows+ where+ titleText = effectiveTitle (_rsReportOpts $ reportspec_ opts) ""+ titleRows headerrow+ | T.null titleText = []+ | otherwise = [Spr.horizontalSpan headerrow (Spr.headerCell titleText)]++accountTransactionsReportAsSpreadsheet ::+ CliOpts -> AmountFormat -> Bool ->+ WhichDate -> Query -> Query -> AccountTransactionsReport ->+ [[Spr.Cell Spr.NumLines Text]]+accountTransactionsReportAsSpreadsheet opts fmt hd wd reportq thisacctq is =+ optional hd+ [Spr.addHeaderBorders $ map Spr.headerCell $+ ["txnidx","date","code","description","otheraccounts","amount","balance"]]+ +++ map (accountTransactionsReportItemAsRecord opts fmt True wd reportq thisacctq) is++accountTransactionsReportItemAsRecord ::+ CliOpts -> AmountFormat -> Bool ->+ WhichDate -> Query -> Query -> AccountTransactionsReportItem ->+ [Spr.Cell Spr.NumLines Text]+accountTransactionsReportItemAsRecord+ opts fmt internals wd reportq thisacctq+ item@(t@Transaction{tindex,tcode,tdescription}, _, _issplit, _, change, balance)+ = (optional internals [Spr.integerCell tindex]) +++ date :+ (optional internals [cell tcode]) +++ [cell tdescription,+ cell $ T.intercalate ", " $ map dropAcct $ itemAccountNames opts thisacctq item,+ amountCell change,+ amountCell balance]+ where+ dropAcct = accountNameDrop (fromMaybe 0 $ readMay =<< maybestringopt "drop" (rawopts_ opts))+ cell = Spr.defaultCell+ date =+ (Spr.defaultCell $ showDate $+ transactionRegisterDate wd reportq thisacctq t)+ {Spr.cellType = Spr.TypeDate}+ amountCell amt =+ wbToText <$> Spr.cellFromMixedAmount fmt (Spr.Class "amount", amt)++-- | Render a register report as a HTML snippet.+accountTransactionsReportAsHTML :: CliOpts -> Query -> Query -> AccountTransactionsReport -> TL.Text+accountTransactionsReportAsHTML copts reportq thisacctq items =+ (<>"\n") $ htmlAsLazyText $ do+ -- the builtin styles, then the optional user stylesheet so it can override them+ H.style $ preEscapedToHtml tableStylesheet+ nl+ H.link ! A.rel "stylesheet" ! A.href "hledger.css"+ nl+ let title = accountTransactionsReportTitle copts reportq thisacctq+ unless (T.null title) $ formatTitle title+ H.table $ do+ nl+ when (headingopt copts) $ do+ H.thead $ H.tr $ do+ H.th "date"+ H.th "description"+ H.th "otheraccounts"+ H.th "amount"+ H.th "balance"+ nl+ H.tbody $ for_ items $+ formatRow . map (fmap toHtml) .+ accountTransactionsReportItemAsRecord copts+ oneLineNoCostFmt False+ (whichDate $ _rsReportOpts $ reportspec_ copts)+ reportq thisacctq++-- | Render a register report as plain text suitable for console output.+accountTransactionsReportAsText :: CliOpts -> Query -> Query -> AccountTransactionsReport -> TL.Text+accountTransactionsReportAsText copts reportq thisacctq items = TB.toLazyText $+ titleBuilder+ <>+ postingsOrTransactionsReportAsText alignAll copts itemAsText itemamt itembal items+ where+ alignAll = boolopt "align-all" $ rawopts_ copts+ itemAsText = accountTransactionsReportItemAsText copts reportq thisacctq+ itemamt (_,_,_,_,a,_) = a+ itembal (_,_,_,_,_,a) = a++ title = accountTransactionsReportTitle copts reportq thisacctq+ titleBuilder | T.null title = mempty+ | otherwise = TB.fromText title <> TB.singleton '\n'++-- | The heading for an account transactions report: a description of the+-- account shown, or --title's value if that was provided (possibly empty).+-- Also empty when --heading=no.+accountTransactionsReportTitle :: CliOpts -> Query -> Query -> Text+accountTransactionsReportTitle copts reportq thisacctq+ | not (headingopt copts) = ""+ | otherwise = effectiveTitle (_rsReportOpts $ reportspec_ copts) defaultTitle+ where+ -- show a heading indicating which account was picked, which can be confusing otherwise+ defaultTitle = maybe "" (\s -> T.concat ["Transactions in ", s, " and subaccounts", qmsg, ":"]) macct+ where+ -- XXX temporary hack ? recover the account name from the query+ macct = case filterQuery queryIsAcct thisacctq of+ Acct r -> Just . T.drop 1 . T.dropEnd 5 $ reString r -- Acct "^JS:expenses(:|$)"+ _ -> Nothing -- shouldn't happen+ -- show a hint in the title when results are restricted by an extra query (other than depth or date or date2)+ qmsg = if hasextraquery then " (matching query)" else ""+ where+ hasextraquery =+ length (querystring_ $ _rsReportOpts $ reportspec_ copts) > 1+ && not (queryIsNull $ filterQuery (not.(\q->queryIsDepth q || queryIsDateOrDate2 q)) reportq)++headingopt :: CliOpts -> Bool+headingopt = fromMaybe True . maybeynopt "heading" . rawopts_++-- | Should the account column show the matched accounts (--matched) rather than+-- the other accounts in each transaction (-r/--related, the default) ?+-- The last of these flags wins.+matchedopt :: CliOpts -> Bool+matchedopt = fromMaybe False . choiceopt parse . rawopts_+ where parse s = lookup s [("matched", True), ("related", False)]++-- | The account names to show for an account register report item:+-- by default, the other accounts involved in the transaction;+-- with --matched, the accounts matched by the account query+-- (this account or its subaccounts), among the postings selected by any extra query.+itemAccountNames :: CliOpts -> Query -> AccountTransactionsReportItem -> [AccountName]+itemAccountNames opts thisacctq (_, tacct, _, otheraccts, _, _)+ | matchedopt opts = nub . map paccount . filter (matchesPosting thisacctq) $ tpostings tacct+ | otherwise = nub otheraccts++optional :: (Monoid p) => Bool -> p -> p+optional b x = if b then x else mempty+++-- | Render one account register report line item as plain text. Layout is like so:+-- @+-- <---------------- width (specified, terminal width, or 80) -------------------->+-- date (10) description other accounts amount (12) balance (12)+-- DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA+-- @+-- If description's width is specified, account will use the remaining space.+-- Otherwise, description and account divide up the space equally.+--+-- Returns a string which can be multi-line, eg if the running balance+-- has multiple commodities.+--+accountTransactionsReportItemAsText :: CliOpts -> Query -> Query -> Int -> Int+ -> (AccountTransactionsReportItem, [WideBuilder], [WideBuilder])+ -> TB.Builder+accountTransactionsReportItemAsText+ copts@CliOpts{reportspec_=ReportSpec{_rsReportOpts=ropts}}+ reportq thisacctq preferredamtwidth preferredbalwidth+ (item@(t@Transaction{tdescription}, _, _issplit, _, _, _), amt, bal) =+ -- Transaction -- the transaction, unmodified+ -- Transaction -- the transaction, as seen from the current account+ -- Bool -- is this a split (more than one posting to other accounts) ?+ -- [AccountName] -- the other account(s), if any+ -- MixedAmount -- the amount posted to the current account(s) (or total amount posted)+ -- MixedAmount -- the register's running total or the current account(s)'s historical balance, after this transaction+ table <> TB.singleton '\n'+ where+ dropAcct = accountNameDrop (fromMaybe 0 $ readMay =<< maybestringopt "drop" (rawopts_ copts))+ table = renderRowB def{tableBorders=False, borderSpaces=False} . Group NoLine $ map Header+ [ textCell TopLeft $ fitText (Just datewidth) (Just datewidth) True True date+ , spacerCell+ , textCell TopLeft $ fitText (Just descwidth) (Just descwidth) True True tdescription+ , spacerCell2+ , textCell TopLeft $ fitText (Just acctwidth) (Just acctwidth) True True accts+ , spacerCell2+ , Cell TopRight $ map (pad amtwidth) amt+ , spacerCell2+ , Cell BottomRight $ map (pad balwidth) bal+ ]+ spacerCell = Cell BottomLeft [WideBuilder (TB.singleton ' ') 1]+ spacerCell2 = Cell BottomLeft [WideBuilder (TB.fromString " ") 2]+ pad fullwidth amt1 = WideBuilder (TB.fromText $ T.replicate w " ") w <> amt1+ where w = fullwidth - wbWidth amt1+ -- calculate widths+ (totalwidth,mdescwidth) = registerWidthsFromOpts copts+ (datewidth, date) = (10, showDate $ transactionRegisterDate wd reportq thisacctq t)+ where wd = whichDate ropts+ (amtwidth, balwidth)+ | shortfall <= 0 = (preferredamtwidth, preferredbalwidth)+ | otherwise = (adjustedamtwidth, adjustedbalwidth)+ where+ mincolwidth = 2 -- columns always show at least an ellipsis+ maxamtswidth = max 0 (totalwidth - (datewidth + 1 + mincolwidth + 2 + mincolwidth + 2 + 2))+ shortfall = (preferredamtwidth + preferredbalwidth) - maxamtswidth+ amtwidthproportion = fromIntegral preferredamtwidth `divideSafe` fromIntegral (preferredamtwidth + preferredbalwidth)+ adjustedamtwidth = round $ amtwidthproportion * fromIntegral maxamtswidth+ adjustedbalwidth = maxamtswidth - adjustedamtwidth++ remaining = totalwidth - (datewidth + 1 + 2 + amtwidth + 2 + balwidth)+ (descwidth, acctwidth) = (w, remaining - 2 - w)+ where w = fromMaybe ((remaining - 2) `div` 2) mdescwidth++ accts = T.intercalate ", " . map (dropAcct . accountSummarisedName) $ itemAccountNames copts thisacctq item++-- tests++tests_Aregister = testGroup "Aregister" [++ ]
+ Hledger/Cli/Commands/Aregister.txt view
@@ -0,0 +1,151 @@+aregister++(areg)++Show the transactions and running balances in one account, with one+entry per transaction.++Flags:+ --txn-dates filter strictly by transaction date, not posting+ date. Warning: this can show a wrong running+ balance.+ --no-elide don't show only 2 commodities per amount+ --cumulative accumulation mode: show running total from report+ start date+ -H --historical accumulation mode: show historical running+ total/balance (includes postings before report+ start date) (default)+ -A --average show running average of transaction amounts+ instead of balance (implies --empty and, unless -H+ is used, --cumulative)+ -r --related show the other accounts in each transaction+ (default)+ --matched show the matched accounts (this account or its+ subaccounts) instead+ --invert display all amounts with reversed sign+ --drop=N omit N leading account name parts+ --heading=YN show heading row above table: yes (default) or no+ -w --width=N set output width (default: terminal width). -wN,M+ sets description width as well.+ --align-all guarantee alignment across all lines (slower)+ -O --output-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ --view write output to FILE, or to view.FMT in hledger's+ cache directory, and open it in the system's+ default viewer for its format (eg a web browser for+ html). The default format is html.+ --chart[=net,SCALE] show a chart: instead of the table (txt), above+ it (html), or as data (csv, tsv, json). net: also+ draw the net total (a line, or marks in text+ charts). SCALE: the amount that fills the chart (eg+ 1000 or 1000 USD; one per commodity), for+ comparable charts.++aregister shows the overall transactions affecting a particular account+(and any subaccounts). Each report line represents one transaction in+this account. Transactions before the report start date are included in+the running balance (--historical mode is the default). You can suppress+this behaviour using the --cumulative option.++This is a more "real world", bank-like view than the register command+(which shows individual postings, possibly from multiple accounts, not+necessarily in historical mode). As a quick rule of thumb:++- aregister is best when reconciling real-world asset/liability accounts+- register is best when reviewing individual revenues/expenses.++Note this command's non-standard, and required, first argument; it+specifies the account whose register will be shown. You can write the+account's name, or (to save typing) a case-insensitive infix regular+expression matching the name, which selects the alphabetically first+matched account. (For example, if you have assets:personal checking and+assets:business checking, hledger areg checking would select+assets:business checking.)++Transactions involving subaccounts of this account will also be shown.+aregister ignores depth limits, so its final total will always match a+historical balance report with similar arguments.++Any additional arguments are standard query arguments, which will limit+the transactions shown. Note some queries will disturb the running+balance, causing it to be different from the account's real-world+running balance.++An example: this shows the transactions and historical running balance+during july, in the first account whose name contains "checking":++$ hledger areg checking date:jul++Each aregister line item shows:++- the transaction's date (or the relevant posting's date if different,+ see below)+- the names of all the other account(s) involved in this transaction+ (probably abbreviated)+- the total change to this account's balance from this transaction+- the account's historical running balance after this transaction.++The account column normally shows the other accounts in each transaction+(this is also selectable with -r/--related). With --matched, it shows+the matched accounts instead: this account, or the subaccounts of it+that were posted to. This is useful when the account has subaccounts,+eg:++$ hledger areg expenses --matched++shows which expense categories each transaction touched. Any additional+query arguments also narrow the matched accounts shown. The amounts and+running balance are the same in both modes.++Transactions making a net change of zero are not shown by default; add+the -E/--empty flag to show them.++The -A/--average flag shows the running average change per transaction,+instead of the running balance, so the last number shown is the average+for the whole report period. It implies --empty, since zero-change+transactions also affect the average. Unlike aregister's other reports,+it is not historical by default; add -H to include the transactions+before the report start date in the average. Like register -A, it works+best with a single commodity.++For performance reasons, column widths are chosen based on the first+1000 lines; this means unusually wide values in later lines can cause+visual discontinuities as column widths are adjusted. If you want to+ensure perfect alignment, at the cost of more time and memory, use the+--align-all flag.++By default, aregister shows a heading above the data. However, when+reporting in a language different from English, it is easier to omit+this heading and prepend your own one. For this purpose, use the+--heading=no option.++This command also supports the output destination and output format+options. The output formats supported are txt, csv, tsv, html, fods and+json.++With --chart, or with svg output (-o FILE.svg), it shows a chart of the+account's balance (or running total or average) over time instead. A+text chart has a row per transaction (for a row per period instead, use+a balance report with a report interval and -H). An SVG chart draws the+balance as a line on a time scale. With --chart -O csv (or tsv or json)+it shows the chart's data. See also Balance charts.++aregister and posting dates++aregister always shows one entry (and one date and amount) per+transaction. (With a single commodity, this means line = one+transaction. But multi-commodity amounts will be shown with one line per+commodity.) But sometimes transactions have postings with different+dates. Also, not all of a transaction's postings may be within the+report period. To resolve this, aregister shows the earliest of the+transaction's date and posting dates that is in-period, and the sum of+the in-period postings. In other words it will show a combined line item+with just the earliest date, and the running balance will (temporarily,+until the transaction's last posting) be inaccurate. Use register -H if+you need to see the individual postings.++There is also a --txn-dates flag, which filters strictly by transaction+date, ignoring posting dates. This too can cause an inaccurate running+balance.
+ Hledger/Cli/Commands/Balance.hs view
@@ -0,0 +1,1297 @@+{-|++A ledger-compatible @balance@ command, with additional support for+multi-column reports.++Here is a description/specification for the balance command. See also+"Hledger.Reports" -> \"Balance reports\".+++/Basic balance report/++With no report interval (@--monthly@ etc.), hledger's balance+command emulates ledger's, showing accounts indented according to+hierarchy, along with their total amount posted (including subaccounts).++Here's an example. With @examples/sample.journal@, which defines the following account tree:++@+ assets+ bank+ checking+ saving+ cash+ expenses+ food+ supplies+ income+ gifts+ salary+ liabilities+ debts+@++the basic @balance@ command gives this output:++@+ $ hledger -f sample.journal balance+ $-1 assets+ $1 bank:saving+ $-2 cash+ $2 expenses+ $1 food+ $1 supplies+ $-2 income+ $-1 gifts+ $-1 salary+ $1 liabilities:debts+--------------------+ 0+@++Subaccounts are displayed indented below their parent. Only the account leaf name (the final part) is shown.+(With @--flat@, account names are shown in full and unindented.)++Each account's \"balance\" is the sum of postings in that account and any subaccounts during the report period.+When the report period includes all transactions, this is equivalent to the account's current balance.++The overall total of the highest-level displayed accounts is shown below the line.+(The @--no-total/-N@ flag prevents this.)++/Eliding and omitting/++Accounts which have a zero balance, and no non-zero subaccount+balances, are normally omitted from the report.+(The @--empty/-E@ flag forces such accounts to be displayed.)+Eg, above @checking@ is omitted because it has a zero balance and no subaccounts.++Accounts which have a single subaccount also being displayed, with the same balance,+are normally elided into the subaccount's line.+(The @--no-elide@ flag prevents this.)+Eg, above @bank@ is elided to @bank:saving@ because it has only a+single displayed subaccount (@saving@) and their balance is the same+($1). Similarly, @liabilities@ is elided to @liabilities:debts@.++/Date limiting/++The default report period is that of the whole journal, including all+known transactions. The @--begin\/-b@, @--end\/-e@, @--period\/-p@+options or @date:@/@date2:@ patterns can be used to report only+on transactions before and/or after specified dates.++/Depth limiting/++The @--depth@ option can be used to limit the depth of the balance report.+Eg, to see just the top level accounts (still including their subaccount balances):++@+$ hledger -f sample.journal balance --depth 1+ $-1 assets+ $2 expenses+ $-2 income+ $1 liabilities+--------------------+ 0+@++/Account limiting/++With one or more account pattern arguments, the report is restricted+to accounts whose name matches one of the patterns, plus their parents+and subaccounts. Eg, adding the pattern @o@ to the first example gives:++@+ $ hledger -f sample.journal balance o+ $1 expenses:food+ $-2 income+ $-1 gifts+ $-1 salary+--------------------+ $-1+@++* The @o@ pattern matched @food@ and @income@, so they are shown.++* @food@'s parent (@expenses@) is shown even though the pattern didn't+ match it, to clarify the hierarchy. The usual eliding rules cause it to be elided here.++* @income@'s subaccounts are also shown.++/Multi-column balance report/++hledger's balance command will show multiple columns when a reporting+interval is specified (eg with @--monthly@), one column for each sub-period.++There are three accumulation strategies for multi-column balance report, indicated by+the heading:++* A \"period balance\" (or \"flow\") report (with @--change@, the default) shows the+ change of account balance in each period, which is equivalent to the sum of postings+ in each period. Here, checking's balance increased by 10 in Feb:++ > Change of balance (flow):+ >+ > Jan Feb Mar+ > assets:checking 20 10 -5++* A \"cumulative balance\" report (with @--cumulative@) shows the accumulated ending balance+ across periods, starting from zero at the report's start date.+ Here, 30 is the sum of checking postings during Jan and Feb:++ > Ending balance (cumulative):+ >+ > Jan Feb Mar+ > assets:checking 20 30 25++* A \"historical balance\" report (with @--historical/-H@) also shows ending balances,+ but it includes the starting balance from any postings before the report start date.+ Here, 130 is the balance from all checking postings at the end of Feb, including+ pre-Jan postings which created a starting balance of 100:++ > Ending balance (historical):+ >+ > Jan Feb Mar+ > assets:checking 120 130 125++/Eliding and omitting, 2/++Here's a (imperfect?) specification for the eliding/omitting behaviour:++* Each account is normally displayed on its own line.++* An account less deep than the report's max depth, with just one+interesting subaccount, and the same balance as the subaccount, is+non-interesting, and prefixed to the subaccount's line, unless+@--no-elide@ is in effect.++* An account with a zero inclusive balance and less than two interesting+subaccounts is not displayed at all, unless @--empty@ is in effect.++* Multi-column balance reports show full account names with no eliding+ (like @--flat@). Accounts (and periods) are omitted as described below.++/Which accounts to show in balance reports/++By default:++* single-column: accounts with non-zero balance in report period.+ (With @--flat@: accounts with non-zero balance and postings.)++* change: accounts with postings and non-zero period balance in any period++* cumulative: accounts with non-zero cumulative balance in any period++* historical: accounts with non-zero historical balance in any period++With @-E/--empty@:++* single-column: accounts with postings in report period++* change: accounts with postings in report period++* cumulative: accounts with postings in report period++* historical: accounts with non-zero starting balance ++ accounts with postings in report period++/Which periods (columns) to show in balance reports/++An empty period/column is one where no report account has any postings.+A zero period/column is one where no report account has a non-zero period balance.++Currently,++by default:++* single-column: N/A++* change: all periods within the overall report period,+ except for leading and trailing empty periods++* cumulative: all periods within the overall report period,+ except for leading and trailing empty periods++* historical: all periods within the overall report period,+ except for leading and trailing empty periods++With @-E/--empty@:++* single-column: N/A++* change: all periods within the overall report period++* cumulative: all periods within the overall report period++* historical: all periods within the overall report period++/What to show in empty cells/++An empty periodic balance report cell is one which has no corresponding postings.+An empty cumulative/historical balance report cell is one which has no corresponding+or prior postings, ie the account doesn't exist yet.+Currently, empty cells show 0.++-}++{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Balance (+ -- ** balance command+ balancemode+ ,balance+ -- ** balance output rendering+ ,balanceReportAsText+ ,balanceReportAsCsv+ ,balanceReportAsHtml+ ,balanceReportAsSpreadsheet+ ,balanceReportAsSpreadsheetParts+ ,balanceReportItemAsText+ ,budgetReportAsText+ ,budgetReportAsCsv+ ,budgetReportAsHtml+ ,budgetReportAsSpreadsheet+ ,multiBalanceRowAsCsvText+ ,multiBalanceRowAsText+ ,multiBalanceReportAsText+ ,multiBalanceReportAsCsv+ ,multiBalanceReportAsHtml+ ,multiBalanceReportAsTable+ ,multiBalanceReportAsPartTable+ ,multiBalanceReportTableAsText+ ,multiBalanceReportAsSpreadsheet+ ,multiBalanceReportAsSpreadsheetParts+ ,multiBalanceReportTitle+ ,multiBalanceReportNumHeaderColumns+ ,tidyColumnLabels+ -- ** Tests+ ,tests_Balance+) where++import Control.Arrow (second, (***))+import Control.Monad (guard)+import Data.Decimal (roundTo)+import Data.Default (def)+import Data.Function (on)+import Data.Foldable qualified as Fold+import Data.List.NonEmpty qualified as NonEmpty+import Data.List.NonEmpty (NonEmpty((:|)))+import Data.List (find, transpose)+#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif+import Data.Map qualified as Map+import Data.Set qualified as S+import Data.Maybe (mapMaybe, fromMaybe, maybeToList)+import Data.Tuple (swap)+import Data.Text (Text)+import Data.Text qualified as T+import Data.Text.Lazy qualified as TL+import Data.Text.Lazy.Builder qualified as TB+import Data.Time (fromGregorian)+import System.Console.CmdArgs.Explicit as C (flagNone, flagReq, flagOpt)+import Safe (headMay, maximumMay)+import Text.Tabular.AsciiWide+ (Header(..), Align(..), Properties(..), Cell(..), Table(..), TableOpts(..),+ cellWidth, concatTables, renderColumns, renderRowB, renderTable, renderTableByRowsB, textCell)++import System.IO qualified as IO++import Hledger.Utils.I18n qualified as I18n+import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils+import Hledger.Cli.Anchor (linkParams, composeAnchorWith, dateTerm, removeInacct,+ withLink, setAccountAnchor, setAccountAnchorWith, renderPeriodHeading, amountPhrase)+import Hledger.Cli.Commands.Balance.Internal+import Hledger.Cli.Chart (ChartArg(..), chartArg, balanceChartFlag, chartWidthFlag, chartRequested, writeChart, multiBalanceReportAsChart, balanceReportAsChart)+import Hledger.Write.Csv (CSV, printCSV, printTSV)+import Hledger.Write.Ods (printFods)+import Hledger.Write.Html (Html, titledTableHtml, htmlAsLazyText, toHtml)+import Hledger.Write.Spreadsheet (rawTableContent, headerCell,+ addHeaderBorders, addRowSpanHeader, addRowSpanHeaderNE,+ cellFromMixedAmount, cellsFromMixedAmount, cellFromAmount)+import Hledger.Write.Spreadsheet qualified as Ods+++-- | Command line options for this command.+balancemode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Balance.txt")+ (+ -- https://hledger.org/dev/hledger.html#calculation-mode :+ [flagNone ["sum"] (setboolopt "sum")+ (calcprefix ++ "show sum of posting amounts (default)")+ ,flagNone ["valuechange"] (setboolopt "valuechange")+ (calcprefix ++ "show total change of value of period-end historical balances (caused by deposits, withdrawals, market price fluctuations)")+ ,flagNone ["gain"] (setboolopt "gain")+ (calcprefix ++ "show capital gain/loss (historical balance value minus cost basis, or transacted cost where there is none)")+ -- XXX --budget[=DESCPAT], --forecast[=PERIODEXP], could be more consistent+ ,flagOpt "" ["budget"] (\s opts -> Right $ setopt "budget" s opts) "DESCPAT"+ (unlines+ [ calcprefix ++ "show sum of posting amounts together with budget goals defined by periodic"+ , "transactions. With a DESCPAT argument (must be separated by = not space),"+ , "use only periodic transactions with matching description"+ , "(case insensitive substring match)."+ ])+ ,flagNone ["count"] (setboolopt "count")+ (calcprefix ++ "show the count of postings")++ -- https://hledger.org/dev/hledger.html#accumulation-mode :+ ,flagNone ["change"] (setboolopt "change")+ (accumprefix ++ "accumulate amounts from column start to column end (in multicolumn reports, default)")+ ,flagNone ["cumulative"] (setboolopt "cumulative")+ (accumprefix ++ "accumulate amounts from report start (specified by e.g. -b/--begin) to column end")+ ,flagNone ["historical","H"] (setboolopt "historical")+ (accumprefix ++ "accumulate amounts from journal start to column end (includes postings before report start date)")+ ]++ -- other options specific to this command:+ ++ flattreeflags True +++ [flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "in list mode, omit N leading account name parts"+ ,flagNone ["declared"] (setboolopt "declared") "include non-parent declared accounts (best used with -E)"+ ,flagNone ["average","A"] (setboolopt "average") "show a row average column (in multicolumn reports)"+ ,flagNone ["row-total","T"] (setboolopt "row-total") "show a row total column (in multicolumn reports)"+ ,flagNone ["summary-only"] (setboolopt "summary-only") "display only row summaries (e.g. row total, average) (in multicolumn reports)"+ ,flagNone ["no-total","N"] (setboolopt "no-total") "omit the final total row"+ ,flagNone ["no-elide"] (setboolopt "no-elide") "in tree mode, don't squash boring parent accounts; in list mode, also show parent accounts (usually zero, hidden without -E)"+ ,flagNone ["full-names"] (setboolopt "full-names") "in tree mode, show full account names instead of indented leaf names"+ ,flagReq ["format"] (\s opts -> Right $ setopt "format" s opts) "FORMATSTR" "use this custom line format (in simple reports)"+ ,flagNone ["sort-amount","S"] (setboolopt "sort-amount") "sort by amount instead of account code/name (in flat mode). With multiple columns, sorts by the row total, or by row average if that is displayed."+ ,flagNone ["percent", "%"] (setboolopt "percent") "express values in percentage of each column's total"+ ,flagNone ["related","r"] (setboolopt "related") "show the other accounts transacted with, instead"+ ,flagNone ["invert"] (setboolopt "invert") "display all amounts with reversed sign"+ ,flagNone ["transpose"] (setboolopt "transpose") "switch rows and columns (use vertical time axis); repeat to cancel"+ ,flagReq ["layout"] (\s opts -> Right $ setopt "layout" s opts) "ARG"+ (unlines+ ["how to lay out multi-commodity amounts and the overall table:"+ ,"'wide[,W]': commodities on same line, up to W wide"+ ,"'tall' : commodities on separate lines"+ ,"'bare' : commodity symbols in a separate column"+ ,"'tidy' : each data field in its own column"+ ])+ ,flagReq ["base-url"] (\s opts -> Right $ setopt "base-url" s opts) "URLPREFIX" "in html output, generate links to hledger-web, with this prefix. (Usually the base url shown by hledger-web; can also be relative.)"++ -- output:+ ,outputFormatFlag ["txt","html","csv","tsv","json","fods","svg"]+ ,outputFileFlag+ ,outputViewFlag+ ,balanceChartFlag+ ,chartWidthFlag++ ]+ )+ cligeneralflagsgroups1+ (hiddenflags +++ [ flagNone ["commodity-column"] (setboolopt "commodity-column")+ "show commodity symbols in a separate column, amounts as bare numbers, one row per commodity"+ ])+ ([], Just $ argsFlag "[QUERY]")++ where+ calcprefix = "calculation mode: "+ accumprefix = "accumulation mode: "++-- | The balance command, prints a balance report.+balance :: CliOpts -> Journal -> IO ()+balance opts j | chartRequested opts = balanceChart opts j+balance opts@CliOpts{reportspec_=rspec} j = case balancecalc_ ropts of+ CalcBudget -> do -- single or multi period budget report+ warnIfLargeMultiPeriodReport rspec j+ let rspan = fst $ reportSpan j rspec+ budgetreport = styleAmounts styles $ budgetReport rspec (balancingopts_ $ inputopts_ opts) rspan j+ render = case fmt of+ "txt" -> budgetReportAsText ropts+ "json" -> (<>"\n") . toJsonText+ "csv" -> printCSV . budgetReportAsCsv ropts+ "tsv" -> printTSV . budgetReportAsCsv ropts+ "html" -> (<>"\n") . htmlAsLazyText . budgetReportAsHtml ropts+ "fods" -> printFods IO.localeEncoding .+ Map.singleton (tr "Budget Report") . budgetReportAsSpreadsheet oneLineNoCostFmt ropts+ _ -> error' $ unsupportedOutputFormatError fmt+ writeOutputLazyText opts $ render budgetreport++ _ | multiperiod -> do -- multi period balance report+ warnIfLargeMultiPeriodReport rspec j+ let report = styleAmounts styles $ multiBalanceReport rspec j+ render = case fmt of+ "txt" -> multiBalanceReportAsText ropts+ "csv" -> printCSV . multiBalanceReportAsCsv ropts+ "tsv" -> printTSV . multiBalanceReportAsCsv ropts+ "html" -> (<>"\n") . htmlAsLazyText . multiBalanceReportAsHtml ropts+ "json" -> (<>"\n") . toJsonText+ "fods" -> printFods IO.localeEncoding .+ Map.singleton (tr "Multi-period Balance Report") . multiBalanceReportAsSpreadsheet ropts+ _ -> const $ error' $ unsupportedOutputFormatError fmt -- PARTIAL:+ writeOutputLazyText opts $ render report++ _ -> do -- single period simple balance report+ let report = styleAmounts styles $ balanceReport rspec j -- simple Ledger-style balance report+ render = case fmt of+ "txt" -> withTitle ropts . balanceReportAsText ropts+ "csv" -> printCSV . balanceReportAsCsv ropts+ "tsv" -> printTSV . balanceReportAsCsv ropts+ "html" -> (<>"\n") . htmlAsLazyText . balanceReportAsHtml ropts+ "json" -> (<>"\n") . toJsonText+ "fods" -> printFods IO.localeEncoding . Map.singleton (tr "Balance Report") . (,) (1,0) . balanceReportAsSpreadsheet oneLineNoCostFmt ropts+ _ -> error' $ unsupportedOutputFormatError fmt -- PARTIAL:+ writeOutputLazyText opts $ render report+ where+ styles = balanceReportStyles ropts j+ tr = I18n.tr (translations_ ropts)+ ropts =+ let ropts0 = _rsReportOpts rspec in+ ropts0 {+ -- tidy csv is defined externally and must not include totals or averages+ no_total_ = no_total_ ropts0 || layout_ ropts0 == LayoutTidy+ }+ -- Tidy csv/tsv should be consistent between single period and multiperiod reports.+ multiperiod = interval_ ropts /= NoInterval || (layout_ ropts == LayoutTidy && delimited)+ delimited = fmt == "csv" || fmt == "tsv"+ fmt = outputFormatFromOpts opts++-- | The balance command with --chart (or svg output): shows a chart of the balance report, or the chart's data.+balanceChart :: CliOpts -> Journal -> IO ()+balanceChart opts@CliOpts{reportspec_=rspec} j = case balancecalc_ ropts of+ CalcBudget -> error' "--chart does not yet support --budget" -- PARTIAL:+ -- with a report interval, or a grouped chart (a bar per account type, which needs the stacked multi-period chart, here with one period)+ _ | interval_ ropts /= NoInterval || caKind (chartArg mempty opts) == "grouped" -> do+ warnIfLargeMultiPeriodReport rspec j+ let report = styleAmounts styles $ multiBalanceReport rspec j+ writeChart opts (Just $ (<>"\n") $ htmlAsLazyText $ multiBalanceReportAsHtml ropts report) $+ multiBalanceReportAsChart (journalAccountType j) ropts (multiBalanceReportTitle ropts report) report+ _ -> do+ let report = styleAmounts styles $ balanceReport rspec j+ writeChart opts (Just $ (<>"\n") $ htmlAsLazyText $ balanceReportAsHtml ropts report) $+ balanceReportAsChart (journalAccountType j) ropts (effectiveTitle ropts "") report+ where+ ropts = _rsReportOpts rspec+ styles = balanceReportStyles ropts j++-- Rendering++budgetClass :: RowClass -> Ods.Class+budgetClass rc =+ Ods.Class $+ case rc of Value -> "budget"; Total -> "budget coltotal"++budgetTotalClass :: RowClass -> Ods.Class+budgetTotalClass rc =+ Ods.Class $+ case rc of Value -> "budget rowtotal"; Total -> "budget coltotal"++budgetAverageClass :: RowClass -> Ods.Class+budgetAverageClass rc =+ Ods.Class $+ case rc of Value -> "budget rowaverage"; Total -> "budget colaverage"+++-- Single-column balance reports++-- | Render a single-column balance report as CSV.+balanceReportAsCsv :: ReportOpts -> BalanceReport -> CSV+balanceReportAsCsv opts =+ rawTableContent . balanceReportAsSpreadsheet machineFmt opts++-- | Render a single-column balance report as plain text.+balanceReportAsText :: ReportOpts -> BalanceReport -> TL.Text+balanceReportAsText originalopts report@((items, total)) =+ case layout_ originalopts of+ LayoutBare | iscustom -> error' "Custom format not supported with commodity columns" -- PARTIAL:+ LayoutBare ->+ TB.toLazyText $ bareLayoutBalanceReportAsText originalopts report+ LayoutBareWide -> bareWideLayoutBalanceReportAsText originalopts report+ _ ->+ TB.toLazyText $+ unlinesB ls <> unlinesB (if no_total_ opts then [] else [overline, totalLines])+ where+ opts = widenDefaultBalanceLineFormat originalopts report+ (ls, sizes) = unzip $ map (balanceReportItemAsText opts) items+ -- abuse renderBalanceReportItem to render the total with similar format+ (totalLines, _totalSizes) = renderBalanceReportItem opts ("",0,total)+ -- with a custom format, extend the line to the full report width;+ -- otherwise show the amount column's width.+ iscustom = case format_ originalopts of+ OneLine ((FormatField _ _ _ TotalField):_) -> False+ TopAligned ((FormatField _ _ _ TotalField):_) -> False+ BottomAligned ((FormatField _ _ _ TotalField):_) -> False+ _ -> True+ isdefault = format_ originalopts == defaultBalanceLineFormat+ overlinewidth+ | iscustom = sum (map maximum' $ transpose sizes)+ | isdefault = defaultBalanceAmountColumnWidth originalopts report+ | otherwise = 20+ overline = TB.fromText $ T.replicate overlinewidth "-"++-- | The default balance format historically used a 20-character amount+-- column. Keep that as the minimum, but widen it when any rendered amount+-- needs more room.+widenDefaultBalanceLineFormat :: ReportOpts -> BalanceReport -> ReportOpts+widenDefaultBalanceLineFormat opts report+ | format_ opts == defaultBalanceLineFormat = opts{format_ = setTotalMinWidth amountwidth defaultBalanceLineFormat}+ | otherwise = opts+ where+ amountwidth = defaultBalanceAmountColumnWidth opts report+ setTotalMinWidth w (BottomAligned (FormatField l _ m TotalField : rest)) =+ BottomAligned (FormatField l (Just w) m TotalField : rest)+ setTotalMinWidth _ fmt = fmt++defaultBalanceAmountColumnWidth :: ReportOpts -> BalanceReport -> Int+defaultBalanceAmountColumnWidth opts ((items, total)) =+ maximum' $ 20 : map renderedAmountWidth visibleAmounts+ where+ visibleAmounts =+ map (\(_,_,_,amt) -> amt) items +++ [total | not (no_total_ opts)]+ renderedAmountWidth =+ wbWidth . showMixedAmountB noCostFmt+ { displayCommodity = layout_ opts /= LayoutBare+ , displayMinWidth = Just 0+ , displayColour = False+ }++-- | Render a single-column balance report as plain text with a separate commodity column (--layout=bare)+bareLayoutBalanceReportAsText :: ReportOpts -> BalanceReport -> TB.Builder+bareLayoutBalanceReportAsText opts (items, total) =+ unlinesB .+ map+ (renderColumns def{tableBorders=singleColumnTableOuterBorder} sizes .+ Group singleColumnTableInterColumnBorder . map Header) $+ ls ++ concat [[[overline], totalline] | not (no_total_ opts)]+ where+ render (_, acctname, dep, amt) =+ [ Cell TopRight damts+ , Cell TopLeft (fmap wbFromText cs)+ , Cell TopLeft (replicate (length damts - 1) mempty ++ [wbFromText dispname]) ]+ where dopts = oneLineNoCostFmt{displayCommodity=layout_ opts /= LayoutBare, displayCommodityOrder=Just cs, displayColour=color_ opts}+ cs = if mixedAmountLooksZero amt then [""] else S.toList $ maCommodities amt+ dispname = T.replicate ((dep - 1) * 2) " " <> acctname+ damts = showMixedAmountLinesB dopts amt+ ls = fmap render items+ totalline = render ("", "", 0, total)+ sizes = fromMaybe 0 . maximumMay . map cellWidth <$>+ transpose ([totalline | not (no_total_ opts)] ++ ls)+ overline = Cell TopLeft . pure . wbFromText . flip T.replicate "-" . fromMaybe 0 $ headMay sizes+ singleColumnTableOuterBorder = pretty_ opts+ singleColumnTableInterColumnBorder = if pretty_ opts then SingleLine else NoLine++-- | Render a single-column balance report as plain text with a separate commodity column (--layout=barewide)+bareWideLayoutBalanceReportAsText :: ReportOpts -> BalanceReport -> TL.Text+bareWideLayoutBalanceReportAsText opts br =+ renderTable tableopts (textCell TopLeft) (textCell TopLeft) (textCell TopRight) $+ Table+ (if null totalheadings+ then Group NoLine rowheadings+ else Group SingleLine $ map (Group NoLine) [rowheadings, totalheadings])+ (Group NoLine $ map (Header . Ods.cellContent) $ NonEmpty.tail header)+ (rows++totaldata)+ where+ tableopts = def{tableBorders=singleColumnTableOuterBorder, prettyTable=pretty_ opts}+ (header, body, totals) = balanceReportAsSpreadsheetParts fmt opts br+ fmt = oneLineNoCostFmt{displayColour=color_ opts}+ separateHeaders =+ unzip . map (\(hd:|tl) -> (Header hd, tl)) . rawTableContent+ (rowheadings,rows) = separateHeaders body+ (totalheadings,totaldata) = separateHeaders totals+ singleColumnTableOuterBorder = pretty_ opts++{-+This implementation turned out to be a bit convoluted but implements the following algorithm for formatting:++- If there is a single amount, print it with the account name directly:+- Otherwise, only print the account name on the last line.++ a USD 1 ; Account 'a' has a single amount+ EUR -1+ b USD -1 ; Account 'b' has two amounts. The account name is printed on the last line.+-}+-- | Render one balance report line item as plain text suitable for console output (or+-- whatever string format is specified). Note, prices will not be rendered, and+-- differently-priced quantities of the same commodity will appear merged.+-- The output will be one or more lines depending on the format and number of commodities.+balanceReportItemAsText :: ReportOpts -> BalanceReportItem -> (TB.Builder, [Int])+balanceReportItemAsText opts (fullName, displayName, dep, amt)+ | accountlistmode_ opts == ALTree && full_names_ opts =+ renderBalanceReportItem opts (accountNameDrop (drop_ opts) fullName, 0, amt)+ | otherwise =+ renderBalanceReportItem opts (displayName, dep, amt)++-- | Render a balance report item, using the StringFormat specified by --format.+--+renderBalanceReportItem :: ReportOpts -> (AccountName, Int, MixedAmount) -> (TB.Builder, [Int])+renderBalanceReportItem opts (acctname, dep, total) =+ case format_ opts of+ OneLine comps -> renderRowFromComponents $ renderComponents True True comps+ TopAligned comps -> renderRowFromComponents $ renderComponents True False comps+ BottomAligned comps -> renderRowFromComponents $ renderComponents False False comps++ where+ -- Combine the rendered component cells horizontally, as a possibly multi-line text (builder),+ -- aligned in borderless columns (? XXX). Also returns the rendered width of each cell.+ renderRowFromComponents :: [Cell] -> (TB.Builder, [Int])+ renderRowFromComponents cs =+ ( renderRowB def{tableBorders=False, borderSpaces=False} . Group NoLine $ map Header cs+ , map cellWidth cs+ )++ -- Render each of the given StringFormat components for the balance report item,+ -- returning each as a Cell.+ renderComponents :: Bool -> Bool -> [StringFormatComponent] -> [Cell]+ renderComponents topaligned oneline = map (renderComponent topaligned oneline opts (acctname, dep, total))++-- Render one StringFormat component for a balance report item.+-- Returns a Cell, containing 0 or more lines of text (as builders).+renderComponent :: Bool -> Bool -> ReportOpts -> (AccountName, Int, MixedAmount) -> StringFormatComponent -> Cell+renderComponent _ _ _ _ (FormatLiteral s) = textCell TopLeft s+renderComponent topaligned oneline opts (acctname, dep, total) (FormatField ljust mmin mmax field) = case field of+ DepthSpacerField -> Cell align [WideBuilder (TB.fromText $ T.replicate d " ") d]+ where d = maybe id min mmax $ dep * fromMaybe 1 mmin+ AccountField -> textCell align $ formatText ljust mmin mmax acctname+ TotalField -> Cell align . pure $ showMixedAmountB dopts total+ _ -> Cell align [mempty]+ where+ align | topaligned && ljust = TopLeft+ | topaligned = TopRight+ | ljust = BottomLeft+ | otherwise = BottomRight+ dopts = noCostFmt{displayCommodity = layout_ opts /= LayoutBare+ ,displayOneLine = oneline+ ,displayMinWidth = mmin+ ,displayMaxWidth = mmax+ ,displayColour = color_ opts+ }+++-- | Render a single-column balance report as HTML.+-- This report has no default heading, so one is shown only with --title.+balanceReportAsHtml :: ReportOpts -> BalanceReport -> Html+balanceReportAsHtml ropts br =+ titledTableHtml (effectiveTitle ropts "") . map (map (fmap toHtml)) $+ balanceReportAsSpreadsheet oneLineNoCostFmt ropts br++-- | Render a single-column balance report as FODS.+balanceReportAsSpreadsheet ::+ AmountFormat -> ReportOpts -> BalanceReport -> [[Ods.Cell Ods.NumLines Text]]+balanceReportAsSpreadsheet fmt opts mbr =+ (if transpose_ opts then Ods.transpose else id) $+ map Fold.toList $ header : body ++ totals+ where (header, body, totals) =+ balanceReportAsSpreadsheetParts fmt opts mbr++-- | Render the ODS table rows for a BalanceReport.+-- Returns the heading row, 0 or more body rows, and the totals row if enabled.+balanceReportAsSpreadsheetParts ::+ AmountFormat -> ReportOpts -> BalanceReport ->+ (NonEmpty (Ods.Cell Ods.NumLines Text),+ [NonEmpty (Ods.Cell Ods.NumLines Text)],+ [NonEmpty (Ods.Cell Ods.NumLines Text)])+balanceReportAsSpreadsheetParts fmt opts (items, total) =+ (headers,+ concatMap (rows Value) items,+ if no_total_ opts+ then []+ else addTotalBorders $+ rows Total (totalRowHeadingSpreadsheet, totalRowHeadingSpreadsheet, 0, total))+ where+ cell = Ods.defaultCell+ hCell cls label = (headerCell label) {Ods.cellClass = Ods.Class cls}+ headers =+ addHeaderBorders $+ hCell "account" "account" :| case layout_ opts of+ LayoutBareWide -> map (hCell "amount") allCommodities+ LayoutBare -> [headerCell "commodity", hCell "amount" "balance"]+ _ -> [hCell "amount" "balance"]+ allCommodities =+ S.toAscList $ foldMap (\(_,_,_,ma) -> maCommodities ma) items+ shownParents = shownParentsOf [name | (name, _, _, _) <- items]+ -- The report's period, from -b/-e/-p. A date: query term is in the+ -- query string already, and the report intersected the two.+ periodterms = if period_ opts == PeriodAll then [] else dateTerm (date2_ opts) $ periodAsDateSpan $ period_ opts+ linkquery = periodterms ++ querystring_ opts+ rows ::+ RowClass -> BalanceReportItem ->+ [NonEmpty (Ods.Cell Ods.NumLines Text)]+ rows rc (name, dispName, dep, ma) =+ let lo = rowLinkOpts opts [] shownParents name+ accountCell =+ setAccountAnchorWith lo+ (guard (rc==Value) >> balance_base_url_ opts)+ linkquery name $+ (\c -> c{Ods.cellClass = case rc of Value -> treeAccountClass opts dep name+ Total -> accountClass}) $+ cell $ case rc of+ Total -> dispName -- show the total row heading as is; --drop etc. don't apply (#2688)+ Value -> renderBalanceAcct opts nbsp (name, dispName, dep) in+ -- The figure links where the account name does, or, in the total+ -- row, to the register of everything in the report; a figure that+ -- looks zero has an empty register, and no link.+ let linkFigure+ | not (figuresLink opts) || mixedAmountLooksZero ma = id+ | rc == Value = withLink (Ods.cellAnchor accountCell) (amountPhrase lo False)+ | otherwise =+ withLink+ (composeAnchorWith (linkParams lo) (balance_base_url_ opts) $+ periodterms ++ removeInacct (querystring_ opts))+ (amountPhrase lo True) in+ addRowSpanHeaderNE accountCell $+ case layout_ opts of+ LayoutBareWide ->+ let bopts =+ machineFmt {+ displayCommodity = False,+ displayCommodityOrder = Just allCommodities+ } in+ [map (\bldAmt ->+ fmap wbToText $ cellFromAmount bopts (amountClass rc, bldAmt)) $+ showMixedAmountLinesPartsB bopts ma]+ LayoutBare ->+ map (\a -> [cell $ acommodity a, renderAmount rc $ mixedAmount a])+ . amounts $ mixedAmountStripCosts ma+ _ -> [[linkFigure $ renderAmount rc ma]]++ renderAmount rc mixedAmt =+ wbToText <$> cellFromMixedAmount bopts (amountClass rc, mixedAmt)+ where+ bopts = fmt{displayCommodity=showcomm, displayCommodityOrder = commorder}+ (showcomm, commorder)+ | layout_ opts == LayoutBare = (False, Just $ S.toList $ maCommodities mixedAmt)+ | otherwise = (True, Nothing)++++-- Multi-column balance reports++-- | Render a multi-column balance report as CSV.+-- The CSV will always include the initial headings row,+-- and will include the final totals row unless --no-total is set.+multiBalanceReportAsCsv :: ReportOpts -> MultiBalanceReport -> CSV+multiBalanceReportAsCsv opts@ReportOpts{..} report =+ (if transpose_ then transpose else id) $+ rawTableContent $ header ++ body ++ totals+ where+ (header, body, totals) =+ multiBalanceReportAsSpreadsheetParts machineFmt opts report+++multiBalanceReportNumHeaderColumns :: Layout -> Int+multiBalanceReportNumHeaderColumns lay =+ case lay of+ LayoutBare -> 2+ LayoutTidy -> 0+ _ -> 1++-- | Render the Spreadsheet table rows (CSV, ODS, HTML) for a MultiBalanceReport.+-- Returns the heading rows, 0 or more body rows, and the totals row if enabled.+multiBalanceReportAsSpreadsheetParts ::+ AmountFormat -> ReportOpts -> MultiBalanceReport ->+ ([[Ods.Cell Ods.NumLines Text]],+ [[Ods.Cell Ods.NumLines Text]],+ [[Ods.Cell Ods.NumLines Text]])+multiBalanceReportAsSpreadsheetParts fmt opts mbr =+ balanceSubReportAsSpreadsheetParts fmt opts+ (allCommoditiesFromPeriodicReport $ prRows mbr) mbr+++-- | Render a multi-column balance report as HTML.+multiBalanceReportAsHtml :: ReportOpts -> MultiBalanceReport -> Html+multiBalanceReportAsHtml ropts mbr =+ titledTableHtml (multiBalanceReportTitle ropts mbr) . map (map (fmap toHtml)) $+ snd $ multiBalanceReportAsSpreadsheet ropts mbr++-- | Render the ODS table rows for a MultiBalanceReport.+-- Returns the heading row, 0 or more body rows, and the totals row if enabled.+multiBalanceReportAsSpreadsheet ::+ ReportOpts -> MultiBalanceReport ->+ ((Int, Int), [[Ods.Cell Ods.NumLines Text]])+multiBalanceReportAsSpreadsheet ropts mbr =+ let (header,body,total) =+ multiBalanceReportAsSpreadsheetParts oneLineNoCostFmt ropts mbr+ in (if transpose_ ropts then swap *** Ods.transpose else id) $+ ((length header, multiBalanceReportNumHeaderColumns (layout_ ropts)),+ header ++ body ++ total)+++-- | Render a report title as a text block to prefix to a text report,+-- or nothing if the title is empty.+titleAsTextBuilder :: Text -> TB.Builder+titleAsTextBuilder title+ | T.null title = mempty+ | otherwise = TB.fromText title <> TB.fromText "\n\n"++-- | Render a multi-column balance report as plain text suitable for console output.+multiBalanceReportAsText :: ReportOpts -> MultiBalanceReport -> TL.Text+multiBalanceReportAsText ropts r = TB.toLazyText $+ titleAsTextBuilder (multiBalanceReportTitle ropts r)+ <> multiBalanceReportTableAsText ropts (multiBalanceReportAsTable ropts r)++-- | The heading for a multi-column balance report: a description of the+-- report, or --title's value if that was provided (possibly empty).+multiBalanceReportTitle :: ReportOpts -> MultiBalanceReport -> Text+multiBalanceReportTitle ropts@ReportOpts{..} r = effectiveTitle ropts defaultTitle+ where+ tr = I18n.tr translations_+ trf = I18n.trf translations_+ -- TRANSLATORS: the multi-period balance report title, eg "Balance changes in 2024, valued at period ends:".+ defaultTitle = trf "{report} in {dates}{valuation}:"+ [ ("report", mtitle), ("dates", showDateSpan (periodicReportSpan r)), ("valuation", valuationdesc) ]++ mtitle = case (balancecalc_, balanceaccum_) of+ (CalcValueChange, PerPeriod ) -> tr "Period-end value changes"+ (CalcValueChange, Cumulative ) -> tr "Cumulative period-end value changes"+ (CalcGain, PerPeriod ) -> tr "Incremental gain"+ (CalcGain, Cumulative ) -> tr "Cumulative gain"+ (CalcGain, Historical ) -> tr "Historical gain"+ (CalcPostingsCount, PerPeriod ) -> tr "Posting counts"+ (CalcPostingsCount, Cumulative ) -> tr "Cumulative posting counts"+ (CalcPostingsCount, Historical ) -> tr "Historical posting counts"+ (CalcTransactionsCount, _ ) -> tr "Transaction counts"+ (_, PerPeriod ) -> tr "Balance changes"+ (_, Cumulative ) -> tr "Ending balances (cumulative)"+ (_, Historical) -> tr "Ending balances (historical)"+ valuationdesc =+ (case conversionop_ of+ Just ToCost -> tr ", converted to cost"+ _ -> "")+ <> (case value_ of+ Just (AtThen _mc) -> tr ", valued at posting date"+ Just (AtEnd _mc) | changingValuation -> ""+ Just (AtEnd _mc) -> tr ", valued at period ends"+ Just (AtNow _mc) -> tr ", current value"+ Just (AtDate d _mc) -> trf ", valued at {date}" [("date", showDate d)]+ Nothing -> "")++ changingValuation = case (balancecalc_, balanceaccum_) of+ (CalcValueChange, PerPeriod) -> True+ (CalcValueChange, Cumulative) -> True+ _ -> False++-- | Given a table representing a multi-column balance report,+-- render it in a format suitable for console output.+-- Amounts with more than two commodities will be elided unless --no-elide is used.+multiBalanceReportTableAsText :: ReportOpts -> Table T.Text T.Text WideBuilder -> TB.Builder+multiBalanceReportTableAsText ReportOpts{..} = renderTableByRowsB tableopts renderCh renderRow+ where+ tableopts = def{tableBorders=multiColumnTableOuterBorder, prettyTable=pretty_}+ multiColumnTableOuterBorder = pretty_++ renderCh :: [Text] -> [Cell]+ renderCh+ | layout_ /= LayoutBare || transpose_ = fmap (textCell TopRight)+ | otherwise = zipWith ($) (textCell TopLeft : repeat (textCell TopRight))++ renderRow :: (Text, [WideBuilder]) -> (Cell, [Cell])+ renderRow (rh, row)+ | layout_ /= LayoutBare || transpose_ =+ (textCell TopLeft rh, fmap (Cell TopRight . pure) row)+ | otherwise =+ (textCell TopLeft rh, zipWith ($) (Cell TopLeft : repeat (Cell TopRight)) (fmap pure row))++-- | Build a 'Table' from a multi-column balance report.+multiBalanceReportAsTable :: ReportOpts -> MultiBalanceReport -> Table T.Text T.Text WideBuilder+multiBalanceReportAsTable opts report@(PeriodicReport _spans items _tr) =+ multiBalanceReportAsPartTable opts+ (allCommoditiesFromPeriodicReport items)+ report+++multiBalanceRowAsCsvText ::+ ReportOpts -> [DateSpan] -> [CommoditySymbol] ->+ PeriodicReportRow a MixedAmount -> [[T.Text]]+multiBalanceRowAsCsvText opts colspans allCommodities =+ map (map (wbToText . Ods.cellContent)) .+ multiBalanceRowAsCellBuilders machineFmt opts colspans allCommodities+ Value (simpleDateSpanCell $ period_titles_ opts)+++-- Budget reports++-- A BudgetCell's data values rendered for display - the actual change amount,+-- the budget goal amount if any, and the corresponding goal percentage if possible.+type BudgetDisplayCell = (WideBuilder, Maybe (WideBuilder, Maybe WideBuilder))++-- | A row of rendered budget data cells.+type BudgetDisplayRow = [BudgetDisplayCell]++-- | An amount render helper for the budget report. Renders each commodity separately.+type BudgetShowAmountsFn = MixedAmount -> [WideBuilder]++-- | A goal percentage calculating helper for the budget report.+type BudgetCalcPercentagesFn = Change -> BudgetGoal -> [Maybe Percentage]++-- | Render a budget report as plain text suitable for console output.+budgetReportAsText :: ReportOpts -> BudgetReport -> TL.Text+budgetReportAsText ropts budgetr = TB.toLazyText $+ titleAsTextBuilder (budgetReportTitle ropts budgetr) <>+ multiBalanceReportTableAsText ropts (budgetReportAsTable ropts budgetr)++-- | The heading for a budget report: a description of the report,+-- or --title's value if that was provided (possibly empty).+budgetReportTitle :: ReportOpts -> BudgetReport -> Text+budgetReportTitle ropts@ReportOpts{..} budgetr = effectiveTitle ropts defaultTitle+ where+ tr = I18n.tr translations_+ trf = I18n.trf translations_+ -- TRANSLATORS: the budget report title, eg "Budget performance in 2024, valued at period ends:".+ defaultTitle = trf "Budget performance in {dates}{valuation}:"+ [ ("dates", showDateSpan (periodicReportSpan budgetr)), ("valuation", valuationdesc) ]+ valuationdesc =+ (case conversionop_ of+ Just ToCost -> tr ", converted to cost"+ _ -> "")+ <> (case value_ of+ Just (AtThen _mc) -> tr ", valued at posting date"+ Just (AtEnd _mc) -> tr ", valued at period ends"+ Just (AtNow _mc) -> tr ", current value"+ Just (AtDate d _mc) -> trf ", valued at {date}" [("date", showDate d)]+ Nothing -> "")++-- | Build a 'Table' from a multi-column balance report.+budgetReportAsTable :: ReportOpts -> BudgetReport -> Table Text Text WideBuilder+budgetReportAsTable ropts@ReportOpts{..} (PeriodicReport spans items totrow) =+ (case layout_ of+ LayoutTall -> id+ LayoutWide _ -> id+ LayoutBare -> id+ _ -> unsupportedLayout layout_) $+ maybetransposetable $+ addtotalrow $+ Table+ (Group budgetTableInterRowBorder $ map Header accts)+ (Group budgetTableInterColumnBorder $ map Header colheadings)+ rows+ where+ trc = I18n.trc translations_+ budgetTableInterRowBorder = NoLine+ budgetTableInterColumnBorder = if pretty_ then SingleLine else NoLine++ maybetransposetable+ | transpose_ = \(Table rh ch vals) -> Table ch rh (transpose vals)+ | otherwise = id++ addtotalrow+ | no_total_ = id+ | otherwise =+ let+ rowhdrs = Group NoLine $ map Header $ totalRowHeadingBudgetText : replicate (length totalrows - 1) ""+ colhdrs = Header [] -- ignored by concatTables+ in+ (flip (concatTables SingleLine) $ Table rowhdrs colhdrs totalrows) -- XXX ?++ colheadings = [trc "column heading" "Commodity" | layout_ == LayoutBare]+ ++ (if not summary_only_ then map (reportPeriodName ropts spans) spans else [])+ ++ [" " <> trc "column heading" "Total" | row_total_]+ ++ [trc "column heading" "Average" | average_]++ (accts, rows, totalrows) =+ (accts'+ ,maybecommcol itemscs $ showcells texts+ ,maybecommcol totrowcs $ showtotrow totrowtexts)+ where+ -- If --layout=bare, prepend a commodities column.+ maybecommcol :: [WideBuilder] -> [[WideBuilder]] -> [[WideBuilder]]+ maybecommcol cs+ | layout_ == LayoutBare = zipWith (:) cs+ | otherwise = id++ showcells, showtotrow :: [[BudgetDisplayCell]] -> [[WideBuilder]]+ (showcells, showtotrow) =+ (maybetranspose . map (zipWith showBudgetDisplayCell widths) . maybetranspose+ ,maybetranspose . map (zipWith showBudgetDisplayCell totrowwidths) . maybetranspose)+ where+ -- | Combine a BudgetDisplayCell's rendered values into a "[PERCENT of GOAL]" rendering,+ -- respecting the given widths.+ showBudgetDisplayCell :: (Int, Int, Int) -> BudgetDisplayCell -> WideBuilder+ showBudgetDisplayCell (actualwidth, budgetwidth, percentwidth) (actual, mbudget) =+ flip WideBuilder (actualwidth + totalbudgetwidth) $+ toPadded actual <> maybe emptycell showBudgetGoalAndPercentage mbudget++ where+ toPadded (WideBuilder b w) = (TB.fromText . flip T.replicate " " $ actualwidth - w) <> b++ (totalpercentwidth, totalbudgetwidth) =+ let totalpercentwidth' = if percentwidth == 0 then 0 else percentwidth + 5+ in ( totalpercentwidth'+ , if budgetwidth == 0 then 0 else budgetwidth + totalpercentwidth' + 3+ )++ emptycell :: TB.Builder+ emptycell = TB.fromText $ T.replicate totalbudgetwidth " "++ showBudgetGoalAndPercentage :: (WideBuilder, Maybe WideBuilder) -> TB.Builder+ showBudgetGoalAndPercentage (goal, perc) =+ let perct = case perc of+ Nothing -> T.replicate totalpercentwidth " "+ Just pct -> T.replicate (percentwidth - wbWidth pct) " " <> wbToText pct <> "% of "+ in TB.fromText $ " [" <> perct <> T.replicate (budgetwidth - wbWidth goal) " " <> wbToText goal <> "]"++ -- | Build a list of widths for each column.+ -- When --transpose is used, the totals row must be included in this list.+ widths :: [(Int, Int, Int)]+ widths = zip3 actualwidths budgetwidths percentwidths+ where+ actualwidths = map (maximum' . map first3 ) $ cols+ budgetwidths = map (maximum' . map second3) $ cols+ percentwidths = map (maximum' . map third3 ) $ cols+ catcolumnwidths = foldl' (zipWith (++)) $ repeat []+ cols = maybetranspose $ catcolumnwidths $ map (cellswidth . rowToBudgetCells) items ++ [cellswidth $ rowToBudgetCells totrow]++ cellswidth :: [BudgetCell] -> [[(Int, Int, Int)]]+ cellswidth row =+ let cs = budgetCellsCommodities row+ (showmixed, percbudget) = mkBudgetDisplayFns cs+ disp = showcell showmixed percbudget+ budgetpercwidth = wbWidth *** maybe 0 wbWidth+ cellwidth (am, bm) = let (bw, pw) = maybe (0, 0) budgetpercwidth bm in (wbWidth am, bw, pw)+ in map (map cellwidth . disp) row++ totrowwidths :: [(Int, Int, Int)]+ totrowwidths+ | transpose_ = drop (length texts) widths+ | otherwise = widths++ maybetranspose+ | transpose_ = transpose+ | otherwise = id++ (accts', itemscs, texts) = unzip3 $ concat shownitems+ where+ shownitems :: [[(AccountName, WideBuilder, BudgetDisplayRow)]]+ shownitems =+ map (\i ->+ let+ addacctcolumn = map (\(cs, cvals) -> (renderPeriodicAcct ropts " " i, cs, cvals))+ isunbudgetedrow = displayFull (prrName i) == unbudgetedAccountName+ in addacctcolumn $ showrow isunbudgetedrow $ rowToBudgetCells i)+ items++ (totrowcs, totrowtexts) = unzip $ concat showntotrow+ where+ showntotrow :: [[(WideBuilder, BudgetDisplayRow)]]+ showntotrow = [showrow False $ rowToBudgetCells totrow]++ -- | Get the data cells from a row or totals row, maybe adding+ -- the row total and/or row average depending on options.+ rowToBudgetCells :: PeriodicReportRow a BudgetCell -> [BudgetCell]+ rowToBudgetCells (PeriodicReportRow _ as rowtot rowavg) =+ (if not summary_only_ then as else [])+ ++ [rowtot | row_total_ && not (null as)]+ ++ [rowavg | average_ && not (null as)]++ -- | Render a row's data cells as "BudgetDisplayCell"s, and a rendered list of commodity symbols.+ -- Also requires a flag indicating whether this is the special <unbudgeted> row.+ -- (The types make that hard to check here.)+ showrow :: Bool -> [BudgetCell] -> [(WideBuilder, BudgetDisplayRow)]+ showrow isunbudgetedrow cells =+ let+ cs = budgetCellsCommodities cells+ -- #2071 If there are no commodities - because there are no actual or goal amounts -+ -- the zipped list would be empty, causing this row not to be shown.+ -- But rows like this sometimes need to be shown to preserve the account tree structure.+ -- So, ensure 0 will be shown as actual amount(s).+ -- Unfortunately this disables boring parent eliding, as if --no-elide had been used.+ -- (Just turning on --no-elide higher up doesn't work right.)+ -- Note, no goal amount will be shown for these rows,+ -- whereas --no-elide is likely to show a goal amount aggregated from children.+ cs1 = if null cs && not isunbudgetedrow then [""] else cs+ (showmixed, percbudget) = mkBudgetDisplayFns cs1+ in+ zip (map wbFromText cs1) $+ transpose $+ map (showcell showmixed percbudget)+ cells++ budgetCellsCommodities :: [BudgetCell] -> [CommoditySymbol]+ budgetCellsCommodities = S.toList . foldl' S.union mempty . map budgetCellCommodities+ where+ budgetCellCommodities :: BudgetCell -> S.Set CommoditySymbol+ budgetCellCommodities (am, bm) = f am `S.union` f bm+ where f = maybe mempty maCommodities++ -- | Render a "BudgetCell"'s amounts as "BudgetDisplayCell"s (one per commodity).+ showcell :: BudgetShowAmountsFn -> BudgetCalcPercentagesFn -> BudgetCell -> BudgetDisplayRow+ showcell showCommodityAmounts calcCommodityPercentages (mactual, mbudget) =+ zip actualamts budgetinfos+ where+ actual = fromMaybe nullmixedamt mactual+ actualamts = showCommodityAmounts actual+ budgetinfos =+ case mbudget of+ Nothing -> repeat Nothing+ Just goal -> map Just $ showGoalAmountsAndPercentages goal+ where+ showGoalAmountsAndPercentages :: MixedAmount -> [(WideBuilder, Maybe WideBuilder)]+ showGoalAmountsAndPercentages goal = zip amts mpcts+ where+ amts = showCommodityAmounts goal+ mpcts = map (showrounded <$>) $ calcCommodityPercentages actual goal+ where showrounded = wbFromText . T.pack . show . roundTo 0++ -- | Make budget info display helpers that adapt to --layout=wide.+ mkBudgetDisplayFns :: [CommoditySymbol] -> (BudgetShowAmountsFn, BudgetCalcPercentagesFn)+ mkBudgetDisplayFns cs = case layout_ of+ LayoutWide width ->+ ( pure . showMixedAmountB oneLineNoCostFmt{displayMaxWidth=width, displayColour=color_}+ , \a -> pure . percentage a)+ _ -> ( showMixedAmountLinesB (setDisplayCommodityBare cs noCostFmt){displayCommodity=layout_/=LayoutBare, displayColour=color_}+ , \a b -> map (percentage' a b) cs)+ where+ -- | Calculate the percentage of actual change to budget goal to show, if any.+ -- If valuing at cost, both amounts are converted to cost before comparing.+ -- A percentage will not be shown if:+ --+ -- - actual or goal are not the same, single, commodity+ --+ -- - the goal is zero+ --+ percentage :: Change -> BudgetGoal -> Maybe Percentage+ percentage actual budget =+ case (costedAmounts actual, costedAmounts budget) of+ ([a], [b]) | (acommodity a == acommodity b || amountLooksZero a) && not (amountLooksZero b)+ -> Just $ 100 * aquantity a / aquantity b+ _ -> Nothing+ where+ costedAmounts = case conversionop_ of+ Just ToCost -> amounts . mixedAmountCostBasis+ Just ToTransactedCost -> amounts . mixedAmountCost+ _ -> amounts . mixedAmountStripCosts -- strip any lingering cost info that would prevent unification++ -- | Like percentage, but accept multicommodity actual and budget amounts,+ -- and extract the specified commodity from both.+ percentage' :: Change -> BudgetGoal -> CommoditySymbol -> Maybe Percentage+ percentage' am bm c = case ((,) `on` find ((==) c . acommodity) . amounts) am bm of+ (Just a, Just b) -> percentage (mixedAmount a) (mixedAmount b)+ _ -> Nothing++-- XXX generalise this with multiBalanceReportAsCsv ?+-- | Render a budget report as CSV. Like multiBalanceReportAsCsv,+-- but includes alternating actual and budget amount columns.+budgetReportAsCsv :: ReportOpts -> BudgetReport -> [[Text]]+budgetReportAsCsv ropts report+ = rawTableContent $ snd $+ budgetReportAsSpreadsheet machineFmt ropts report++-- | Render a budget report as HTML.+budgetReportAsHtml :: ReportOpts -> BudgetReport -> Html+budgetReportAsHtml ropts budgetr =+ titledTableHtml (budgetReportTitle ropts budgetr) . map (map (fmap toHtml)) . snd $+ budgetReportAsSpreadsheet oneLineNoCostFmt ropts budgetr++budgetReportAsSpreadsheet ::+ AmountFormat -> ReportOpts -> BudgetReport ->+ ((Int,Int), [[Ods.Cell Ods.NumLines Text]])+budgetReportAsSpreadsheet+ fmt+ ropts@ReportOpts{..}+ (PeriodicReport colspans items totrow)+ =+ (case layout_ of+ LayoutWide _ -> id+ LayoutBare -> id+ LayoutBareWide -> id+ _ -> unsupportedLayout layout_) $+ (if transpose_ then swap *** Ods.transpose else id) $+ ((length allHeaders, length leadingHeaders)+ ,+ -- heading row+ allHeaders ++++ -- account rows+ concatMap (\row -> rowAsTexts Value (accountCell row) row) items++ -- totals row+ ++ addTotalBorders+ (concat [ rowAsTexts Total (cell totalRowHeadingBudgetCsv) totrow | not no_total_ ])+ )++ where+ cell = Ods.defaultCell+ accountCell row =+ let name = prrFullName row in+ setAccountAnchor (balance_base_url_) querystring_ name $+ cell $ renderPeriodicAcct ropts nbsp row+ allHeaders =+ case layout_ of+ LayoutBareWide ->+ [headerWithoutBorders $+ Ods.emptyCell :+ concatMap+ (Ods.horizontalSpan allCommodities . headerCell)+ dateHeaders,+ addHeaderBorders $ map headerCell $+ leadingHeaders ++ (dateHeaders >> allCommodities)]+ _ -> [addHeaderBorders $ map headerCell $ leadingHeaders ++ dateHeaders]+ leadingHeaders =+ "Account" : ["Commodity" | layout_ == LayoutBare ]+ dateHeaders =+ (if not summary_only_+ then concatMap (\spn -> [renderPeriodHeading period_titles_ spn, "budget"]) colspans+ else [])+ ++ concat [["Total" ,"budget"] | row_total_]+ ++ concat [["Average","budget"] | average_]+ allCommodities =+ S.toAscList $+ foldMap (foldMap maCommodities . concatMap (\(change,goal) -> maybeToList change ++ maybeToList goal) . prrAmounts) items++ {-+ ToDo: The chosen HTML cell class names are not put in stone.+ If you find you need more systematic names,+ feel free to develop a more sophisticated scheme.+ -}+ flattentuples rc tups =+ concat [[(amountClass rc, a),(budgetClass rc, b)] | (a,b) <- tups]+ showNorm (cls,mval) =+ maybe Ods.emptyCell (fmap wbToText . curry (cellFromMixedAmount fmt) cls) mval++ rowAsTexts :: RowClass+ -> Ods.Cell Ods.NumLines Text+ -> PeriodicReportRow a BudgetCell+ -> [[Ods.Cell Ods.NumLines Text]]+ rowAsTexts rc acctCell (PeriodicReportRow _ as (rowtot,budgettot) (rowavg, budgetavg)) =+ addRowSpanHeader acctCell $+ case layout_ of+ LayoutBare ->+ zipWith (:) (map cell cs) -- add symbols+ . transpose -- each row becomes a list of Text quantities+ . bareCells cs+ $ vals+ LayoutBareWide -> [concat . bareCells allCommodities $ vals]+ _ -> [map showNorm vals]+ where+ bareCells cs_ =+ map (map (fmap wbToText) .+ cellsFromMixedAmount (setDisplayCommodityBare cs_ fmt) .+ second (fromMaybe nullmixedamt))+ cs = S.toList . mconcat . map maCommodities $ mapMaybe snd vals+ vals = flattentuples rc (if not summary_only_ then as else [])+ ++ concat [[(rowTotalClass rc, rowtot),+ (budgetTotalClass rc, budgettot)]+ | row_total_]+ ++ concat [[(rowAverageClass rc, rowavg),+ (budgetAverageClass rc, budgetavg)]+ | average_]++unsupportedLayout :: Layout -> a -> a+unsupportedLayout lay =+ error' $ show lay ++ " not supported for the chosen output format."+++-- tests++tests_Balance = testGroup "Balance" [++ testGroup "balanceReportAsText" [+ testCase "unicode in balance layout" $ do+ j <- readJournal'' "2009/01/01 * медвежья шкура\n расходы:покупки 100\n актив:наличные\n"+ let rspec = defreportspec{_rsReportOpts=defreportopts{no_total_=True}}+ balanceReportAsText (_rsReportOpts rspec) (balanceReport rspec{_rsDay=fromGregorian 2008 11 26} j)+ @?=+ TL.unlines+ [" -100 актив:наличные"+ ," 100 расходы:покупки"+ ]+ ]++ ]
+ Hledger/Cli/Commands/Balance.txt view
@@ -0,0 +1,1249 @@+balance++(bal)++Show accounts with some kind of summed numeric data: balance changes per+period, end balances on period end dates, simple capital gains, budget+goal performance, etc.++Flags:+ --sum calculation mode: show sum of posting amounts+ (default)+ --valuechange calculation mode: show total change of value+ of period-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ --gain calculation mode: show capital gain/loss+ (historical balance value minus cost basis, or+ transacted cost where there is none)+ --budget[=DESCPAT] calculation mode: show sum of posting amounts+ together with budget goals defined by periodic+ transactions. With a DESCPAT argument (must be+ separated by = not space),+ use only periodic transactions with matching+ description+ (case insensitive substring match).+ --count calculation mode: show the count of postings+ --change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports, default)+ --cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. -b/--begin) to+ column end+ -H --historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date)+ -l --flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth-clipped.+ -t --tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ --drop=N in list mode, omit N leading account name+ parts+ --declared include non-parent declared accounts (best+ used with -E)+ -A --average show a row average column (in multicolumn+ reports)+ -T --row-total show a row total column (in multicolumn+ reports)+ --summary-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ -N --no-total omit the final total row+ --no-elide in tree mode, don't squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without -E)+ --full-names in tree mode, show full account names instead+ of indented leaf names+ --format=FORMATSTR use this custom line format (in simple+ reports)+ -S --sort-amount sort by amount instead of account code/name+ (in flat mode). With multiple columns, sorts by+ the row total, or by row average if that is+ displayed.+ -% --percent express values in percentage of each column's+ total+ -r --related show the other accounts transacted with,+ instead+ --invert display all amounts with reversed sign+ --transpose switch rows and columns (use vertical time+ axis); repeat to cancel+ --layout=ARG how to lay out multi-commodity amounts and the+ overall table:+ 'wide[,W]': commodities on same line, up to W+ wide+ 'tall' : commodities on separate lines+ 'bare' : commodity symbols in a separate+ column+ 'tidy' : each data field in its own column+ --base-url=URLPREFIX in html output, generate links to hledger-web,+ with this prefix. (Usually the base url shown by+ hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, fods, svg.+ -o --output-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ --view write output to FILE, or to view.FMT in+ hledger's cache directory, and open it in the+ system's default viewer for its format (eg a web+ browser for html). The default format is html.+ --chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: grouped (a bar per account type, side by+ side). net: also draw the net total (a line, or+ marks in text charts). SCALE: the amount that+ fills the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)++balance is one of hledger's oldest and most versatile commands, for+listing account balances, balance changes, values, value changes and+more, during one time period or many. Generally it shows a table, with+rows representing accounts, and columns representing periods.++Note there are some variants of the balance command with convenient+defaults, which are simpler to use: balancesheet, balancesheetequity,+cashflow and incomestatement. When you need more control, then use+balance.++balance features++Here's a quick overview of the balance command's features, followed by+more detailed descriptions and examples. Many of these work with the+other balance-like commands as well (bs, cf, is..).++balance can show..++- accounts as a list (-l) or a tree (-t)+- optionally depth-limited (-[1-9])+- sorted by declaration order and name, or by amount++..and their..++- balance changes (the default)+- or actual and planned balance changes (--budget)+- or value of balance changes (-V)+- or change of balance values (--valuechange)+- or capital gain/loss (--gain)+- or balance changes from sibling postings (--related/-r)+- or postings count (--count)++..in..++- one time period (the whole journal period by default)+- or multiple periods (-D, -W, -M, -Q, -Y, -p INTERVAL)++..either..++- per period (the default)+- or accumulated since report start date (--cumulative)+- or accumulated since account creation (--historical/-H)++..possibly converted to..++- cost (--value=cost[,COMM]/--cost/-B)+- or market value, as of transaction dates (--value=then[,COMM])+- or at period ends (--value=end[,COMM])+- or now (--value=now)+- or at some other date (--value=YYYY-MM-DD)++..with..++- totals (-T), averages (-A), percentages (-%), inverted sign (--invert)+- rows and columns swapped (--transpose)+- another field used as account name (--pivot)+- custom-formatted line items (single-period reports only) (--format)+- commodities displayed on the same line or multiple lines (--layout)+- a chart instead of a table (--chart)++This command supports the output destination and output format options,+with output formats txt, csv, tsv, json, html, fods, and svg. In txt+output in a colour-supporting terminal, negative amounts are shown in+red.++Simple balance report++With no arguments, balance shows a list of all accounts and their change+of balance - ie, the sum of posting amounts, both inflows and outflows -+during the entire period of the journal. ("Simple" here means just one+column of numbers, covering a single period. You can also have+multi-period reports, described later.)++For real-world accounts, these numbers will normally be their end+balance at the end of the journal period; more on this below.++Accounts are sorted by declaration order if any, and then alphabetically+by account name. For instance (using examples/sample.journal):++$ hledger -f examples/sample.journal bal+ $1 assets:bank:saving+ $-2 assets:cash+ $1 expenses:food+ $1 expenses:supplies+ $-1 income:gifts+ $-1 income:salary+ $1 liabilities:debts+--------------------+ 0 ++Accounts with a zero balance (and no non-zero subaccounts, in tree+mode - see below) are hidden by default. Use -E/--empty to show them+(revealing assets:bank:checking here):++$ hledger -f examples/sample.journal bal -E+ 0 assets:bank:checking+ $1 assets:bank:saving+ $-2 assets:cash+ $1 expenses:food+ $1 expenses:supplies+ $-1 income:gifts+ $-1 income:salary+ $1 liabilities:debts+--------------------+ 0 ++The total of the amounts displayed is shown as the last line, unless+-N/--no-total is used.++Balance report line format++For single-period balance reports displayed in the terminal (only), you+can use --format FMT to customise the format and content of each line.+Eg:++$ hledger -f examples/sample.journal balance --format "%20(account) %12(total)"+ assets $-1+ bank:saving $1+ cash $-2+ expenses $2+ food $1+ supplies $1+ income $-2+ gifts $-1+ salary $-1+ liabilities:debts $1+---------------------------------+ 0++The FMT format string specifies the formatting applied to each+account/balance pair. It may contain any suitable text, with data fields+interpolated like so:++%[MIN][.MAX](FIELDNAME)++- MIN pads with spaces to at least this width (optional)++- MAX truncates at this width (optional)++- FIELDNAME must be enclosed in parentheses, and can be one of:++ - depth_spacer - a number of spaces equal to the account's depth, or+ if MIN is specified, MIN * depth spaces.+ - account - the account's name+ - total - the account's balance/posted total, right justified++Also, FMT can begin with an optional prefix to control how+multi-commodity amounts are rendered:++- %_ - render on multiple lines, bottom-aligned (the default)+- %^ - render on multiple lines, top-aligned+- %, - render on one line, comma-separated++There are some quirks. Eg in one-line mode, %(depth_spacer) has no+effect, instead %(account) has indentation built in. Experimentation may+be needed to get pleasing results.++Some example formats:++- %(total) - the account's total+- %-20.20(account) - the account's name, left justified, padded to 20+ characters and clipped at 20 characters+- %,%-50(account) %25(total) - account name padded to 50 characters,+ total padded to 20 characters, with multiple commodities rendered on+ one line+- %20(total) %2(depth_spacer)%-(account) - the default format for the+ single-column balance report. The total field keeps this 20-character+ width as a minimum, but widens automatically when displayed amounts+ need more room.++Filtered balance report++You can show fewer accounts, a different time period, totals from+cleared transactions only, etc. by using query arguments or options to+limit the postings being matched. Eg:++$ hledger -f examples/sample.journal bal --cleared assets date:200806+ $-2 assets:cash+--------------------+ $-2 ++List or tree mode++By default, or with -l/--flat, accounts are shown as a flat list with+their full names visible, as in the examples above.++With -t/--tree, the account hierarchy is shown, with subaccounts' "leaf"+names indented below their parent:++$ hledger -f examples/sample.journal balance+ $-1 assets+ $1 bank:saving+ $-2 cash+ $2 expenses+ $1 food+ $1 supplies+ $-2 income+ $-1 gifts+ $-1 salary+ $1 liabilities:debts+--------------------+ 0++Notes:++- "Boring" accounts are combined with their subaccount for more compact+ output, unless --no-elide is used. Boring accounts have no balance of+ their own and just one subaccount (eg assets:bank and liabilities+ above).++- All balances shown are "inclusive", ie including the balances from all+ subaccounts. Note this means some repetition in the output, which+ requires explanation when sharing reports with+ non-plaintextaccounting-users. A tree mode report's final total is the+ sum of the top-level balances shown, not of all the balances shown.++- Each group of sibling accounts (ie, under a common parent) is sorted+ separately.++In list mode, --no-elide shows parent accounts as well, with their+exclusive balances. These are zero unless the parent has postings of its+own, so -E/--empty is usually also needed to make them visible.+Together, these flags guarantee a complete table of all posted-to+accounts and their parents, with full names:++$ hledger -f examples/sample.journal balance --no-elide -E+ 0 assets+ 0 assets:bank+ 0 assets:bank:checking+ $1 assets:bank:saving+ $-2 assets:cash+ 0 expenses+ $1 expenses:food+ $1 expenses:supplies+ 0 income+ $-1 income:gifts+ $-1 income:salary+ 0 liabilities+ $1 liabilities:debts+--------------------+ 0++This can be useful eg when exporting to a spreadsheet which will look up+balances by account name.++In tree mode, --full-names writes each account's full name instead of+indenting leaf names, while keeping tree mode's inclusive balances. So+--tree --no-elide --full-names -E shows the same complete table as+above, but with inclusive balances:++$ hledger -f examples/sample.journal balance --tree --no-elide --full-names -E+ $-1 assets+ $1 assets:bank+ 0 assets:bank:checking+ $1 assets:bank:saving+ $-2 assets:cash+ $2 expenses+ $1 expenses:food+ $1 expenses:supplies+ $-2 income+ $-1 income:gifts+ $-1 income:salary+ $1 liabilities+ $1 liabilities:debts+--------------------+ 0++Note that in this variant, parent and subaccount balances overlap, so+(as in any tree mode report) the rows sum to more than the final total.++Depth limiting++With a depth:NUM query, or --depth NUM option, or just -NUM (eg: -3)+balance reports will show accounts only to the specified depth, hiding+the deeper subaccounts. This can be useful for getting an overview+without too much detail.++Account balances at the depth limit always include the balances from any+deeper subaccounts (even in list mode). Eg, limiting to depth 1:++$ hledger -f examples/sample.journal balance -1+ $-1 assets+ $2 expenses+ $-2 income+ $1 liabilities+--------------------+ 0 ++Dropping top-level accounts++You can also hide one or more top-level account name parts, using+--drop NUM. This can be useful for hiding repetitive top-level account+names:++$ hledger -f examples/sample.journal bal expenses --drop 1+ $1 food+ $1 supplies+--------------------+ $2 ++Showing declared accounts++With --declared, accounts which have been declared with an account+directive will be included in the balance report, even if they have no+transactions. (Since they will have a zero balance, you will also need+-E/--empty to see them.)++More precisely, leaf declared accounts (with no subaccounts) will be+included, since those are usually the more useful in reports.++The idea of this is to be able to see a useful "complete" balance+report, even when you don't have transactions in all of your declared+accounts yet.++Sorting by amount++With -S/--sort-amount, accounts with the largest (most positive)+balances are shown first. Eg: hledger bal expenses -MAS shows your+biggest averaged monthly expenses first. When more than one commodity is+present, they will be sorted by the alphabetically earliest commodity+first, and then by subsequent commodities (if an amount is missing a+commodity, it is treated as 0).++Revenues and liability balances are typically negative, however, so -S+shows these in reverse order. To work around this, you can add --invert+to flip the signs. Or you could use one of the higher-level balance+reports (bs, is..), which flip the sign automatically (eg:+hledger is -MAS).++Percentages++With -%/--percent, balance reports show each account's value expressed+as a percentage of the (column) total.++Note it is not useful to calculate percentages if the amounts in a+column have mixed signs. In this case, make a separate report for each+sign, eg:++$ hledger bal -% amt:`>0`+$ hledger bal -% amt:`<0`++Similarly, if the amounts in a column have mixed commodities, convert+them to one commodity with -B, -V, -X or --value, or make a separate+report for each commodity:++$ hledger bal -% cur:\\$+$ hledger bal -% cur:€++Multi-period balance report++With a report interval (set by the -D/--daily, -W/--weekly,+-M/--monthly, -Q/--quarterly, -Y/--yearly, or -p/--period flag), balance+shows a tabular report, with columns representing successive time+periods (and a title):++$ hledger -f examples/sample.journal bal --quarterly income expenses -E+Balance changes in 2008:++ || 2008q1 2008q2 2008q3 2008q4 +===================++=================================+ expenses:food || 0 $1 0 0 + expenses:supplies || 0 $1 0 0 + income:gifts || 0 $-1 0 0 + income:salary || $-1 0 0 0 +-------------------++---------------------------------+ || $-1 $1 0 0 ++Notes:++- The report's start/end dates will be expanded, if necessary, to fully+ encompass the displayed subperiods (so that the first and last+ subperiods have the same duration as the others).+- Leading and trailing periods (columns) containing all zeroes are not+ shown, unless -E/--empty is used.+- Accounts (rows) containing all zeroes are not shown, unless -E/--empty+ is used.+- Amounts with many commodities are shown in abbreviated form, unless+ --no-elide is used.+- Average and/or total columns can be added with the -A/--average and+ -T/--row-total flags.+- The --transpose flag can be used to exchange rows and columns.+ Repeating it reverses its effect (an even number of --transpose flags+ has no effect).+- The --pivot FIELD option causes a different transaction field to be+ used as "account name". See PIVOTING.+- The --summary-only flag (--summary also works) hides all but the Total+ and Average columns (those should be enabled with --row-total and+ -A/--average).++Multi-period reports with many periods can be too wide for easy viewing+in the terminal. Here are some ways to handle that:++- Hide the totals row with -N/--no-total+- Filter to a single currency with cur:+- Convert to a single currency with -V [--infer-market-price]+- Use a more compact layout like --layout=bare+- Maximize the terminal window+- Reduce the terminal's font size+- View with a pager like less, eg: hledger bal -D --color=yes | less -RS+- Output as CSV and use a CSV viewer like visidata+ (hledger bal -D -O csv | vd -f csv), Emacs' csv-mode+ (M-x csv-mode, C-c C-a), or a spreadsheet+ (hledger bal -D -o a.csv && open a.csv)+- Output as HTML and view with a browser:+ hledger bal -D -o a.html && open a.html++Balance change, end balance++It's important to be clear on the meaning of the numbers shown in+balance reports. Here is some terminology we use:++A balance change is the net amount added to, or removed from, an account+during some period.++An end balance is the amount accumulated in an account as of some date+(and some time, but hledger doesn't store that; assume end of day in+your timezone). It is the sum of previous balance changes.++We call it a historical end balance if it includes all balance changes+since the account was created. For a real world account, this means it+will match the "historical record", eg the balances reported in your+bank statements or bank web UI. (If they are correct!)++In general, balance changes are what you want to see when reviewing+revenues and expenses, and historical end balances are what you want to+see when reviewing or reconciling asset, liability and equity accounts.++balance shows balance changes by default. To see accurate historical end+balances:++1. Initialise account starting balances with an "opening balances"+ transaction (a transfer from equity to the account), unless the+ journal covers the account's full lifetime.++2. Include all of of the account's prior postings in the report, by not+ specifying a report start date, or by using the -H/--historical+ flag. (-H causes report start date to be ignored when summing+ postings.)++Balance report modes++The balance command is quite flexible; here is the full detail on how to+control what it reports. If the following seems complicated, don't+worry - this is for advanced reporting, and it does take time and+experimentation to get familiar with all the report modes.++There are three important option groups:++hledger balance [CALCULATIONMODE] [ACCUMULATIONMODE] [VALUATIONMODE] ...++Calculation mode++The basic calculation to perform for each table cell. It is one of:++- --sum : sum the posting amounts (default)+- --budget : sum the amounts, but also show the budget goal amount (for+ each account/period)+- --valuechange : show the change in period-end historical balance+ values (caused by deposits, withdrawals, and/or market price+ fluctuations)+- --gain : show capital gain/loss for each account: the current valued+ balance minus its cost. For lot-tracked commodities the cost is the+ cost basis of the units still held, so this is the unrealised gain.+ For other commodities it is the net of postings' transacted costs+ (acquisition costs minus disposal proceeds): where nothing has been+ sold this too is the unrealised gain, but once disposals exist the+ figure also includes the realised gain on the disposed units, so it is+ best read as "total gain since inception" (to separate realised and+ unrealised gains, track lots). Compare --valuechange, which shows how+ much the value moved in a period, from price changes and from buying+ and selling. See Unrealised gains for examples.+- --count : show the count of postings++Accumulation mode++How amounts should accumulate across a report's subperiods/columns.+Another way to say it: which time period's postings should contribute to+each cell's calculation. It is one of:++- --change : calculate with postings from column start to column end, ie+ "just this column". Typically used to see revenues/expenses. (default+ for balance, cashflow, incomestatement)++- --cumulative : calculate with postings from report start to column+ end, ie "previous columns plus this column". Typically used to show+ changes accumulated since the report's start date. Not often used.++- --historical/-H : calculate with postings from journal start to column+ end, ie "all postings from before report start date until this+ column's end". Typically used to see historical end balances of+ assets/liabilities/equity. (default for balancesheet,+ balancesheetequity)++Valuation mode++Which kind of value or cost conversion should be applied, if any, before+displaying the report. See Cost reporting and Value reporting for more+about conversions.++A valuation (or cost) mode can be selected with the --value option:++- no conversion : don't convert to cost or value (default)+- --value=cost[,COMM] : convert amounts to cost (then optionally to some+ other commodity)+- --value=then[,COMM] : convert amounts to market value on transaction+ dates+- --value=end[,COMM] : convert amounts to market value on period end+ date(s)+ (default with --valuechange, --gain)+- --value=now[,COMM] : convert amounts to market value on today's date+- --value=YYYY-MM-DD[,COMM] : convert amounts to market value on another+ date++or with the legacy -B/-V/-X options, which are equivalent and easier to+type:++- -B/--cost : like --value=cost+- -V/--market : like --value=end+- -X COMM/--exchange COMM : like --value=end,COMM++Note that --value can also convert to cost, as a convenience; but+actually --cost and --value are independent options, and could be used+together.++Combining balance report modes++Most combinations of these modes produce reasonable reports. The+following restrictions are applied:++- --valuechange implies --value=end+- --valuechange makes --change the default when used with the+ balancesheet/balancesheetequity commands+- --cumulative or --historical disables --row-total/-T++For reference, here is what the combinations of accumulation and+valuation show:++ ------------------------------------------------------------------------------------------------+ Valuation:> no valuation --value= then --value= end --value= YYYY-MM-DD /now+ Accumulation:v + ------------------ ---------------- ----------------- --------------- --------------------------+ --change change in period sum of period-end DATE-value of change in+ posting-date value of change period+ market values in in period + period ++ --cumulative change from sum of period-end DATE-value of change from+ report start to posting-date value of change report start to period end+ period end market values from report + from report start start to period + to period end end ++ --historical /-H change from sum of period-end DATE-value of change from+ journal start to posting-date value of change journal start to period+ period end market values from journal end+ (historical end from journal start to period + balance) start to period end + end + ------------------------------------------------------------------------------------------------++Budget report++The balance --budget report is like a regular balance report, but with+two main differences:++- Budget goals and performance percentages are also shown, in brackets+- Accounts which don't have budget goals are hidden by default.++This is useful for comparing planned and actual income, expenses, time+usage, etc.++Periodic transaction rules are used to define budget goals. For example,+here's a periodic rule defining monthly goals for bus travel and food+expenses:++;; Budget+~ monthly+ (expenses:bus) $30+ (expenses:food) $400++After recording some actual expenses,++;; Two months worth of expenses+2017-11-01+ income $-1950+ expenses:bus $35+ expenses:food:groceries $310+ expenses:food:dining $42+ expenses:movies $38+ assets:bank:checking++2017-12-01+ income $-2100+ expenses:bus $53+ expenses:food:groceries $380+ expenses:food:dining $32+ expenses:gifts $100+ assets:bank:checking++we can see a budget report like this:++$ hledger bal -M --budget+Budget performance in 2017-11-01..2017-12-31:++ || Nov Dec +===============++============================================+ <unbudgeted> || $-425 $-565 + expenses || $425 [ 99% of $430] $565 [131% of $430] + expenses:bus || $35 [117% of $30] $53 [177% of $30] + expenses:food || $352 [ 88% of $400] $412 [103% of $400] +---------------++--------------------------------------------+ || 0 [ 0% of $430] 0 [ 0% of $430] ++This is "goal-based budgeting"; you define goals for accounts and+periods, often recurring, and hledger shows performance relative to the+goals. This contrasts with "envelope budgeting", which is more detailed+and strict - useful when cash is tight, but also quite a bit more work.+https://plaintextaccounting.org/Budgeting has more on this topic.++Using the budget report++Historically this report has been confusing and fragile. hledger's+version should be relatively robust and intuitive, but you may still+find surprises. Here are more notes to help with learning and+troubleshooting.++- In the above example, expenses:bus and expenses:food are shown because+ they have budget goals during the report period.++- Their parent expenses is also shown, with budget goals aggregated from+ the children.++- The subaccounts expenses:food:groceries and expenses:food:dining are+ not shown since they have no budget goal of their own, but they+ contribute to expenses:food's actual amount.++- Unbudgeted accounts expenses:movies and expenses:gifts are also not+ shown, but they contribute to expenses's actual amount.++- The other unbudgeted accounts income and assets:bank:checking are+ grouped as <unbudgeted>.++- --depth or depth: can be used to limit report depth in the usual way+ (but will not reveal unbudgeted subaccounts).++- Amounts are always inclusive of subaccounts (even in -l/--list mode).++- Numbers displayed in a --budget report will not always agree with the+ totals, because of hidden unbudgeted accounts; this is normal.+ -E/--empty can be used to reveal the hidden accounts.++- In the periodic rules used for setting budget goals, unbalanced+ postings are convenient.++- You can filter budget reports with the usual queries, eg to focus on+ particular accounts. It's common to restrict them to just expenses.+ (The <unbudgeted> account is occasionally hard to exclude; this is+ because of date surprises, discussed below.)++- Only the account, account type, depth, date and commodity parts of the+ query are applied to the budget goals; the other parts+ (status:/-U/-P/-C, code:, desc:, payee:, note:, tag:, real:, amt:)+ select actual transactions and postings only. So eg --budget --cleared+ compares your cleared spending against the full budget goals.++- When you have multiple currencies, you may want to convert them to one+ (-X COMM --infer-market-prices) and/or show just one at a time+ (cur:COMM). If you do need to show multiple currencies at once,+ --layout bare can be helpful.++- You can "roll over" amounts (actual and budgeted) to the next period+ with --cumulative.++See also: https://hledger.org/budgeting.html.++Budget date surprises++With small data, or when starting out, some of the generated budget goal+transaction dates might fall outside the report periods. Eg with the+following journal and report, the first period appears to have no+expenses:food budget. (Also the <unbudgeted> account should be excluded+by the expenses query, but isn't.):++~ monthly in 2020+ (expenses:food) $500++2020-01-15+ expenses:food $400+ assets:checking++$ hledger bal --budget expenses+Budget performance in 2020-01-15:++ || 2020-01-15 +===============++====================+ <unbudgeted> || $400 + expenses:food || 0 [ 0% of $500] +---------------++--------------------+ || $400 [80% of $500] ++In this case, the budget goal transactions are generated on first days+of of month (this can be seen with+hledger print --forecast tag:generated expenses). Whereas the report+period defaults to just the 15th day of january (this can be seen from+the report table's column headings).++To fix this kind of thing, be more explicit about the report period+(and/or the periodic rules' dates). In this case, adding -b 2020 does+the trick.++Selecting budget goals++By default, the budget report uses all available periodic transaction+rules to generate goals. This includes rules with a different report+interval from your report. Eg if you have daily, weekly and monthly+periodic rules, all of these will contribute to the goals in a monthly+budget report.++You can select a subset of periodic rules by providing an argument to+the --budget flag. --budget=DESCPAT will match all periodic rules whose+description contains DESCPAT, a case-insensitive substring (not a+regular expression or query). This means you can give your periodic+rules descriptions (remember that two spaces are needed between period+expression and description), and then select from multiple budgets+defined in your journal.++Budgeting vs forecasting++--forecast and --budget both use the periodic transaction rules in the+journal to generate temporary transactions for reporting purposes.+However they are separate features - though you can use both at the same+time if you want. Here are some differences between them:++ -----------------------------------------------------------------------+ --forecast --budget+ -------------------------------------- --------------------------------+ is a general option; it enables is a balance command option; it+ forecasting with all reports selects the balance report's+ budget mode++ generates visible transactions which generates invisible transactions+ appear in reports which produce goal amounts++ generates forecast transactions from generates budget goal+ after the last regular transaction, to transactions throughout the+ the end of the report period; or with report period, optionally+ an argument --forecast=PERIODEXPR restricted by periods specified+ generates them throughout the in the periodic transaction+ specified period, both optionally rules+ restricted by periods specified in the + periodic transaction rules ++ uses all periodic rules uses all periodic rules; or with+ an argument --budget=DESCPAT+ uses just the rules matched by+ DESCPAT+ -----------------------------------------------------------------------++Balance report layout++The --layout option affects how balance and the other balance-like+commands show multi-commodity amounts and commodity symbols. It can+improve readability, for humans and/or machines (other software). It has+four possible values:++- --layout=wide[,WIDTH]: commodities are shown on a single line,+ optionally elided to WIDTH+- --layout=tall: each commodity is shown on a separate line+- --layout=bare: commodity symbols are in their own column, amounts are+ bare numbers+- --layout=barewide: commodities are shown on a single line, all in+ separate columns, amounts are bare numbers+- --layout=tidy: data is normalised to easily-consumed "tidy" form, with+ one row per data value. (This one is currently supported only by the+ balance command.)++Here are the --layout modes supported by each output format Only CSV+output supports all of them:++ - txt csv html json sql+ ---------- ----- ----- ------ ------ -----+ wide Y Y Y + tall Y Y Y + bare Y Y Y + barewide Y Y Y + tidy Y ++Choice of layouts for budget reports is more restricted:++ - txt csv html json sql+ ---------- ----- ----- ------ ------ -----+ wide Y Y Y + tall Y + bare Y Y Y + barewide Y Y + tidy ++Examples:++Wide layout++With many commodities, reports can be very wide:++$ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -T -Y --layout=wide+Balance changes in 2012-01-01..2014-12-31:++ || 2012 2013 2014 Total +==================++====================================================================================================================================================================================================================+ Assets:US:ETrade || 10.00 ITOT, 337.18 USD, 12.00 VEA, 106.00 VHT 70.00 GLD, 18.00 ITOT, -98.12 USD, 10.00 VEA, 18.00 VHT -11.00 ITOT, 4881.44 USD, 14.00 VEA, 170.00 VHT 70.00 GLD, 17.00 ITOT, 5120.50 USD, 36.00 VEA, 294.00 VHT +------------------++--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ || 10.00 ITOT, 337.18 USD, 12.00 VEA, 106.00 VHT 70.00 GLD, 18.00 ITOT, -98.12 USD, 10.00 VEA, 18.00 VHT -11.00 ITOT, 4881.44 USD, 14.00 VEA, 170.00 VHT 70.00 GLD, 17.00 ITOT, 5120.50 USD, 36.00 VEA, 294.00 VHT ++A width limit reduces the width, but some commodities will be hidden:++$ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -T -Y --layout=wide,32+Balance changes in 2012-01-01..2014-12-31:++ || 2012 2013 2014 Total +==================++===========================================================================================================================+ Assets:US:ETrade || 10.00 ITOT, 337.18 USD, 2 more.. 70.00 GLD, 18.00 ITOT, 3 more.. -11.00 ITOT, 3 more.. 70.00 GLD, 17.00 ITOT, 3 more.. +------------------++---------------------------------------------------------------------------------------------------------------------------+ || 10.00 ITOT, 337.18 USD, 2 more.. 70.00 GLD, 18.00 ITOT, 3 more.. -11.00 ITOT, 3 more.. 70.00 GLD, 17.00 ITOT, 3 more.. ++Tall layout++Each commodity gets a new line (may be different in each column), and+account names are repeated:++$ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -T -Y --layout=tall+Balance changes in 2012-01-01..2014-12-31:++ || 2012 2013 2014 Total +==================++==================================================+ Assets:US:ETrade || 10.00 ITOT 70.00 GLD -11.00 ITOT 70.00 GLD + Assets:US:ETrade || 337.18 USD 18.00 ITOT 4881.44 USD 17.00 ITOT + Assets:US:ETrade || 12.00 VEA -98.12 USD 14.00 VEA 5120.50 USD + Assets:US:ETrade || 106.00 VHT 10.00 VEA 170.00 VHT 36.00 VEA + Assets:US:ETrade || 18.00 VHT 294.00 VHT +------------------++--------------------------------------------------+ || 10.00 ITOT 70.00 GLD -11.00 ITOT 70.00 GLD + || 337.18 USD 18.00 ITOT 4881.44 USD 17.00 ITOT + || 12.00 VEA -98.12 USD 14.00 VEA 5120.50 USD + || 106.00 VHT 10.00 VEA 170.00 VHT 36.00 VEA + || 18.00 VHT 294.00 VHT ++Bare layout++Commodity symbols are kept in one column, each commodity has its own+row, amounts are bare numbers, account names are repeated:++$ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -T -Y --layout=bare+Balance changes in 2012-01-01..2014-12-31:++ || Commodity 2012 2013 2014 Total +==================++=============================================+ Assets:US:ETrade || GLD 0 70.00 0 70.00 + Assets:US:ETrade || ITOT 10.00 18.00 -11.00 17.00 + Assets:US:ETrade || USD 337.18 -98.12 4881.44 5120.50 + Assets:US:ETrade || VEA 12.00 10.00 14.00 36.00 + Assets:US:ETrade || VHT 106.00 18.00 170.00 294.00 +------------------++---------------------------------------------+ || GLD 0 70.00 0 70.00 + || ITOT 10.00 18.00 -11.00 17.00 + || USD 337.18 -98.12 4881.44 5120.50 + || VEA 12.00 10.00 14.00 36.00 + || VHT 106.00 18.00 170.00 294.00 ++Bare layout also affects CSV output, which is useful for producing data+that is easier to consume, eg for making charts:++$ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -O csv --layout=bare+"account","commodity","balance"+"Assets:US:ETrade","GLD","70.00"+"Assets:US:ETrade","ITOT","17.00"+"Assets:US:ETrade","USD","5120.50"+"Assets:US:ETrade","VEA","36.00"+"Assets:US:ETrade","VHT","294.00"+"Total:","GLD","70.00"+"Total:","ITOT","17.00"+"Total:","USD","5120.50"+"Total:","VEA","36.00"+"Total:","VHT","294.00"++Bare layout will sometimes display an extra row for the no-symbol+commodity, because of zero amounts (hledger treats zeroes as+commodity-less, usually). This can break hledger-bar confusingly+(workaround: add a cur: query to exclude the no-symbol row).++Barewide layout++Commodity symbols are spread in the table headers, each commodity has+its own column, all column groups share the same set of commodities even+if in one commodity column all values are zero. For consistency you may+think of layout bare as baretall.++$ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -T -Y --layout=barewide+Balance changes in 2012-01-01..2014-12-31:++ || 2012 (GLD) 2012 (ITOT) 2012 (USD) 2012 (VEA) 2012 (VHT) 2013 (GLD) 2013 (ITOT) 2013 (USD) 2013 (VEA) 2013 (VHT) 2014 (GLD) 2014 (ITOT) 2014 (USD) 2014 (VEA) 2014 (VHT) Total (GLD) Total (ITOT) Total (USD) Total (VEA) Total (VHT) +==================++===================================================================================================================================================================================================================================================================+ Assets:US:ETrade || 0 10.00 337.18 12.00 106.00 70.00 18.00 -98.12 10.00 18.00 0 -11.00 4881.44 14.00 170.00 70.00 17.00 5120.50 36.00 294.00 +------------------++-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ || 0 10.00 337.18 12.00 106.00 70.00 18.00 -98.12 10.00 18.00 0 -11.00 4881.44 14.00 170.00 70.00 17.00 5120.50 36.00 294.00 ++Barewide layout is very useful for FODS and CSV output, since you can+easily use LibreOffice's VLOOKUP function for accessing numbers in a+table with mixed commodities.++Tidy layout++This produces normalised "tidy data" (see+https://cran.r-project.org/web/packages/tidyr/vignettes/tidy-data.html)+where every variable has its own column and each row represents a single+data point. This is the easiest kind of data for other software to+consume:++$ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -Y -O csv --layout=tidy+"account","period","start_date","end_date","commodity","value"+"Assets:US:ETrade","2012","2012-01-01","2012-12-31","GLD","0"+"Assets:US:ETrade","2012","2012-01-01","2012-12-31","ITOT","10.00"+"Assets:US:ETrade","2012","2012-01-01","2012-12-31","USD","337.18"+"Assets:US:ETrade","2012","2012-01-01","2012-12-31","VEA","12.00"+"Assets:US:ETrade","2012","2012-01-01","2012-12-31","VHT","106.00"+"Assets:US:ETrade","2013","2013-01-01","2013-12-31","GLD","70.00"+"Assets:US:ETrade","2013","2013-01-01","2013-12-31","ITOT","18.00"+"Assets:US:ETrade","2013","2013-01-01","2013-12-31","USD","-98.12"+"Assets:US:ETrade","2013","2013-01-01","2013-12-31","VEA","10.00"+"Assets:US:ETrade","2013","2013-01-01","2013-12-31","VHT","18.00"+"Assets:US:ETrade","2014","2014-01-01","2014-12-31","GLD","0"+"Assets:US:ETrade","2014","2014-01-01","2014-12-31","ITOT","-11.00"+"Assets:US:ETrade","2014","2014-01-01","2014-12-31","USD","4881.44"+"Assets:US:ETrade","2014","2014-01-01","2014-12-31","VEA","14.00"+"Assets:US:ETrade","2014","2014-01-01","2014-12-31","VHT","170.00"++Balance report output++As noted in Output format, if you choose HTML output (by using -O html+or -o somefile.html), you can create a hledger.css file in the same+directory to customise the report's appearance.++The HTML and FODS output formats can generate hyperlinks to hledger-web+register views: an account name links to the account's transactions, a+period heading to the period's transactions, and, in the default layout,+a figure to the transactions it is made of, in a register whose final+balance is that figure (a historical balance report asks the register+for its historical mode). The two can differ when a transaction's+postings have dates of their own, since the report counts such a posting+in its own period while the register shows its whole transaction. Each+link says where it leads in its title, which browsers show on hover.+E.g. if your hledger-web server is reachable at http://localhost:5000+then you might run the balance command with the extra option+--base-url=http://localhost:5000. You can also produce relative links,+like --base-url="some/path" or --base-url="".)++Balance charts++With --chart, balance shows a chart of the report instead of a table,+choosing a useful kind of chart automatically. In the terminal, this is+a bar chart drawn with text characters:++$ hledger -f examples/bcexample.journal bal -M expenses:food -b 2013 -e 2013-04 cur:USD --chart -w 70+Balance changes in 2013Q1:++█ Expenses:Food:Groceries ▓ Expenses:Food:Restaurant++Jan 396.46 USD █████████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓+Feb 481.48 USD ████████████████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓+Mar 603.32 USD ██████████████████████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓++- A multi-period report of balance changes is charted as stacked bars+ per period, showing the net total as the value (and with net, see+ below, as a line mark, ┃ in text).+- A multi-period report of end balances (--cumulative, -H) is charted+ the same way in text (and as lines in graphical charts).+- With --chart=grouped, the accounts are stacked in a bar for each+ account type (assets, liabilities, equity, revenues, expenses, then+ any accounts of unknown type), side by side in each period, so that+ the types can be compared. Amounts keep their signs (eg liabilities+ are usually below zero), and end balances are drawn as bars too. In+ text charts, each period has a row for each type, and one for the+ total. Without a report interval, the whole report period is charted+ this way, as one period.+- A single-period report is charted as one bar per account, with the+ total below the chart (as a number only, since it belongs to no+ account's bar, even with net).++Negative amounts grow left from an axis, positive amounts right. Each+account has its own colour (when colour is enabled) and fill character;+fill characters repeat after four accounts. The legend lists the+accounts visible in the chart (an account too small to fill a character+cell is left out). Accounts are coloured by their account type, with+conventional colours: assets blue, liabilities amber, equity violet,+revenues green, expenses red; several accounts of one type get different+shades of its colour (up to eight; beyond that, shades are shared). (In+terminals which advertise 24-bit colour support, by setting+COLORTERM=truecolor, these are the same exact colours as in SVG charts;+otherwise they are the terminal's basic blue, yellow, magenta, green and+red, whose shades depend on its colour theme.) Accounts of unknown type+get distinct colours instead. But when it shows just one account (in+each panel), there is nothing to tell apart, so the account has its+type's colour, or if its type is unknown, cyan, a colour no account type+uses. A chart showing just a total (eg with -0, or of all accounts'+transaction counts) is also cyan. Colours and fill characters are chosen+by account name, not by position, so an account usually keeps its colour+in other charts: with or without -S, or when you exclude other accounts+to see more detail. (Not always, since there are only a few colours: an+account may get a different one when some accounts are added or+removed.) The chart fills the terminal width, or the width set by+-w/--width (except for posting counts, with --count, which use at most+one character per posting). It is drawn with unicode block characters,+or with ASCII characters if the system's text encoding is not UTF-8.++There is one chart panel per commodity. You can reduce this by+converting to one commodity (eg -X USD) or selecting some (eg cur:USD);+hledger suggests this when there are more than 8 panels. In tree mode,+each account's own amounts are stacked, excluding its subaccounts', so+that nothing is counted twice. At most 8 accounts are shown per panel;+the smallest are combined into "other" series, one for each account type+(so eg assets and liabilities are never combined), and each type keeps+at least its largest account. "other" series are grey, or when coloured+by type, a greyed version of their type's colour. The total is omitted+with -N or --percent. Charts draw it (as a line or marks) only with net,+eg --chart=net (or --chart=grouped,net). net draws the total where a bar+combines several amounts; a chart of one account, or with one bar per+account, does not draw it. (Text charts show it as a number either way.)++In a chart of balance changes per period, -T/--row-total and+-A/--average show the net total's total and average per period on a line+below the chart, eg Total 11, Average 0.9; and in graphical charts, the+average is also drawn as a dashed line across the chart, with an entry+in the legend. In a chart of end balances (eg with -H, or bs), -A shows+the average of the net total's period-end balances in the same way+(there is no total).++Each chart is scaled to fit its values. To draw charts at a fixed scale+instead, so that you can compare them (eg this month's chart with last+month's), add a SCALE amount: --chart=SCALE. This is the amount that the+chart spans; eg with --chart=5000, a bar of 5000 fills the chart. If the+chart also has negative values, they take the room they need and+positive values get the rest. Bars that don't fit are clipped, with a+mark at the edge (▸ or ◂ in text, a small triangle in SVG); lines go off+the edge. A SCALE with a commodity symbol (eg --chart='5000 USD')+applies to that commodity's panel, and one without, to the others. SCALE+can follow KIND and net, and several SCALEs can be given, separated by+commas (eg --chart='auto,5000 USD,4000 EUR'); so a SCALE can't contain a+comma: write it without digit group marks, or with spaces or periods (eg+10 000 EUR). A number like 10.000 is read using that commodity's decimal+mark, as it is shown in the report: eg in a journal where EUR is written+with a decimal comma, 10.000 EUR is ten thousand. For the same scale in+text charts, use the same width too (-w).++With SVG output (-o FILE.svg or -O svg), balance always shows a chart,+as a graphical image. Time runs along the x axis, and end balances are+drawn as lines. A single-period report is drawn as vertical bars, one+per account, with the account names below (angled if needed) and values+above the bars (where they fit); or with more than 30 accounts, as+horizontal bars. The y axis shows the unit only on its top (or bottom)+label. In an HTML page, the chart shrinks to fit a narrower window.++With HTML output, --chart shows the chart (as SVG), with the report's+table collapsed below it (click Report details to show it).++With -O csv, -O tsv or -O json, --chart shows the chart's data, eg to+inspect it or chart it with other tools.++The compound balance commands (balancesheet, balancesheetequity,+cashflow, incomestatement) can show charts in the same ways. They chart+their sections' accounts, with the net total (as a number in text+charts, and with net, as a mark in text charts or a line in SVG charts),+in one of two layouts:++- diverging (the default, or with --chart=diverging): at each period,+ all accounts are stacked in one bar, showing each amount as its+ contribution to the net total: sections that add to it (eg assets,+ revenues) above zero, and sections that subtract from it (eg+ liabilities, expenses) below zero. (This is also why an is chart draws+ expenses below zero while bal draws them above, as their raw amounts+ are positive; bal --invert gives the same signs.) In text charts, each+ period is a row showing the net total, the totals of the sections on+ each side at the ends of the bar (as the report's table shows them;+ headed by the sections' names), and with net, a mark at the net+ total's position.++- grouped (with --chart=grouped): at each period, each section's+ accounts are stacked in a bar of their own, side by side, so that the+ sections' sizes can be compared. Amounts are shown as the tables show+ them, eg expenses as well as revenues are positive. In text charts,+ each period has a row for each section, showing its total, and a row+ showing the net total (and with net, marking it).++Contra amounts - those with the opposite sign to their section's usual+sign, like a refund recorded as a negative expense, or a contra account+like accumulated depreciation - are drawn next to the zero line, hatched+in their account's colour (below zero in the grouped layout, and on the+other side from their section in the diverging layout). They are+included in their section's totals. (Cash flows, in cf, have no usual+sign: decreases are drawn like increases, below zero.) Each section+shows at most five accounts, combining the smallest into "other"; use a+depth limit (eg -1 or -2) for less detail. A single-period report is+charted the same way, with one period. The chart data has one record per+value, with fields: commodity, series (usually an account name), role+(item, other or total), mark (bar, line or marker), x (a period heading,+period end date, or account name), and value. With -T or -A, each+commodity's total or average follows, with role rowtotal or average, and+an empty mark and x. Eg:++$ hledger -f examples/sample.journal bal -M expenses -N --chart -O csv+"commodity","series","role","mark","x","value"+"$","expenses:food","item","bar","Jan","0"+"$","expenses:food","item","bar","Feb","0"+...++Some useful balance reports++Some frequently used balance options/reports are:++- bal -M revenues expenses+ Show revenues/expenses in each month. Also available as the+ incomestatement command.++- bal -M -H assets liabilities+ Show historical asset/liability balances at each month end. Also+ available as the balancesheet command.++- bal -M -H assets liabilities equity+ Show historical asset/liability/equity balances at each month end.+ Also available as the balancesheetequity command.++- bal -M assets not:receivable+ Show changes to liquid assets in each month. Also available as the+ cashflow command.++Also:++- bal -M expenses -2 -SA+ Show monthly expenses summarised to depth 2 and sorted by average+ amount.++- bal -M --budget expenses+ Show monthly expenses and budget goals.++- bal -M --valuechange investments+ Show monthly change in market value of investment assets.++- bal -M -H --gain investments+ Show unrealised gain on investment assets (market value minus cost) at+ each month end.++- bal investments --valuechange -D date:lastweek amt:'>1000' -STA [--invert]+ Show top gainers [or losers] last week
+ Hledger/Cli/Commands/Balance/Internal.hs view
@@ -0,0 +1,393 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE RecordWildCards #-}++module Hledger.Cli.Commands.Balance.Internal where++import Control.Monad (guard)+import Data.List (transpose)+import Data.Set qualified as S+import Data.Text (Text)+import Data.Text qualified as T+import Data.Time (addDays)+import Text.Tabular.AsciiWide (Header(..), Properties(..), Table(..), concatTables)++import Hledger.Utils.I18n qualified as I18n+import Hledger+import Hledger.Cli.Anchor (LinkOpts(..), valueParam, dateTerm, removeDates, withLink, setAccountAnchorWith,+ dateSpanCellWith, totalDateSpanCell, headerDateSpanCell, renderPeriodHeading, amountPhrase)+import Hledger.Write.Spreadsheet (rawTableContent, headerCell,+ addHeaderBorders, addRowSpanHeader,+ cellFromMixedAmount, cellsFromMixedAmount)+import Hledger.Write.Spreadsheet qualified as Ods++++-- Rendering++accountClass :: Ods.Class+accountClass = Ods.Class "account"++-- | The class of an account cell in a tree-mode report: "account", its+-- row's indent (indent-N), and the account's depth (depth-N, its name's+-- level, which a depth limit counts; deeper than the indent when boring+-- parents are squashed into its row), so that a UI can fold the tree, as+-- hledger-web does. In list mode, just "account".+treeAccountClass :: ReportOpts -> Int -> AccountName -> Ods.Class+treeAccountClass opts indent acct+ | accountlistmode_ opts == ALTree = Ods.Class $+ "account indent-" <> T.pack (show indent) <> " depth-" <> T.pack (show (accountNameLevel acct))+ | otherwise = accountClass++data RowClass = Value | Total+ deriving (Eq, Ord, Enum, Bounded, Show)++amountClass :: RowClass -> Ods.Class+amountClass rc =+ Ods.Class $+ case rc of Value -> "amount"; Total -> "amount coltotal"++rowTotalClass :: RowClass -> Ods.Class+rowTotalClass rc =+ Ods.Class $+ case rc of Value -> "amount rowtotal"; Total -> "amount coltotal"++rowAverageClass :: RowClass -> Ods.Class+rowAverageClass rc =+ Ods.Class $+ case rc of Value -> "amount rowaverage"; Total -> "amount colaverage"++-- What to show as heading for the totals row in balance reports ?+-- Currently nothing in terminal, Total: in HTML, FODS and xSV output.+totalRowHeadingText :: Text+totalRowHeadingSpreadsheet :: Text+totalRowHeadingBudgetText :: Text+totalRowHeadingBudgetCsv :: Text++totalRowHeadingText = ""+totalRowHeadingSpreadsheet = "Total:"+totalRowHeadingBudgetText = ""+totalRowHeadingBudgetCsv = "Total:"+++headerWithoutBorders :: [Ods.Cell () text] -> [Ods.Cell Ods.NumLines text]+headerWithoutBorders = map (\c -> c {Ods.cellBorder = Ods.noBorder})++simpleDateSpanCell :: PeriodTitles -> DateSpan -> Ods.Cell Ods.NumLines Text+simpleDateSpanCell ph = Ods.defaultCell . renderPeriodHeading ph++-- | Do this report's figures link to registers? Only when they are+-- sums of postings, which is what a register shows.+figuresLink :: ReportOpts -> Bool+figuresLink ropts = balancecalc_ ropts == CalcChange && not (percent_ ropts)++-- | The register link options of a report's rows: its accumulation+-- mode, the span its columns cover, whether it shows figures with+-- the sign opposite to the register's (as the compound reports' negated+-- sections do), and how it converts amounts.+reportLinkOpts :: ReportOpts -> [DateSpan] -> LinkOpts+reportLinkOpts ropts colspans = LinkOpts {+ loAccum = balanceaccum_ ropts,+ loSpan = spansSpan colspans,+ loDate2 = date2_ ropts,+ loIncludesSubs = True,+ loNegated = normalbalance_ ropts == Just NormallyNegative,+ loValue = valueParam (conversionop_ ropts) (value_ ropts)+}++-- | The link options of one account's row: whether its figures include+-- the subaccounts. In tree mode every row does. In list mode a row+-- excludes them only when some of them have rows of their own; a+-- depth-clipped row, or a parent whose children are not shown, sums them.+rowLinkOpts :: ReportOpts -> [DateSpan] -> S.Set AccountName -> AccountName -> LinkOpts+rowLinkOpts ropts colspans shownParents acct =+ (reportLinkOpts ropts colspans) {+ loIncludesSubs = tree_ ropts || acct `S.notMember` shownParents+ }++-- | The accounts that have a subaccount among the given rows.+shownParentsOf :: [AccountName] -> S.Set AccountName+shownParentsOf = S.fromList . concatMap parentAccountNames++addTotalBorders ::+ (Functor f) =>+ [f (Ods.Cell border text)] -> [f (Ods.Cell Ods.NumLines text)]+addTotalBorders =+ zipWith+ (\border ->+ fmap (\c -> c {+ Ods.cellStyle = Ods.Body Ods.Total,+ Ods.cellBorder = Ods.noBorder {Ods.borderTop = border}}))+ (Ods.DoubleLine : repeat Ods.NoLine)+++nbsp :: Text+nbsp = "\160"+++renderBalanceAcct ::+ ReportOpts -> Text -> (AccountName, AccountName, Int) -> Text+renderBalanceAcct opts space (fullName, displayName, dep) =+ if accountlistmode_ opts == ALTree && not (full_names_ opts)+ then T.replicate (dep*2) space <> displayName+ else accountNameDrop (drop_ opts) fullName++-- FIXME. Have to check explicitly for which to render here, since+-- budgetReport sets accountlistmode to ALTree. Find a principled way to do+-- this.+renderPeriodicAcct ::+ ReportOpts -> Text -> PeriodicReportRow DisplayName a -> Text+renderPeriodicAcct opts space row =+ renderBalanceAcct opts space+ (prrFullName row, prrDisplayName row, prrIndent row)++++multiBalanceHasTotalsColumn :: ReportOpts -> Bool+multiBalanceHasTotalsColumn ropts =+ row_total_ ropts && balanceaccum_ ropts `notElem` [Cumulative, Historical]+++multiBalanceReportAsPartTable ::+ ReportOpts -> [CommoditySymbol] -> MultiBalanceReport ->+ Table T.Text T.Text WideBuilder+multiBalanceReportAsPartTable+ opts@ReportOpts{summary_only_, average_}+ allCommodities+ (PeriodicReport spans items tr) =+ maybetranspose $+ addtotalrow $+ Table+ (Group multiColumnTableInterRowBorder $ map Header $ concat accts)+ (Group multiColumnTableInterColumnBorder $ map Header colheadings)+ (concat rows)+ where+ trc = I18n.trc (translations_ opts)+ colheadings =+ [trc "column heading" "Commodity" | layout_ opts == LayoutBare]+ +++ case layout_ opts of+ LayoutBareWide ->+ liftA2 (\s c -> T.concat [s, " (", c, ")"])+ spanNames allCommodities+ _ -> spanNames+ spanNames =+ (guard (not summary_only_) >>+ map (reportPeriodName opts spans) spans)+ ++ [" " <> trc "column heading" "Total" | multiBalanceHasTotalsColumn opts]+ ++ [trc "column heading" "Average" | average_]+ (accts, rows) = unzip $ fmap fullRowAsTexts items'+ where+ isLeaf rs row = not $ any (\r -> T.isPrefixOf (displayFull (prrName row) <> ":") (displayFull (prrName r))) rs+ items' = if transpose_ opts && tree_ opts+ then filter (isLeaf items) items+ else items+ fullRowAsTexts row = (replicate (length rs) (renderacct row), rs)+ where+ rs = multiBalanceRowAsText opts allCommodities row+ renderacct row' = renderPeriodicAcct opts " " row'+ addtotalrow+ | no_total_ opts = id+ | otherwise =+ let totalrows = multiBalanceRowAsText opts allCommodities tr+ rowhdrs = Group NoLine $ map Header $ totalRowHeadingText : replicate (length totalrows - 1) ""+ colhdrs = Header [] -- unused, concatTables will discard+ in (flip (concatTables SingleLine) $ Table rowhdrs colhdrs totalrows)+ maybetranspose | transpose_ opts = \(Table rh ch vals) -> Table ch rh (transpose vals)+ | otherwise = id+ multiColumnTableInterRowBorder = NoLine+ multiColumnTableInterColumnBorder = if pretty_ opts then SingleLine else NoLine+++multiBalanceRowAsText ::+ ReportOpts -> [CommoditySymbol] -> PeriodicReportRow a MixedAmount -> [[WideBuilder]]+multiBalanceRowAsText opts allCommodities =+ rawTableContent .+ multiBalanceRowAsCellBuilders oneLineNoCostFmt{displayColour=color_ opts}+ opts [] allCommodities+ Value (simpleDateSpanCell $ period_titles_ opts)++multiBalanceRowAsCellBuilders ::+ AmountFormat -> ReportOpts -> [DateSpan] -> [CommoditySymbol] ->+ RowClass -> (DateSpan -> Ods.Cell Ods.NumLines Text) ->+ PeriodicReportRow a MixedAmount ->+ [[Ods.Cell Ods.NumLines WideBuilder]]+multiBalanceRowAsCellBuilders bopts ropts@ReportOpts{..} colspans allCommodities+ rc renderDateSpanCell (PeriodicReportRow _acct as rowtot rowavg) =+ case layout_ of+ LayoutWide width ->+ [zipWith linkFigure spanclsamts $+ map (cellFromMixedAmount bopts{displayMaxWidth=width}) clsamts]+ LayoutTall -> paddedTranspose Ods.emptyCell+ . map (cellsFromMixedAmount bopts{displayMaxWidth=Nothing})+ $ clsamts+ LayoutBare -> zipWith (:) (map wbCell cs) -- add symbols+ . transpose -- each row becomes a list of Text quantities+ . map (cellsFromMixedAmount (setDisplayCommodityBare cs bopts))+ $ clsamts+ LayoutBareWide -> [concatMap (cellsFromMixedAmount (setDisplayCommodityBare allCommodities bopts))+ $ clsamts]+ LayoutTidy -> concat+ . zipWith (map . addDateColumns) colspans+ . map ( zipWith (\c a -> [wbCell c, a]) cs+ . cellsFromMixedAmount (setDisplayCommodityBare cs bopts))+ $ classified+ -- Do not include totals column or average for tidy output, as this+ -- complicates the data representation and can be easily calculated+ where+ wbCell = Ods.defaultCell . wbFromText+ wbDate content = (wbCell content) {Ods.cellType = Ods.TypeDate}+ cs = if all mixedAmountLooksZero allamts then [""] else S.toList $ foldMap maCommodities allamts+ classified = map ((,) (amountClass rc)) as+ allamts = map snd clsamts+ clsamts = map snd spanclsamts+ -- Each figure with its class, and the span it covers: a column's, the+ -- whole report's for a row total, none for an average. The text+ -- renderer passes no spans.+ spanclsamts =+ (if not summary_only_ then zip (map Just colspans ++ repeat Nothing) classified else []) +++ [(Just (spansSpan colspans) <* guard (not $ null colspans), (rowTotalClass rc, rowtot)) |+ multiBalanceHasTotalsColumn ropts && not (null as)] +++ [(Nothing, (rowAverageClass rc, rowavg)) | average_ && not (null as)]+ -- In the wide layout each figure links to the register it is derived+ -- from, through the row's date span cell for the span it covers. A+ -- figure that looks zero has an empty register, and a figure that is+ -- not a sum of postings has none, so neither links. A totals row's+ -- date span cell carries its own title.+ linkFigure (Just spn, (_, amt)) c+ | figuresLink ropts && not (mixedAmountLooksZero amt) =+ let dsCell = renderDateSpanCell spn in+ withLink (Ods.cellAnchor dsCell)+ (if rc == Total then Ods.cellTitle dsCell+ else amountPhrase (reportLinkOpts ropts colspans) False) c+ linkFigure _ c = c+ addDateColumns spn@(DateSpan s e) remCols =+ (wbFromText <$> renderDateSpanCell spn) :+ wbDate (maybe "" showEFDate s) :+ wbDate (maybe "" (showEFDate . modifyEFDay (addDays (-1))) e) :+ remCols++ paddedTranspose :: a -> [[a]] -> [[a]]+ paddedTranspose _ [] = [[]]+ paddedTranspose n as1 = take (maximum . map length $ as1) . trans $ as1+ where+ trans ([] : xss) = (n : map h xss) : trans ([n] : map t xss)+ trans ((x : xs) : xss) = (x : map h xss) : trans (m xs : map t xss)+ trans [] = []+ h (x:_) = x+ h [] = n+ t (_:xs) = xs+ t [] = [n]+ m (x:xs) = x:xs+ m [] = [n]++-- | Render the Spreadsheet table rows (CSV, ODS, HTML) for a MultiBalanceReport.+-- Returns the heading rows, 0 or more body rows, and the totals row if enabled.+balanceSubReportAsSpreadsheetParts ::+ AmountFormat -> ReportOpts ->+ [CommoditySymbol] -> MultiBalanceReport ->+ ([[Ods.Cell Ods.NumLines Text]],+ [[Ods.Cell Ods.NumLines Text]],+ [[Ods.Cell Ods.NumLines Text]])+balanceSubReportAsSpreadsheetParts fmt opts@ReportOpts{..}+ allCommodities (PeriodicReport colspans items tr) =+ (allHeaders, concatMap fullRowAsTexts items, totalrows)+ where+ accountCell label = (Ods.defaultCell label) {Ods.cellClass = accountClass}+ hCell cls label = (headerCell label) {Ods.cellClass = cls}+ allHeaders =+ case layout_ of+ LayoutBareWide ->+ [headerWithoutBorders $+ Ods.emptyCell :+ concatMap (Ods.horizontalSpan allCommodities) dateHeaders,+ headers]+ _ -> [headers]+ headers =+ addHeaderBorders $+ hCell accountClass "account" :+ case layout_ of+ LayoutTidy -> map headerCell tidyColumnLabels+ LayoutBareWide -> dateHeaders >> map headerCell allCommodities+ LayoutBare -> headerCell "commodity" : dateHeaders+ _ -> dateHeaders+ -- The headings over columns of figures are marked as such, so that a+ -- stylesheet can align them with the figures below (cf amountClass).+ amountHeader c = c{Ods.cellClass = amountClass Value}+ dateHeaders =+ (if not summary_only_ then map (amountHeader . headerDateSpanCell date2_ period_titles_ balance_base_url_ querystring_) colspans else [] )+++ [hCell (rowTotalClass Value) "total" | multiBalanceHasTotalsColumn opts] +++ [hCell (rowAverageClass Value) "average" | average_]+ shownParents = shownParentsOf $ map prrFullName items+ -- An account's link covers the span its row sums: the columns', which+ -- can be wider than the span asked for. When none was asked for, the+ -- register is left unrestricted, as the report is.+ rowquery =+ [t | requestedSpan, t <- dateTerm date2_ $ spansSpan colspans] ++ removeDates querystring_+ where+ requestedSpan = period_ /= PeriodAll || any isDateTerm querystring_+ isDateTerm t = "date:" `T.isPrefixOf` t || "date2:" `T.isPrefixOf` t+ fullRowAsTexts row =+ addRowSpanHeader anchorCell $+ map (map (fmap wbToText)) $+ multiBalanceRowAsCellBuilders fmt opts colspans allCommodities Value+ (dateSpanCellWith lo period_titles_ balance_base_url_ querystring_ acctName) row+ where acctName = prrFullName row+ lo = rowLinkOpts opts colspans shownParents acctName+ anchorCell =+ setAccountAnchorWith lo balance_base_url_ rowquery acctName $+ (\c -> c{Ods.cellClass = treeAccountClass opts (prrIndent row) acctName}) $+ accountCell $ renderPeriodicAcct opts nbsp row+ totalrows =+ if no_total_+ then []+ else multiBalanceTotalsRows fmt opts (reportLinkOpts opts colspans) []+ allCommodities colspans totalRowHeadingSpreadsheet tr++-- | The totals row of a multi-column report, as one or more rows of+-- spreadsheet cells: the label, then a total per column, each linking+-- to the register of everything in the report's query, plus the given+-- terms, for that column.+multiBalanceTotalsRows ::+ AmountFormat -> ReportOpts -> LinkOpts -> [Text] -> [CommoditySymbol] -> [DateSpan] ->+ Text -> PeriodicReportRow a MixedAmount -> [[Ods.Cell Ods.NumLines Text]]+multiBalanceTotalsRows fmt opts@ReportOpts{..} lo extraquery allCommodities colspans label row =+ addTotalBorders $+ addRowSpanHeader ((Ods.defaultCell label) {Ods.cellClass = accountClass}) $+ map (map (fmap wbToText)) $+ multiBalanceRowAsCellBuilders fmt opts colspans allCommodities Total+ (totalDateSpanCell lo period_titles_ balance_base_url_ extraquery querystring_)+ row++tidyColumnLabels :: [Text]+tidyColumnLabels =+ ["period", "start_date", "end_date", "commodity", "value"]++++-- | All commodities appearing in these report rows, sorted.+-- Used as the commodity column order for LayoutBareWide; it must cover+-- every row rendered, see 'setDisplayCommodityBare'.+allCommoditiesFromPeriodicReport ::+ [PeriodicReportRow a MixedAmount] -> [CommoditySymbol]+allCommoditiesFromPeriodicReport =+ S.toAscList . foldMap (foldMap maCommodities . prrAmounts)++-- | Adjust an amount format for bare layouts, which show commodity symbols+-- in their own column(s): hide the symbols and show amounts in the given+-- commodity order.+--+-- Caution: the order list must include every commodity that will be+-- rendered with this format. 'orderedAmounts' renders exactly one amount+-- per listed commodity, so an amount whose commodity is missing from the+-- list is silently dropped (a listed commodity with no amount shows as zero).+-- For LayoutBareWide the list is the whole report's commodities, gathered by+-- 'allCommoditiesFromPeriodicReport' or 'allCommoditiesFromSubreports';+-- for LayoutBare and LayoutTidy it is the row's own commodities.+setDisplayCommodityBare :: [CommoditySymbol] -> AmountFormat -> AmountFormat+setDisplayCommodityBare cs fmt =+ fmt{+ displayCommodity = False,+ displayCommodityOrder = Just cs,+ displayMinWidth = Nothing+ }
+ Hledger/Cli/Commands/Balancesheet.hs view
@@ -0,0 +1,64 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE TemplateHaskell #-}+{-|++The @balancesheet@ command prints a simple balance sheet.++-}++module Hledger.Cli.Commands.Balancesheet (+ balancesheetmode+ ,balancesheet+ ,balancesheetSpec+) where++import System.Console.CmdArgs.Explicit++import Hledger.Utils.I18n (i18n)+import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.CompoundBalanceCommand++balancesheetSpec :: CompoundBalanceCommandSpec+balancesheetSpec = CompoundBalanceCommandSpec {+ cbcdoc = $(embedFileRelative "Hledger/Cli/Commands/Balancesheet.txt"),+ -- TRANSLATORS: the report title, with its reporting interval if any. Each is a+ -- whole phrase, so put the words in the order and form your language needs.+ cbctitle = \case+ NoInterval -> i18n "Balance Sheet"+ Days 1 -> i18n "Daily Balance Sheet"+ Weeks 1 -> i18n "Weekly Balance Sheet"+ Weeks 2 -> i18n "Biweekly Balance Sheet"+ Months 1 -> i18n "Monthly Balance Sheet"+ Months 2 -> i18n "Bimonthly Balance Sheet"+ Months 3 -> i18n "Quarterly Balance Sheet"+ Months 6 -> i18n "Half-yearly Balance Sheet"+ Years 1 -> i18n "Yearly Balance Sheet"+ Years 2 -> i18n "Biennial Balance Sheet"+ _ -> i18n "Periodic Balance Sheet",+ cbcqueries = [+ CBCSubreportSpec{+ cbcsubreporttitle=i18n "Assets"+ ,cbcsubreportquery=Type [Asset]+ ,cbcsubreportoptions=(\ropts -> ropts{normalbalance_=Just NormallyPositive})+ ,cbcsubreporttransform=id+ ,cbcsubreportincreasestotal=True+ }+ ,CBCSubreportSpec{+ cbcsubreporttitle=i18n "Liabilities"+ ,cbcsubreportquery=Type [Liability]+ ,cbcsubreportoptions=(\ropts -> ropts{normalbalance_=Just NormallyNegative})+ ,cbcsubreporttransform=fmap maNegate+ ,cbcsubreportincreasestotal=False+ }+ ],+ cbcaccum = Historical+}++balancesheetmode :: Mode RawOpts+balancesheetmode = compoundBalanceCommandMode balancesheetSpec++balancesheet :: CliOpts -> Journal -> IO ()+balancesheet = compoundBalanceCommand balancesheetSpec
+ Hledger/Cli/Commands/Balancesheet.txt view
@@ -0,0 +1,120 @@+balancesheet++(bs)++Show the end balances in asset and liability accounts. Amounts are shown+with normal positive sign, as in conventional financial statements.++Flags:+ --sum calculation mode: show sum of posting amounts+ (default)+ --valuechange calculation mode: show total change of value+ of period-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ --gain calculation mode: show unrealised capital+ gain/loss (historical balance value minus cost+ basis)+ --count calculation mode: show the count of postings+ --change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports)+ --cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. -b/--begin) to+ column end+ -H --historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date) (default)+ -l --flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth-clipped.+ -t --tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ --drop=N in list mode, omit N leading account name+ parts+ --declared include non-parent declared accounts (best+ used with -E)+ -A --average show a row average column (in multicolumn+ reports)+ -T --row-total show a row total column (in multicolumn+ reports)+ --summary-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ -N --no-total omit the final total row+ --no-elide in tree mode, don't squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without -E)+ --full-names in tree mode, show full account names instead+ of indented leaf names+ --format=FORMATSTR use this custom line format (in simple+ reports)+ -S --sort-amount sort by amount instead of account code/name+ -% --percent express values in percentage of each column's+ total+ --layout=ARG how to show multi-commodity amounts:+ 'wide[,WIDTH]': all commodities on one line+ 'tall' : each commodity on a new line+ 'bare' : bare numbers, symbols in a+ column+ --base-url=URLPREFIX in html output, generate hyperlinks to+ hledger-web, with this prefix. (Usually the base+ url shown by hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ -o --output-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ --view write output to FILE, or to view.FMT in+ hledger's cache directory, and open it in the+ system's default viewer for its format (eg a web+ browser for html). The default format is html.+ --chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: diverging (sections above and below zero;+ the default) or grouped (sections side by side).+ net: also draw the net total (a line, or marks+ in text charts). SCALE: the amount that fills+ the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)++This command displays a balance sheet, showing historical ending+balances of asset and liability accounts. (To see equity as well, use+the balancesheetequity command.)++Accounts declared with the Asset, Cash or Liability type are shown (see+account types). Or if no such accounts are declared, it shows top-level+accounts named asset or liability (case insensitive, plurals allowed)+and their subaccounts.++Example:++$ hledger balancesheet+Balance Sheet 2008-12-31++ || 2008-12-31 +====================++============+ Assets || +--------------------++------------+ assets:bank:saving || $1 + assets:cash || $-2 +--------------------++------------+ || $-1 +====================++============+ Liabilities || +--------------------++------------+ liabilities:debts || $-1 +--------------------++------------+ || $-1 +====================++============+ Net: || 0 ++This command is a higher-level variant of the balance command, and+supports many of that command's features, such as multi-period reports.+It is similar to hledger balance -H assets liabilities, but with smarter+account detection, and liabilities displayed with their sign flipped.++This command also supports the output destination and output format+options The output formats supported are txt, csv, tsv, html, json, and+svg (a chart; see Balance charts).
+ Hledger/Cli/Commands/Balancesheetequity.hs view
@@ -0,0 +1,72 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE TemplateHaskell #-}+{-|++The @balancesheetequity@ command prints a simple balance sheet.++-}++module Hledger.Cli.Commands.Balancesheetequity (+ balancesheetequitymode+ ,balancesheetequity+ ,balancesheetequitySpec+) where++import System.Console.CmdArgs.Explicit++import Hledger.Utils.I18n (i18n)+import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.CompoundBalanceCommand++balancesheetequitySpec :: CompoundBalanceCommandSpec+balancesheetequitySpec = CompoundBalanceCommandSpec {+ cbcdoc = $(embedFileRelative "Hledger/Cli/Commands/Balancesheetequity.txt"),+ -- TRANSLATORS: the report title, with its reporting interval if any. Each is a+ -- whole phrase, so put the words in the order and form your language needs.+ cbctitle = \case+ NoInterval -> i18n "Balance Sheet With Equity"+ Days 1 -> i18n "Daily Balance Sheet With Equity"+ Weeks 1 -> i18n "Weekly Balance Sheet With Equity"+ Weeks 2 -> i18n "Biweekly Balance Sheet With Equity"+ Months 1 -> i18n "Monthly Balance Sheet With Equity"+ Months 2 -> i18n "Bimonthly Balance Sheet With Equity"+ Months 3 -> i18n "Quarterly Balance Sheet With Equity"+ Months 6 -> i18n "Half-yearly Balance Sheet With Equity"+ Years 1 -> i18n "Yearly Balance Sheet With Equity"+ Years 2 -> i18n "Biennial Balance Sheet With Equity"+ _ -> i18n "Periodic Balance Sheet With Equity",+ cbcqueries = [+ CBCSubreportSpec{+ cbcsubreporttitle=i18n "Assets"+ ,cbcsubreportquery=Type [Asset]+ ,cbcsubreportoptions=(\ropts -> ropts{normalbalance_=Just NormallyPositive})+ ,cbcsubreporttransform=id+ ,cbcsubreportincreasestotal=True+ }+ ,CBCSubreportSpec{+ cbcsubreporttitle=i18n "Liabilities"+ ,cbcsubreportquery=Type [Liability]+ ,cbcsubreportoptions=(\ropts -> ropts{normalbalance_=Just NormallyNegative})+ ,cbcsubreporttransform=fmap maNegate+ ,cbcsubreportincreasestotal=False+ }+ ,CBCSubreportSpec{+ cbcsubreporttitle=i18n "Equity"+ ,cbcsubreportquery=Type [Equity]+ ,cbcsubreportoptions=(\ropts -> ropts{normalbalance_=Just NormallyNegative})+ ,cbcsubreporttransform=fmap maNegate+ ,cbcsubreportincreasestotal=False+ }+ ],+ cbcaccum = Historical+}++balancesheetequitymode :: Mode RawOpts+balancesheetequitymode = compoundBalanceCommandMode balancesheetequitySpec++balancesheetequity :: CliOpts -> Journal -> IO ()+balancesheetequity = compoundBalanceCommand balancesheetequitySpec
+ Hledger/Cli/Commands/Balancesheetequity.txt view
@@ -0,0 +1,128 @@+balancesheetequity++(bse)++Show a balance sheet, with historical ending balances of asset,+liability and equity accounts. Amounts are shown with normal positive+sign, as in conventional financial statements.++Flags:+ --sum calculation mode: show sum of posting amounts+ (default)+ --valuechange calculation mode: show total change of value+ of period-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ --gain calculation mode: show unrealised capital+ gain/loss (historical balance value minus cost+ basis)+ --count calculation mode: show the count of postings+ --change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports)+ --cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. -b/--begin) to+ column end+ -H --historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date) (default)+ -l --flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth-clipped.+ -t --tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ --drop=N in list mode, omit N leading account name+ parts+ --declared include non-parent declared accounts (best+ used with -E)+ -A --average show a row average column (in multicolumn+ reports)+ -T --row-total show a row total column (in multicolumn+ reports)+ --summary-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ -N --no-total omit the final total row+ --no-elide in tree mode, don't squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without -E)+ --full-names in tree mode, show full account names instead+ of indented leaf names+ --format=FORMATSTR use this custom line format (in simple+ reports)+ -S --sort-amount sort by amount instead of account code/name+ -% --percent express values in percentage of each column's+ total+ --layout=ARG how to show multi-commodity amounts:+ 'wide[,WIDTH]': all commodities on one line+ 'tall' : each commodity on a new line+ 'bare' : bare numbers, symbols in a+ column+ --base-url=URLPREFIX in html output, generate hyperlinks to+ hledger-web, with this prefix. (Usually the base+ url shown by hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ -o --output-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ --view write output to FILE, or to view.FMT in+ hledger's cache directory, and open it in the+ system's default viewer for its format (eg a web+ browser for html). The default format is html.+ --chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: diverging (sections above and below zero;+ the default) or grouped (sections side by side).+ net: also draw the net total (a line, or marks+ in text charts). SCALE: the amount that fills+ the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)++This report shows accounts declared with the Asset, Cash, Liability or+Equity type (see account types). Or if no such accounts are declared, it+shows top-level accounts named asset, liability or equity (case+insensitive, plurals allowed) and their subaccounts.++Example:++$ hledger balancesheetequity+Balance Sheet With Equity 2008-12-31++ || 2008-12-31 +====================++============+ Assets || +--------------------++------------+ assets:bank:saving || $1 + assets:cash || $-2 +--------------------++------------+ || $-1 +====================++============+ Liabilities || +--------------------++------------+ liabilities:debts || $-1 +--------------------++------------+ || $-1 +====================++============+ Equity || +--------------------++------------+--------------------++------------+ || 0 +====================++============+ Net: || 0 ++This command is a higher-level variant of the balance command, and+supports many of that command's features, such as multi-period reports.+It is similar to hledger balance -H assets liabilities equity, but with+smarter account detection, and liabilities/equity displayed with their+sign flipped.++This report is the easiest way to see if the accounting equation (A+L+E+= 0) is satisfied (after you have done a close --retain to merge+revenues and expenses with equity, and perhaps added --infer-equity to+balance your commodity conversions).++This command also supports the output destination and output format+options The output formats supported are txt, csv, tsv, html, json, and+svg (a chart; see Balance charts).
+ Hledger/Cli/Commands/Cashflow.hs view
@@ -0,0 +1,61 @@+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE TemplateHaskell #-}+{-|++The @cashflow@ command prints a simplified cashflow statement. It just+shows the change in all "cash" accounts for the period (without the+traditional segmentation into operating, investing, and financing+cash flows.)++-}++module Hledger.Cli.Commands.Cashflow (+ cashflowmode+ ,cashflow+ ,cashflowSpec+) where++import System.Console.CmdArgs.Explicit++import Hledger.Utils.I18n (i18n)+import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.CompoundBalanceCommand++cashflowSpec :: CompoundBalanceCommandSpec+cashflowSpec = CompoundBalanceCommandSpec {+ cbcdoc = $(embedFileRelative "Hledger/Cli/Commands/Cashflow.txt"),+ -- TRANSLATORS: the report title, with its reporting interval if any. Each is a+ -- whole phrase, so put the words in the order and form your language needs.+ cbctitle = \case+ NoInterval -> i18n "Cashflow Statement"+ Days 1 -> i18n "Daily Cashflow Statement"+ Weeks 1 -> i18n "Weekly Cashflow Statement"+ Weeks 2 -> i18n "Biweekly Cashflow Statement"+ Months 1 -> i18n "Monthly Cashflow Statement"+ Months 2 -> i18n "Bimonthly Cashflow Statement"+ Months 3 -> i18n "Quarterly Cashflow Statement"+ Months 6 -> i18n "Half-yearly Cashflow Statement"+ Years 1 -> i18n "Yearly Cashflow Statement"+ Years 2 -> i18n "Biennial Cashflow Statement"+ _ -> i18n "Periodic Cashflow Statement",+ cbcqueries = [+ CBCSubreportSpec{+ cbcsubreporttitle=i18n "Cash flows"+ ,cbcsubreportquery=Type [Cash]+ ,cbcsubreportoptions=(\ropts -> ropts{normalbalance_= Just NormallyPositive})+ ,cbcsubreporttransform=id+ ,cbcsubreportincreasestotal=True+ }+ ],+ cbcaccum = PerPeriod+}++cashflowmode :: Mode RawOpts+cashflowmode = compoundBalanceCommandMode cashflowSpec++cashflow :: CliOpts -> Journal -> IO ()+cashflow = compoundBalanceCommand cashflowSpec
+ Hledger/Cli/Commands/Cashflow.txt view
@@ -0,0 +1,120 @@+cashflow++(cf)++Show a (simple) cashflow statement, with the inflows and outflows+affecting "cash" (ie, liquid, easily convertible) assets. Amounts are+shown with normal positive sign, as in conventional financial+statements.++Flags:+ --sum calculation mode: show sum of posting amounts+ (default)+ --valuechange calculation mode: show total change of value+ of period-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ --gain calculation mode: show unrealised capital+ gain/loss (historical balance value minus cost+ basis)+ --count calculation mode: show the count of postings+ --change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports) (default)+ --cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. -b/--begin) to+ column end+ -H --historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date)+ -l --flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth-clipped.+ -t --tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ --drop=N in list mode, omit N leading account name+ parts+ --declared include non-parent declared accounts (best+ used with -E)+ -A --average show a row average column (in multicolumn+ reports)+ -T --row-total show a row total column (in multicolumn+ reports)+ --summary-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ -N --no-total omit the final total row+ --no-elide in tree mode, don't squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without -E)+ --full-names in tree mode, show full account names instead+ of indented leaf names+ --format=FORMATSTR use this custom line format (in simple+ reports)+ -S --sort-amount sort by amount instead of account code/name+ -% --percent express values in percentage of each column's+ total+ --layout=ARG how to show multi-commodity amounts:+ 'wide[,WIDTH]': all commodities on one line+ 'tall' : each commodity on a new line+ 'bare' : bare numbers, symbols in a+ column+ --base-url=URLPREFIX in html output, generate hyperlinks to+ hledger-web, with this prefix. (Usually the base+ url shown by hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ -o --output-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ --view write output to FILE, or to view.FMT in+ hledger's cache directory, and open it in the+ system's default viewer for its format (eg a web+ browser for html). The default format is html.+ --chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: diverging (sections above and below zero;+ the default) or grouped (sections side by side).+ net: also draw the net total (a line, or marks+ in text charts). SCALE: the amount that fills+ the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)++This report shows accounts declared with the Cash type (see account+types). Or if no such accounts are declared, it shows accounts++- under a top-level account named asset (case insensitive, plural+ allowed)+- whose name contains some variation of cash, bank, checking or saving.++More precisely: all accounts matching this case insensitive regular+expression:++^assets?(:.+)?:(cash|bank|che(ck|que?)(ing)?|savings?|currentcash)(:|$)++and their subaccounts.++An example cashflow report:++$ hledger cashflow+Cashflow Statement 2008++ || 2008 +====================++======+ Cash flows || +--------------------++------+ assets:bank:saving || $1 + assets:cash || $-2 +--------------------++------+ || $-1 ++This command is a higher-level variant of the balance command, and+supports many of that command's features, such as multi-period reports.+It is similar to+hledger balance assets not:fixed not:investment not:receivable, but with+smarter account detection.++This command also supports the output destination and output format+options The output formats supported are txt, csv, tsv, html, json, and+svg (a chart; see Balance charts).
+ Hledger/Cli/Commands/Check.hs view
@@ -0,0 +1,144 @@+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Check (+ checkmode+ ,check+) where++import Data.Char (toLower)+import Data.Either (partitionEithers)+import Data.List (isPrefixOf, find, partition, sort)+import Data.Text qualified as T+import Control.Monad (forM_)+import System.Console.CmdArgs.Explicit++import Hledger+import Hledger.Cli.CliOptions++checkmode :: Mode RawOpts+checkmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Check.txt")+ []+ cligeneralflagsgroups1+ hiddenflags+ ([], Just $ flagArg checkArg "[CHECKS]")+ where+ -- Validate each check argument as it is parsed, so an unknown check+ -- name is reported at startup, before the journal is read (and before+ -- any error in it). cmdargs reports the message as+ -- "Unhandled argument, MSG: ARG". The check name is parsed again by 'check'.+ -- An assert rule argument is parsed later, by 'check'.+ checkArg s opts+ | isAssertRule s = Right $ setopt "args" s opts+ | otherwise = case parseCheckArgument s of+ Left _ | map toLower s `elem` ["none","some"] ->+ Left "unknown check name. To check an assert rule, quote it as one argument, eg 'assert none daily type:A balance:<0'"+ Left _ -> Left "unknown check name"+ Right _ -> Right $ setopt "args" s opts++check :: CliOpts -> Journal -> IO ()+check copts@CliOpts{rawopts_, reportspec_} j = do+ let + (rules, args) = partition isAssertRule $ listofstringopt "args" rawopts_+ today = _rsDay reportspec_+ -- reset the report spec that was generated by argsToCliOpts,+ -- since we are not using arguments as a query in the usual way+ copts' = cliOptsUpdateReportSpecWith (\ropts -> ropts{querystring_=[]}) copts++ -- Parse any assert rules first, so their syntax errors are reported before other checks run.+ asserts <- either error' return $ mapM (parseAssertDirective today "check argument" . T.pack) rules++ -- unknown checks were rejected by checkmode already; report them anyway in case+ case partitionEithers (map parseCheckArgument args) of+ (unknowns@(_:_), _) -> error' $ "These checks are unknown: "++unwords unknowns+ ([], checks) -> forM_ (sort checks) $ runCheck copts' j++ -- Then check the assert rules, on the whole journal (all files), even with -I.+ either error' return $ journalCheckAsserts today j{jasserts=asserts}++-- | Is this check argument an assert rule, like an assert directive (assert followed by more words) ?+-- (A plain "assert" is a prefix of, and selects, the assertions check.)+isAssertRule :: String -> Bool+isAssertRule s = case words s of+ "assert":_:_ -> True+ _ -> False+ +-- | Regenerate this CliOpts' report specification, after updating its+-- underlying report options with the given update function.+-- This can raise an error if there is a problem eg due to missing or+-- unparseable options data. See also updateReportSpecFromOpts.+cliOptsUpdateReportSpecWith :: (ReportOpts -> ReportOpts) -> CliOpts -> CliOpts+cliOptsUpdateReportSpecWith roptsupdate copts@CliOpts{reportspec_} =+ case updateReportSpecWith roptsupdate reportspec_ of+ Left e -> error' e -- PARTIAL:+ Right rs -> copts{reportspec_=rs}++-- | A type of error check that we can perform on the data.+-- If performing multiple checks, they will be performed in the order defined here, generally.+-- (We report only the first failure, so the more useful checks should come first.)+data Check =+ -- keep the order here synced with Check.md and Hledger.Data.JournalChecks.journalStrictChecks.+ -- done always+ Parseable+ | Autobalanced+ | Assertions -- unless -I is used; failures are reported after any lot errors (see journalFinalise)+ -- done when --strict is used, or when specified with the check command+ | Balanced+ | Commodities+ | Accounts+ -- done when specified with the check command+ | Lots+ | Ordereddates+ | Payees+ | Tags+ | Recentassertions+ | Uniqueleafnames+ deriving (Read,Show,Eq,Enum,Bounded,Ord)++-- | Parse the name (or a name prefix) of an error check, or return the name unparsed.+-- Check names are conventionally all lower case, but this parses case insensitively.+parseCheck :: String -> Either String Check+parseCheck s = + maybe (Left s) (Right . read) $ -- PARTIAL: read should not fail here+ find (s' `isPrefixOf`) $ checknames+ where+ s' = capitalise $ map toLower s+ checknames = map show [minBound..maxBound::Check]++-- | Parse a check argument: a string which is the lower-case name of an error check,+-- or a prefix thereof, followed by zero or more space-separated arguments for that check.+parseCheckArgument :: String -> Either String (Check,[String])+parseCheckArgument s =+ dbg3 "check argument" $+ case words' s of+ checkname:checkargs -> (,checkargs) <$> parseCheck checkname+ [] -> Left (show s) -- an empty argument++-- XXX do all of these print on stderr ?+-- | Run the named error check, possibly with some arguments,+-- on this journal with these options.+runCheck :: CliOpts -> Journal -> (Check,[String]) -> IO ()+runCheck _opts j (chck,_) = do+ let+ results = case chck of+ -- these checks are assumed to have passed earlier during journal parsing (if enabled):+ Parseable -> Right ()+ Autobalanced -> Right ()+ Balanced -> Right ()+ Assertions -> Right ()+ Accounts -> journalCheckAccounts j+ Commodities -> journalCheckCommodities j+ Lots -> journalCheckLots j+ Ordereddates -> journalCheckOrdereddates j+ Payees -> journalCheckPayees j+ Recentassertions -> journalCheckRecentAssertions j+ Tags -> journalCheckTags j+ Uniqueleafnames -> journalCheckUniqueleafnames j++ case results of+ Right () -> return ()+ Left err -> error' err
+ Hledger/Cli/Commands/Check.txt view
@@ -0,0 +1,141 @@+check++Check that your data is valid, using hledger's built-in correctness+checks.++Flags:+no command-specific flags++hledger provides a number of built-in correctness checks to help+validate your data and prevent errors. Some are run automatically, some+when you enable --strict mode; or you can run any of them on demand by+providing them as arguments to the check command. check produces no+output and a zero exit code if all is well. Eg:++hledger check # run default checks+hledger check -s # run default and strict checks+hledger check ordereddates payees # run default checks and two others+hledger check 'assert none daily type:A balance:<0' # run default checks and a custom rule++If you are an Emacs user, you can also configure flycheck-hledger to run+these checks, providing instant feedback as you edit the journal.++Here are the checks currently available. They are generally checked in+the order they are shown here, and only the first failure will be+reported.++Default checks++These important checks are performed by default, by almost all hledger+commands:++- parseable - data files are in a supported format, with no syntax+ errors and no invalid include directives. This ensures that all files+ exist and are readable.++- autobalanced - all transactions are balanced, after automatically+ inferring missing amounts and conversion rates and then converting+ amounts to cost. This ensures that each transaction's journal entry is+ well formed.++- assertions - all balance assertions and assert directives in the+ journal are passing. Balance assertions are a strong defense against+ errors, catching many problems; assert directives check standing+ rules, like "no asset account is ever negative". This check is on by+ default, but if it gets in your way, you can disable it temporarily+ with -I or --ignore-assertions, or as a default by adding that flag to+ your config file. If you put it in your config file, you can override+ that with -s/--strict or hledger check assertions. When a journal has+ both kinds of problem, lot errors are reported before assertion+ failures, and balance assertion failures before assert directive+ failures.++- lots - all lot entries are valid. Checks lot posting classifications,+ lot movements, that an acquisition writing both a cost basis and a+ transacted cost has them agree (a mismatch would silently miscalculate+ gains), and that any user-written realised gain amount on a disposal+ matches the calculated gain. This check can be disabled by -I or+ --ignore-lots. If you put it in your config file, you can override+ that with -s/--strict or hledger check lots.++Strict checks++When the -s/--strict flag is used (AKA strict mode), all commands will+perform the following additional checks. These provide extra+error-catching power to help you keep your data clean and correct:++- balanced - like autobalanced, but implicit conversions between+ commodities are not allowed; all conversion transactions must use cost+ notation or equity postings. This prevents wrong conversions caused by+ typos.++- commodities - all commodity symbols used must be declared. This guards+ against mistyping or omitting commodity symbols.++- accounts - all account names used must be declared. This prevents the+ use of mis-spelled or outdated account names. (Except lot subaccounts,+ like :{2026-01-15, $50}, which are automatically exempt; only their+ base account needs to be declared. And the accounts of postings+ generated by hledger, such as equity conversion, gain, and imbalance+ postings.)++Also, strict mode ensures that the assertions and lots checks run+(overriding their ignore flags).++Other checks++These are not wanted by everyone, but can be run using the check+command:++- tags - all tags used must be declared (tags on transactions, postings,+ and account and commodity directives; except the special tags). This+ prevents mis-spelled tag names. Note hledger fairly often finds+ unintended tags in comments.++- payees - all payees used in transactions must be declared. This will+ force you to declare any new payee name before using it. Most people+ will probably find this a bit too strict.++- ordereddates - within each file, transactions must be ordered by date.+ (Forecast transactions are not checked.) This is a simple and+ effective error catcher. It's not included in strict mode, but you can+ add it by running hledger check -s ordereddates. If enabled, this+ check is performed before balance assertions.++- recentassertions - all accounts with balance assertions must have one+ that's within the 7 days before their latest posting. This will+ encourage adding balance assertions for your active asset/liability+ accounts, which in turn should encourage you to reconcile regularly+ with those real world balances - another strong defense against+ errors. (hledger close --assert >>$LEDGER_FILE is a convenient way to+ add new balance assertions. Later these become quite redundant, and+ you might choose to remove them to reduce clutter.)++- uniqueleafnames - no two accounts may have the same last account name+ part (eg the checking in assets:bank:checking). This ensures each+ account can be matched by a unique short name, easier to remember and+ to type.++Assert rules++You can also check custom rules, written like assert directives. Give+each one as a single quoted argument, written exactly as the directive+would be written in the journal. Eg:++hledger check 'assert none daily type:A balance:<0'+hledger check 'assert some monthly income:salary' 'assert none assets:oldbank date:2025-'++This is a convenient way to try out a rule before adding it to the+journal, or to check rules you don't want to keep there. Unlike assert+directives, these rules check all of the data files read, combined (not+each file tree separately), and they are checked even with -I. They are+checked after any other checks requested. (A plain assert argument, with+nothing after it, is short for the assertions check.)++Custom checks++You can build your own custom checks with add-on command scripts. See+also Cookbook > Scripting. Here are some examples from hledger/bin/:++- hledger-check-tagfiles - all tag values containing / exist as file+ paths
+ Hledger/Cli/Commands/Close.hs view
@@ -0,0 +1,308 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE MultiWayIf #-}++module Hledger.Cli.Commands.Close (+ closemode+ ,close+)+where++import Data.Function (on)+import Data.List (groupBy)+import Control.Monad (guard)+import Data.List.Extra (nubSort)+import Data.Map qualified as M+import Data.Maybe (catMaybes, fromMaybe, isNothing)+import Data.Text qualified as T+import Data.Time.Calendar (addDays)+import System.Console.CmdArgs.Explicit as C++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils (writeOutputWithTitle)+import Safe (lastDef, readMay, readDef)+import System.FilePath (takeBaseName)+import Data.Char (isDigit)+import Hledger.Read.RulesReader (parseBalanceAssertionType)+import Hledger.Cli.Commands.Print (roundFlag, amountStylesSetRoundingFromRawOpts, layoutFlag, layoutFromRawOpts)++defclosedesc = "closing balances"+defopendesc = "opening balances"+defretaindesc = "retain earnings"++defcloseacct = "equity:opening/closing balances"+defretainacct = "equity:retained earnings"++closemode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Close.txt")+ [flagOpt "" ["clopen"] (\s opts -> Right $ setopt "clopen" s opts) "TAGVAL" "show closing and opening balances transactions, for AL accounts by default"+ ,flagOpt "" ["close"] (\s opts -> Right $ setopt "close" s opts) "TAGVAL" "show just a closing balances transaction"+ ,flagOpt "" ["open"] (\s opts -> Right $ setopt "open" s opts) "TAGVAL" "show just an opening balances transaction"+ ,flagOpt "" ["assert"] (\s opts -> Right $ setopt "assert" s opts) "TAGVAL" "show a balance assertions transaction"+ ,flagOpt "" ["assign"] (\s opts -> Right $ setopt "assign" s opts) "TAGVAL" "show a balance assignments transaction"+ ,flagOpt "" ["retain"] (\s opts -> Right $ setopt "retain" s opts) "TAGVAL" "show a retain earnings transaction, for RX accounts by default"+ ,flagNone ["explicit","x"] (setboolopt "explicit") "show all amounts explicitly"+ ,flagNone ["show-costs"] (setboolopt "show-costs") "show amounts with different costs separately"+ ,flagNone ["interleaved"] (setboolopt "interleaved") "show source and destination postings together"+ ,flagReq ["assertion-type"] (\s opts -> Right $ setopt "assertion-type" s opts) "TYPE" "=, ==, =* or ==*"+ ,flagReq ["close-desc"] (\s opts -> Right $ setopt "close-desc" s opts) "DESC" "set closing transaction's description"+ ,flagReq ["close-acct"] (\s opts -> Right $ setopt "close-acct" s opts) "ACCT" "set closing transaction's destination account"+ ,flagReq ["open-desc"] (\s opts -> Right $ setopt "open-desc" s opts) "DESC" "set opening transaction's description"+ ,flagReq ["open-acct"] (\s opts -> Right $ setopt "open-acct" s opts) "ACCT" "set opening transaction's source account"+ ,roundFlag+ ,layoutFlag+ ]+ cligeneralflagsgroups1+ (hiddenflags+ ++ -- keep supporting old flag names for compatibility+ [flagNone ["closing"] (setboolopt "close") "old spelling of --close"+ ,flagNone ["opening"] (setboolopt "open") "old spelling of --open"+ ,flagNone ["migrate"] (setboolopt "clopen") "old spelling of --clopen"+ ,flagReq ["close-to"] (\s opts -> Right $ setopt "close-acct" s opts) "ACCT" "old spelling of --close-acct"+ ,flagReq ["open-from"] (\s opts -> Right $ setopt "open-acct" s opts) "ACCT" "old spelling of --open-acct"+ ]+ )+ ([], Just $ argsFlag "[--close|--open|--clopen|--assign|--assert|--retain] [ACCTQUERY]")++-- | The close command's mode (subcommand).+-- The code depends on these spellings.+data CloseMode = Clopen | Close | Open | Assign | Assert | Retain deriving (Eq,Show,Read)++-- | Pick the rightmost flag spelled like a CloseMode (--clopen, --close, --open, etc), or default to Close.+closeModeFromRawOpts :: RawOpts -> CloseMode+closeModeFromRawOpts rawopts = lastDef Close $ collectopts (\(name,_) -> readMay (capitalise name)) rawopts++-- Debugger, beware: close is incredibly devious; simple rules combine to make a horrid maze.+-- Tests are in hledger/test/close.test.+close copts@CliOpts{rawopts_=rawopts, reportspec_=rspec0} j = do+ let+ mode_ = closeModeFromRawOpts rawopts+ defacctsq_ = if mode_ == Retain then Type [Revenue, Expense] else Type [Asset, Liability]+ defcloseacct_ = if mode_ == Retain then defretainacct else defcloseacct+ closeacct = T.pack $ fromMaybe defcloseacct_ $ maybestringopt "close-acct" rawopts+ openacct = maybe closeacct T.pack $ maybestringopt "open-acct" rawopts++ -- For easy matching and exclusion, a recognisable tag is added to all generated transactions+ tagval = fromMaybe "" $ maybestringopt modeflag rawopts where modeflag = lowercase $ show mode_+ comment = T.pack $ if+ | mode_ == Assert -> "assert:" <> tagval+ | mode_ == Assign -> "assign:" <> tagval+ | mode_ == Retain -> "retain:" <> tagval+ | otherwise -> "clopen:" <> if null tagval then inferredval else tagval+ where+ inferredval = newfilebasename+ where+ oldfilebasename = takeBaseName $ journalFilePath j+ (nonnum, rest) = break isDigit $ reverse oldfilebasename+ (oldnum, rest2) = span isDigit rest+ newfilebasename = case oldnum of+ [] -> ""+ _ -> reverse rest2 <> newnum <> reverse nonnum+ where+ newnum = show $ 1 + readDef err (reverse oldnum) -- PARTIAL: should not fail+ where err = error' $ "could not read " <> show oldnum <> " as a number in Hledger.Cli.Commands.Close.close"++ ropts = (_rsReportOpts rspec0){balanceaccum_=Historical, accountlistmode_=ALFlat}+ rspec1 = setDefaultConversionOp NoConversionOp rspec0{_rsReportOpts=ropts}++ -- Dates of the closing and opening transactions.+ -- "The default closing date is yesterday, or the journal's end date, whichever is later.+ -- You can change this by specifying a [report end date](#report-start--end-date) with `-e`.+ -- The last day of the report period will be the closing date, eg `-e 2024` means "close on 2023-12-31".+ -- The opening date is always the day after the closing date."+ argsq = _rsQuery rspec1+ yesterday = addDays (-1) $ _rsDay rspec1+ yesterdayorjournalend = case journalLastDay False j of+ Just journalend -> max yesterday journalend+ Nothing -> yesterday+ mreportlastday = addDays (-1) <$> queryEndDate False argsq+ closedate = fromMaybe yesterdayorjournalend mreportlastday+ opendate = addDays 1 closedate++ -- should we show the amount(s) on the equity posting(s) ?+ explicit = boolopt "explicit" rawopts++ -- the accounts to close+ argsacctq = filterQuery (\q -> queryIsAcct q || queryIsType q) argsq+ q2 = if queryIsNull argsacctq then And [argsq, defacctsq_] else argsq+ -- always exclude the balancing equity account+ q3 = And [q2, Not $ Acct $ accountNameToAccountOnlyRegex closeacct]+ -- the balances to close+ rspec3 = rspec1{_rsQuery=q3}+ (acctbals',_) = balanceReport rspec3 j+ showcosts = show_costs_ ropts+ -- Strip costs unless --show-costs is used, and drop any accounts whose+ -- balance thereby becomes zero (unless -E). These are accounts which were+ -- emptied by postings with mismatched costs; without this they would+ -- generate zero postings, and with --lots, duplicate lot ids (#2689).+ -- Lot subaccounts are stripped even with --show-costs: their cost info+ -- lives in the lot name, and transacted prices on their postings would+ -- make the output unparseable (lot transfers may not have one).+ acctbals = [ (withAverageCost a b, b')+ | (a,_,_,b) <- acctbals'+ , let keepcosts = showcosts && not (isLotSubaccount a)+ , let b' = if keepcosts then b else mixedAmountStripCosts b+ , keepcosts || empty_ ropts || not (mixedAmountLooksZero b')+ ]++ -- The lot subaccount names of AVERAGE/AVERAGEALL lots leave out the+ -- cost, which changes as the pool is re-averaged; but the generated+ -- entries must say what cost the lots have, to be re-readable+ -- (especially an opening entry starting a new file). So add the pool's+ -- average cost as of the closing date, which all of its lots share:+ -- eg assets:stocks:{2026-01-15} -> assets:stocks:{2026-01-15, $55}.+ withAverageCost a b = fromMaybe a $ do+ name <- lotSubaccountName a+ cb <- either (const Nothing) Just $ parseLotName (const Nothing) name+ guard $ isNothing (cbCost cb)+ [c] <- Just $ nubSort $ map acommodity $ amounts b+ avg <- M.lookup (lotBaseAccount a, c) avgcosts+ Just $ lotBaseAccount a <> ":" <> showLotName cb{cbCost = Just $ styleAmounts lotstyles avg}+ avgcosts = journalAveragePoolCosts j (Just opendate)+ -- lot names keep their cost's decimal digits+ lotstyles = journalCommodityStylesWith NoRounding j+ totalamt = maSum $ map snd acctbals++ -- since balance assertion amounts are required to be exact, the+ -- amounts in opening/closing transactions should be too (#941, #1137)+ precise = amountSetFullPrecision++ -- does this account have a lot subaccount component (e.g. assets:stocks:{2026-01-15, $50}) ?+ isLotSubaccount a = lotBaseAccount a /= a++ -- interleave equity postings next to the corresponding closing posting, or put them all at the end ?+ interleaved = boolopt "interleaved" rawopts++ -- a balance assertion template of the right type+ assertion =+ case maybestringopt "assertion-type" rawopts >>= parseBalanceAssertionType of+ Nothing -> nullassertion+ Just (total, inclusive) -> nullassertion{batotal=total, bainclusive=inclusive}++ -- the closing (balance-asserting or balance-zeroing) transaction+ mclosetxn+ | mode_ `notElem` [Clopen, Close, Assert, Retain] = Nothing+ | otherwise = Just nulltransaction{+ tdate=closedate, tdescription=closedesc, tcomment=comment, tpostings=closeps+ }+ where+ closedesc = T.pack $ fromMaybe defclosedesc_ $ maybestringopt "close-desc" rawopts+ where+ defclosedesc_+ | mode_ == Retain = defretaindesc+ | mode_ == Assert = "assert balances"+ | otherwise = defclosedesc+ closeps+ -- XXX some duplication+ | mode_ == Assert =+ [ posting{+ paccount = a+ ,pamount = mixedAmount $ precise b{aquantity=0, acost=Nothing}+ -- after each commodity's last posting, assert 0 balance (#1035)+ -- balance assertion amounts are unpriced (#824)+ -- lot subaccounts are skipped: assertions run before lot calculation,+ -- so the subaccount balance would be wrong when re-read+ ,pbalanceassertion =+ if islast && not (isLotSubaccount a)+ then Just assertion{baamount=precise b}+ else Nothing+ }+ | -- get the balances for each commodity and transaction price+ (a,mb) <- acctbals+ , let bs0 = amounts mb+ -- mark the last balance in each commodity with True+ , let bs2 = concat [reverse $ zip (reverse bs1) (True : repeat False)+ | bs1 <- groupBy ((==) `on` acommodity) bs0]+ , (b, islast) <- bs2+ ]++ | otherwise =+ concat [+ posting{paccount = a+ ,pamount = mixedAmount . precise $ negate b+ -- after each commodity's last posting, assert 0 balance (#1035)+ -- balance assertion amounts are unpriced (#824)+ -- lot subaccounts are skipped (see Assert branch above)+ ,pbalanceassertion =+ if islast && not (isLotSubaccount a)+ then Just assertion{baamount=precise b{aquantity=0, acost=Nothing}}+ else Nothing+ }++ -- maybe an interleaved posting transferring this balance to equity+ : [posting{paccount=closeacct, pamount=mixedAmount $ precise b} | interleaved]++ | -- get the balances for each commodity and transaction price+ (a,mb) <- acctbals+ , let bs0 = amounts mb+ -- mark the last balance in each commodity with True+ , let bs2 = concat [reverse $ zip (reverse bs1) (True : repeat False)+ | bs1 <- groupBy ((==) `on` acommodity) bs0]+ , (b, islast) <- bs2+ ]++ -- or a final multicommodity posting transferring all balances to equity+ -- (print will show this as multiple single-commodity postings)+ ++ [posting{paccount=closeacct, pamount=if explicit then mixedAmountSetFullPrecision totalamt else missingmixedamt} | not interleaved]++ -- the opening (balance-assigning or balance-unzeroing) transaction+ mopentxn+ | mode_ `notElem` [Clopen, Open, Assign] = Nothing+ | otherwise = Just nulltransaction{+ tdate=opendate, tdescription=opendesc, tcomment=comment, tpostings=openps+ }+ where+ opendesc = T.pack $ fromMaybe defopendesc $ maybestringopt "open-desc" rawopts+ openps+ | mode_ == Assign =+ [ posting{paccount = a+ ,pamount = missingmixedamt+ ,pbalanceassertion = Just assertion{baamount=b}+ -- case mcommoditysum of+ -- Just s -> Just nullassertion{baamount=precise s}+ -- Nothing -> Nothing+ }++ | (a,mb) <- acctbals+ , let bs0 = amounts mb+ -- mark the last balance in each commodity with the unpriced sum in that commodity (for a balance assertion)+ , let bs2 = concat [reverse $ zip (reverse bs1) (Just commoditysum : repeat Nothing)+ | bs1 <- groupBy ((==) `on` acommodity) bs0+ , let commoditysum = (sum bs1)]+ , (b, _mcommoditysum) <- bs2+ ]+ ++ [posting{paccount=openacct, pamount=if explicit then mixedAmountSetFullPrecision (maNegate totalamt) else missingmixedamt} | not interleaved]++ | otherwise =+ concat [+ posting{paccount = a+ ,pamount = mixedAmount $ precise b+ -- lot subaccounts are skipped: assertions run before lot+ -- calculation, so the subaccount balance would be wrong+ -- when re-read (mirrors the close branch above)+ ,pbalanceassertion =+ case mcommoditysum of+ Just s | not (isLotSubaccount a) ->+ Just assertion{baamount=precise s{acost=Nothing}}+ _ -> Nothing+ }+ : [posting{paccount=openacct, pamount=mixedAmount . precise $ negate b} | interleaved]++ | (a,mb) <- acctbals+ , let bs0 = amounts mb+ -- mark the last balance in each commodity with the unpriced sum in that commodity (for a balance assertion)+ , let bs2 = concat [reverse $ zip (reverse bs1) (Just commoditysum : repeat Nothing)+ | bs1 <- groupBy ((==) `on` acommodity) bs0+ , let commoditysum = (sum bs1)]+ , (b, mcommoditysum) <- bs2+ ]+ ++ [posting{paccount=openacct, pamount=if explicit then mixedAmountSetFullPrecision (maNegate totalamt) else missingmixedamt} | not interleaved]++ -- print them+ -- allow user-specified rounding with --round, like print+ let styles = amountStylesSetRoundingFromRawOpts rawopts $ journalCommodityStyles j+ postinglayout = layoutFromRawOpts rawopts+ showtxn = showTransactionWithLayout postinglayout . styleAmounts styles+ writeOutputWithTitle copts $ foldMap showtxn $ catMaybes [mclosetxn, mopentxn]+
+ Hledger/Cli/Commands/Close.txt view
@@ -0,0 +1,265 @@+close++(equity)++Print several kinds of "closing" and/or "opening" transactions, useful+eg when migrating balances to a new journal file, retaining earnings+into equity, consolidating balances, or viewing lot costs. Like print,+it prints valid journal entries. You can copy these into your journal+file(s) when you are happy with how they look.++Flags:+ --clopen[=TAGVAL] show closing and opening balances transactions,+ for AL accounts by default+ --close[=TAGVAL] show just a closing balances transaction+ --open[=TAGVAL] show just an opening balances transaction+ --assert[=TAGVAL] show a balance assertions transaction+ --assign[=TAGVAL] show a balance assignments transaction+ --retain[=TAGVAL] show a retain earnings transaction, for RX+ accounts by default+ -x --explicit show all amounts explicitly+ --show-costs show amounts with different costs separately+ --interleaved show source and destination postings together+ --assertion-type=TYPE =, ==, =* or ==*+ --close-desc=DESC set closing transaction's description+ --close-acct=ACCT set closing transaction's destination account+ --open-desc=DESC set opening transaction's description+ --open-acct=ACCT set opening transaction's source account+ --round=TYPE how much rounding or padding should be done when+ displaying amounts ?+ none - show original decimal digits,+ as in journal (default)+ soft - just add or remove decimal zeros+ to match precision+ hard - round posting amounts to precision+ (can unbalance transactions)+ all - also round cost amounts to precision+ (can unbalance transactions)+ --layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 - right-align amounts, as in hledger 1+ COL - align decimal marks at column COL+ (default: 53)++close has six modes, selected by choosing one of the mode flags:+--clopen, --close (default), --open, --assert, --assign, or --retain.+They are all doing the same kind of operation, but with different+defaults for different situations.++The journal entries generated by close will have a clopen: tag, which is+helpful when you want to exclude them from reports. If the main journal+file name contains a number, the tag's value will be that base file name+with the number incremented. Eg if the journal file is 2025.journal, the+tag will be clopen:2026. Or you can set the tag value by providing an+argument to the mode flag. Eg --close=foo or --clopen=2025-main.++close --clopen++This is useful if migrating balances to a new journal file at the start+of a new year. It prints a "closing balances" transaction that zeroes+out account balances (Asset and Liability accounts, by default), and an+opposite "opening balances" transaction that restores them again.+Typically, you would run++hledger close --clopen -e NEWYEAR >> $LEDGER_FILE++and then move the opening transaction from the old file to the new file+(and probably also update your LEDGER_FILE environment variable).++Why might you do this ? If your reports are fast, you may not need it.+But at some point you will probably want to partition your data by time,+for performance or data integrity or regulatory reasons. A new file or+set of files per year is common. Then, having each file/fileset+"bookended" with opening and closing balance transactions will allow you+to freely pick and choose which files to read - just the current year,+any past year, any sequence of years, or all of them - while showing+correct account balances in each case. The earliest opening balances+transaction sets correct starting balances, and any later+closing/opening pairs will harmlessly cancel each other out.++The balances will be transferred to and from+equity:opening/closing balances by default. You can override this by+using --close-acct and/or --open-acct.++You can select a different set of accounts to close/open by providing an+account query. Eg to add Equity accounts, provide arguments like+assets liabilities equity or type:ALE. When migrating to a new file,+you'll usually want to bring along the AL or ALE accounts, but not the+RX accounts (Revenue, Expense).++Assertions will be added indicating and checking the new balances of the+closed/opened accounts.++close --close++This prints just the closing balances transaction of --clopen. It is the+default if you don't specify a mode.++More customisation options are described below. Among other things, you+can use close --close to generate a transaction moving the balances from+any set of accounts, to a different account. (If you need to move just a+portion of the balance, see hledger-move.)++close --open++This prints just the opening balances transaction of --clopen. (It is+similar to Ledger's equity command.)++close --assert++This prints a transaction that asserts the account balances as they are+on the end date (and adds an assert: tag). It could be useful as+documention and to guard against changes.++close --assign++This prints a transaction that assigns the account balances as they are+on the end date (and adds an "assign:" tag). Unlike balance assertions,+assignments will post changes to balances as needed to reach the+specified amounts.++This is another way to set starting balances when migrating to a new+file, and it will set them correctly even in the presence of earlier+files which do not have a closing balances transaction. However, it can+hide errors, and disturb the accounting equation, so --clopen is usually+recommended.++close --retain++This is like --close, but it closes Revenue and Expense account balances+by default. They will be transferred to equity:retained earnings, or+another account specified with --close-acct.++Revenues and expenses correspond to changes in equity. They are+categorised separately for reporting purposes, but traditionally at the+end of each accounting period, businesses consolidate them into equity,+This is called "retaining earnings", or "closing the books".++In personal accounting, there's not much reason to do this, and most+people don't. (One reason to do it is to help the balancesheetequity+report show a zero total, demonstrating that the accounting equation+(A-L=E) is satisfied.)++close customisation++In all modes, the following things can be overridden:++- the accounts to be closed/opened, with account query arguments+- the closing/opening dates, with -e OPENDATE+- the balancing account, with --close-acct=ACCT and/or --open-acct=ACCT+- the transaction descriptions, with --close-desc=DESC and+ --open-desc=DESC+- the transactions' clopen tag value, with a TAGVAL argument for the+ mode flag (see above).++By default, the closing date is yesterday, or the journal's end date,+whichever is later; and the opening date is always one day after the+closing date. You can change these by specifying a report end date; the+closing date will be the last day of the report period. Eg -e 2024 means+"close on 2023-12-31, open on 2024-01-01".++With --x/--explicit, the balancing amount will be shown explicitly, and+if it involves multiple commodities, a separate posting will be+generated for each of them (similar to print -x).++With --interleaved, each individual transfer is shown with source and+destination postings next to each other (perhaps useful for+troubleshooting).++With --show-costs, balances' costs are also shown, with different costs+kept separate. This may generate very large journal entries, if you have+many currency conversions or investment transactions. close --show-costs+is currently the best way to view investment lots with hledger. (To move+or dispose of lots, see the more capable hledger-move script.) With+--lots, lot subaccount balances are always shown without costs, even+under --show-costs: their cost information is carried by the lot name+itself, and transacted costs on lot postings would prevent the output+from being read back. For lots using the AVERAGE or AVERAGEALL cost+basis method, whose lot names normally leave out the cost, the pool's+average cost as of the closing date is added to each lot name (eg+{2026-01-15, $55}), so that the output can be read back, eg to start a+new file. A non-terminating average is written with up to 8 decimal+places, so the re-opened lots' total cost basis may differ from the+original by a tiny amount.++close and balance assertions++close adds balance assertions verifying that the accounts have been+reset to zero in a closing transaction or restored to their previous+balances in an opening transaction. These provide useful error checking,+but you can ignore them temporarily with -I, or remove them if you+prefer.++With --lots, balance assertions are not generated for the lot subaccount+postings in closing transactions (assertions on lot postings get+confusing, because they apply to the parent account).++Single-commodity, subaccount-exclusive balance assertions (=) are+generated by default. This can be changed with --assertion-type='==*'+(eg).++When running close you should probably avoid using -C, -R, status:+(filtering by status or realness) or --auto (generating postings), since+the generated balance assertions would then require these.++Transactions with multiple dates (eg posting dates) spanning the file+boundary also can disrupt the balance assertions:++2023-12-30 a purchase made in december, cleared in january+ expenses:food 5+ assets:bank:checking -5 ; date: 2023-01-02++To solve this you can transfer the money to and from a temporary+account, splitting the multi-day transaction into two single-day+transactions:++; in 2022.journal:+2022-12-30 a purchase made in december, cleared in january+ expenses:food 5+ equity:pending -5++; in 2023.journal:+2023-01-02 last year's transaction cleared+ equity:pending 5 = 0+ assets:bank:checking -5++close examples++Retain earnings++Record 2022's revenues/expenses as retained earnings on 2022-12-31,+appending the generated transaction to the journal:++$ hledger close --retain -f 2022.journal -p 2022 >> 2022.journal++After this, to see 2022's revenues and expenses you must exclude the+retain earnings transaction:++$ hledger -f 2022.journal is not:desc:'retain earnings'++Migrate balances to a new file++Close assets/liabilities on 2022-12-31 and re-open them on 2023-01-01:++$ hledger close --clopen -f 2022.journal -p 2022+# copy/paste the closing transaction to the end of 2022.journal+# copy/paste the opening transaction to the start of 2023.journal++After this, to see 2022's end-of-year balances you must exclude the+closing balances transaction:++$ hledger -f 2022.journal bs not:desc:'closing balances'++For more flexibility, it helps to tag closing and opening transactions+with eg clopen:NEWYEAR, then you can ensure correct balances by+excluding all opening/closing transactions except the first, like so:++$ hledger bs -Y -f 2021.j -f 2022.j -f 2023.j expr:'tag:clopen=2021 or not tag:clopen'+$ hledger bs -Y -f 2021.j -f 2022.j expr:'tag:clopen=2021 or not tag:clopen'+$ hledger bs -Y -f 2022.j -f 2023.j expr:'tag:clopen=2022 or not tag:clopen'+$ hledger bs -Y -f 2021.j expr:'tag:clopen=2021 or not tag:clopen'+$ hledger bs -Y -f 2022.j expr:'tag:clopen=2022 or not tag:clopen'+$ hledger bs -Y -f 2023.j # unclosed file, no query needed++More detailed close examples++See examples/multi-year.
+ Hledger/Cli/Commands/Codes.hs view
@@ -0,0 +1,39 @@+{-|++The @codes@ command lists the codes seen in transactions, in the order parsed.++-}++{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Codes (+ codesmode+ ,codes+) where++import Data.Text qualified as T++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils (writeOutputWithTitle)+++-- | Command line options for this command.+codesmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Codes.txt")+ []+ cligeneralflagsgroups1+ hiddenflags+ ([], Just $ argsFlag "[QUERY]")++-- | The codes command.+codes :: CliOpts -> Journal -> IO ()+codes opts@CliOpts{reportspec_=rspec} j = do+ let ts = entriesReport rspec j+ codes' = (if empty_ (_rsReportOpts rspec) then id else filter (not . T.null)) $+ map tcode ts+ writeOutputWithTitle opts $ T.unlines codes'
+ Hledger/Cli/Commands/Codes.txt view
@@ -0,0 +1,46 @@+codes++List the codes seen in transactions, in the order parsed.++Flags:+no command-specific flags++This command prints the value of each transaction's code field, in the+order transactions were parsed. The transaction code is an optional+value written in parentheses between the date and description, often+used to store a cheque number, order number or similar.++Transactions aren't required to have a code, and missing or empty codes+will not be shown by default. With the -E/--empty flag, they will be+printed as blank lines.++You can add a query to select a subset of transactions.++Examples:++2022/1/1 (123) Supermarket + Food $5.00+ Checking ++2022/1/2 (124) Post Office+ Postage $8.32+ Checking++2022/1/3 Supermarket+ Food $11.23+ Checking ++2022/1/4 (126) Post Office+ Postage $3.21+ Checking++$ hledger codes+123+124+126++$ hledger codes -E+123+124++126
+ Hledger/Cli/Commands/Commodities.hs view
@@ -0,0 +1,109 @@+{-|++The @commodities@ command lists commodity/currency symbols.++-}++{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Commodities (+ commoditiesmode+ ,commodities+) where++import Data.Char (isDigit)+import Data.Map qualified as M+import Data.Maybe (fromMaybe)+import Data.Set qualified as S+import Data.Text qualified as Text+import Data.Text qualified as T+import System.Console.CmdArgs.Explicit++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils (writeOutputWithTitle)+import Data.List.Extra (nubSort)+import Data.List ((\\))+++-- | Command line options for this command.+commoditiesmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Commodities.txt")+ [flagNone ["used"] (setboolopt "used") "list commodities used in transactions"+ ,flagNone ["priced"] (setboolopt "priced") "list commodities appearing in P directives"+ ,flagNone ["declared"] (setboolopt "declared") "list commodities declared by commodity directives"+ ,flagNone ["undeclared"] (setboolopt "undeclared") "list commodities used or priced but not declared"+ ,flagNone ["unused"] (setboolopt "unused") "list commodities declared but not used or priced"+ ,flagNone ["find"] (setboolopt "find") "list the first commodity matched by the first argument (a case-insensitive infix regexp)"+ ,flagNone ["directives"] (setboolopt "directives") "show as commodity directives (with their display styles), for use in journals"+ ]+ [generalflagsgroup2]+ confflags+ ([], Just $ argsFlag "[QUERY..]")++commodities :: CliOpts -> Journal -> IO ()+commodities opts@CliOpts{rawopts_=rawopts, reportspec_=ReportSpec{_rsQuery=query}} j = do+ let+ -- The "used" set is commodities appearing in transactions (postings and+ -- their costs). The "priced" set is commodities appearing in P (price)+ -- directives. A date query (or report period) narrows both sets to the+ -- matching transactions/directives. Dateless sources (commodity+ -- directives) are excluded under a date query, which is why --declared+ -- and --unused ignore it. Other query terms (cur:, tag:, ...) filter+ -- the final commodity name list.+ dateq = filterQuery queryIsDate query+ nondateq = filterQuery (not . queryIsDate) query+ hasdateq = not $ queryIsNull dateq+ jmatched = j { jtxns = dbg5With (\xs -> "txnsmatched: " <> show (length xs))+ $ filter (matchesTransaction dateq) (jtxns j)+ , jpricedirectives = dbg5With (\xs -> "pricedirectivesmatched: " <> show (length xs))+ $ filter (matchesPriceDirective dateq) (jpricedirectives j)+ }+ filt = filter (matchesCommodityExtra (journalCommodityTags j) nondateq)+ txusedmatched = dbg5 "txusedmatched" $ S.toList $ journalCommoditiesFromTransactions jmatched+ pricedmatched = dbg5 "pricedmatched" $ S.toList $ journalCommoditiesFromPriceDirectives jmatched+ refdmatched = dbg5 "refdmatched" $ nubSort $ txusedmatched <> pricedmatched+ refdall = dbg5 "refdall" $ S.toList $+ journalCommoditiesFromTransactions j+ <> journalCommoditiesFromPriceDirectives j+ declared' = dbg5 "declared" $ M.keys $ jdeclaredcommodities j+ unused = dbg5 "unused" $ declared' \\ refdall -- whole-journal hygiene; date ignored+ undeclared = dbg5 "undeclared" $ refdmatched \\ declared' -- date narrows the used+priced side+ -- Default: declared ∪ transacted ∪ priced. Under a date query, declarations are dropped (dateless).+ all' = dbg5 "all" $ if hasdateq then refdmatched+ else nubSort $ declared' <> refdall+ -- --find is a name lookup over all known commodity names; date queries don't apply.+ found = dbg5 "found" $ findMatchedByArgument rawopts "commodity" $+ nubSort $ declared' <> refdall++ -- With --directives, show each commodity as a commodity directive declaring its+ -- (declared or inferred) display style, using a sample amount. A decimal mark is+ -- always included, since the directive requires one (eg: commodity 1000. AAPL).+ showc c+ | boolopt "directives" rawopts = "commodity " <> ensureDecimalMark (wbToText $ showAmountB fmt sample)+ | otherwise = c+ where+ style = M.findWithDefault amountstyle c $ journalCommodityStyles j+ sample = nullamt{acommodity=c, aquantity=1000, astyle=style}+ fmt = defaultFmt{displayForceDecimalMark=True}+ mark = fromMaybe '.' $ asdecimalmark style+ -- add a decimal mark after the last digit, if the number has none+ ensureDecimalMark t+ | Text.any (==mark) (if Text.null c then t else Text.replace c "" t) = t+ | otherwise = case Text.findIndex isDigit (Text.reverse t) of+ Just i -> let n = Text.length t - i in Text.take n t <> Text.singleton mark <> Text.drop n t+ Nothing -> t++ -- --priced is specific to commodities, not part of the shared DeclarablesSelector.+ -- Enforce the mutex with the other selectors locally.+ writeOutputWithTitle opts $ T.unlines $ map showc $+ case (boolopt "priced" rawopts, declarablesSelectorFromOpts opts) of+ (True, Nothing) -> filt pricedmatched+ (True, Just _) -> error' "please pick at most one of --used, --priced, --declared, --undeclared, --unused, --find"+ (False, Nothing) -> filt all'+ (False, Just Used) -> filt txusedmatched+ (False, Just Declared) -> filt declared'+ (False, Just Undeclared) -> filt undeclared+ (False, Just Unused) -> filt unused+ (False, Just FindFirst) -> [found]
+ Hledger/Cli/Commands/Commodities.txt view
@@ -0,0 +1,56 @@+commodities++(comm)++List the commodity symbols used or declared in the journal.++Flags:+ --used list commodities used in transactions+ --priced list commodities appearing in P directives+ --declared list commodities declared by commodity directives+ --undeclared list commodities used or priced but not declared+ --unused list commodities declared but not used or priced+ --find list the first commodity matched by the first+ argument (a case-insensitive infix regexp)+ --directives show as commodity directives (with their display+ styles), for use in journals++Most of these flags can be combined. With --directives, it shows valid+commodity directives, declaring each commodity's (declared or inferred)+display style, which could be pasted into a journal file. Some kinds of+query argument are supported: cur:, tag:, and date: (also -b/-e/-p+report period options).++Providing a date query will affect which commodities are reported, as+follows:++ ---------------------------------------------------------------------------+ Flag No date query With a date query+ -------------- ---------------------------- -------------------------------+ (none) declared ∪ transacted ∪ (transacted ∪ priced) in the+ priced period++ --used transacted in the journal transacted in the period++ --priced appearing in any P directive appearing in a P directive in+ the period++ --declared declared with a commodity same+ directive ++ --undeclared (transacted ∪ priced) ∖ (transacted ∪ priced in the+ declared period) ∖ declared++ --unused declared ∖ (transacted ∪ same+ priced) ++ --find the first commodity matching same+ the argument + ---------------------------------------------------------------------------++Example:++$ hledger commodities+$+AAPL+EUR
+ Hledger/Cli/Commands/Descriptions.hs view
@@ -0,0 +1,38 @@+{-|++The @descriptions@ command lists all unique descriptions seen in transactions, sorted alphabetically.++-}++{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Descriptions (+ descriptionsmode+ ,descriptions+) where++import Data.List.Extra (nubSort)+import Data.Text qualified as T++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils (writeOutputWithTitle)+++-- | Command line options for this command.+descriptionsmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Descriptions.txt")+ []+ cligeneralflagsgroups1+ hiddenflags+ ([], Just $ argsFlag "[QUERY]")++-- | The descriptions command.+descriptions :: CliOpts -> Journal -> IO ()+descriptions opts@CliOpts{reportspec_=rspec} j = do+ let ts = entriesReport rspec j+ descs = nubSort $ map tdescription ts+ writeOutputWithTitle opts $ T.unlines descs
+ Hledger/Cli/Commands/Descriptions.txt view
@@ -0,0 +1,19 @@+descriptions++(desc)++List the unique descriptions used in transactions.++Flags:+no command-specific flags++This command lists the unique descriptions that appear in transactions,+in alphabetic order. You can add a query to select a subset of+transactions.++Example:++$ hledger descriptions+Store Name+Gas Station | Petrol+Person A
+ Hledger/Cli/Commands/Diff.hs view
@@ -0,0 +1,116 @@+{-|++The @diff@ command compares two diff.++-}++{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Diff (+ diffmode+ ,diff+) where++import Data.List.Extra ((\\), groupSortOn, nubBy, sortBy)+import Data.Function (on)+import Data.Ord (comparing)+import Data.Maybe (fromJust)+import Data.Time (diffDays)+import Data.Either (partitionEithers)+import Lens.Micro (set)+import Safe (headDef)++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils (writeOutputWithTitle)++-- | Command line options for this command.+diffmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Diff.txt")+ []+ [generalflagsgroup2]+ confflags+ ([], Just $ argsFlag "-f FILE1 -f FILE2 FULLACCOUNTTNAME")++data PostingWithPath = PostingWithPath {+ ppposting :: Posting,+ pptxnidx :: Int,+ pppidx :: Int }+ deriving (Show)++instance Eq PostingWithPath where+ a == b = pptxnidx a == pptxnidx b+ && pppidx a == pppidx b++pptxn :: PostingWithPath -> Transaction+pptxn = fromJust . ptransaction . ppposting++ppamountqty :: PostingWithPath -> Quantity+ppamountqty = aquantity . headDef nullamt . amounts . pamount . ppposting++allPostingsWithPath :: Journal -> [PostingWithPath]+allPostingsWithPath j = do+ (txnidx, txn) <- zip [0..] $ jtxns j+ (pidx, p) <- zip [0..] $ tpostings txn+ return PostingWithPath { ppposting = p, pptxnidx = txnidx, pppidx = pidx }++combine :: ([a], [b]) -> [Either a b]+combine (ls, rs) = map Left ls ++ map Right rs++combinedBinBy :: Ord b => (a -> b) -> ([a], [a]) -> [([a], [a])]+combinedBinBy f = map partitionEithers . groupSortOn (either f f) . combine++greedyMaxMatching :: (Eq a, Eq b) => [(a,b)] -> [(a,b)]+greedyMaxMatching = greedyMaxMatching' []++greedyMaxMatching' :: (Eq a, Eq b) => [Either a b] -> [(a,b)] -> [(a,b)]+greedyMaxMatching' alreadyUsed ((l,r):rest)+ | Left l `elem` alreadyUsed || Right r `elem` alreadyUsed+ = greedyMaxMatching' alreadyUsed rest+ | otherwise = (l,r) : greedyMaxMatching' (Left l : Right r : alreadyUsed) rest+greedyMaxMatching' _ [] = []++dateCloseness :: (PostingWithPath, PostingWithPath) -> Integer+dateCloseness = negate . uncurry (diffDays `on` tdate.pptxn)++type Matching = [(PostingWithPath, PostingWithPath)]++matching :: [PostingWithPath] -> [PostingWithPath] -> Matching+matching ppl ppr = do+ (left, right) <- combinedBinBy ppamountqty (ppl, ppr) -- TODO: probably not a correct choice of bins+ greedyMaxMatching $ sortBy (comparing dateCloseness) [ (l,r) | l <- left, r <- right ]++matchingPostings :: AccountName -> Journal -> [PostingWithPath]+matchingPostings acct j = filter ((== acct) . paccount . ppposting) $ allPostingsWithPath j++pickSide :: Side -> (a,a) -> a+pickSide L (l,_) = l+pickSide R (_,r) = r++unmatchedtxns :: Side -> [PostingWithPath] -> Matching -> [Transaction]+unmatchedtxns s pp m =+ map pptxn $ nubBy ((==) `on` pptxnidx) $ pp \\ map (pickSide s) m++-- | The diff command.+diff :: CliOpts -> Journal -> IO ()+diff opts@CliOpts{file_=[f1, f2], reportspec_=ReportSpec{_rsQuery=Acct acctRe}} _ = do+ j1 <- orDieTrying $ readJournalFile (set ignore_assertions True definputopts) f1+ j2 <- orDieTrying $ readJournalFile (set ignore_assertions True definputopts) f2++ let acct = reString acctRe+ let pp1 = matchingPostings acct j1+ let pp2 = matchingPostings acct j2++ let m = matching pp1 pp2++ let unmatchedtxn1 = unmatchedtxns L pp1 m+ let unmatchedtxn2 = unmatchedtxns R pp2 m++ writeOutputWithTitle opts $+ "These transactions are in the first file only:\n\n"+ <> foldMap showTransaction unmatchedtxn1+ <> "These transactions are in the second file only:\n\n"+ <> foldMap showTransaction unmatchedtxn2++diff _ _ = error' "Please specify two input files. Usage: hledger diff -f FILE1 -f FILE2 FULLACCOUNTNAME"
+ Hledger/Cli/Commands/Diff.txt view
@@ -0,0 +1,34 @@+diff++Compare a particular account's transactions in two input files. It shows+any transactions to this account which are in one file but not in the+other.++Flags:+no command-specific flags++More precisely: for each posting affecting this account in either file,+this command looks for a corresponding posting in the other file which+posts the same amount to the same account (ignoring date, description,+etc).++Since it compares postings, not transactions, this also works when+multiple bank transactions have been combined into a single journal+entry.++This command is useful eg if you have downloaded an account's+transactions from your bank (eg as CSV data): when hledger and your bank+disagree about the account balance, you can compare the bank data with+your journal to find out the cause.++Examples:++$ hledger diff -f $LEDGER_FILE -f bank.csv assets:bank:giro +These transactions are in the first file only:++2014/01/01 Opening Balances+ assets:bank:giro EUR ...+ ...+ equity:opening balances EUR -...++These transactions are in the second file only:
+ Hledger/Cli/Commands/Files.hs view
@@ -0,0 +1,106 @@+{-|++The @files@ command lists the files read: the main and included data files,+and any rules or data files used to read them.++-}++{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Files (+ filesmode+ ,files+) where++import Data.Aeson (ToJSON(..), object, (.=))+import Data.List (mapAccumL, tails)+import Data.Maybe (fromMaybe)+import Data.Text qualified as T+import Safe (headMay)+import System.Console.CmdArgs.Explicit (flagNone)+import System.Directory (doesFileExist)+import System.FilePath (makeRelative, takeDirectory)++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils (unsupportedOutputFormatError, writeOutputLazyText, writeOutputWithTitle)+++-- | Command line options for this command.+filesmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Files.txt")+ [flagNone ["flat","l"] (setboolopt "flat") "list/tree mode: show files as a flat list (default)"+ ,flagNone ["tree","t"] (setboolopt "tree") "list/tree mode: show files as a tree, indenting included files below the file that includes them"+ ,outputFormatFlag ["txt","json"]+ ,outputFileFlag+ ]+ cligeneralflagsgroups2+ hiddenflags+ ([], Just $ argsFlag "[REGEX]")++-- | One entry in the list of files read.+data FileEntry = FileEntry {+ fePath :: FilePath -- ^ the file's path+ ,feShortPath :: FilePath -- ^ its path relative to its parent's directory, if it has a parent+ ,feDepth :: Int -- ^ its depth in the tree of files: 0 for a main file+ ,feParent :: Maybe FilePath -- ^ the file which included it, or which it was used to read+ ,feExists :: Bool -- ^ does it exist ? (Missing included files are recorded, not an error, when finding the files read.)+ }++instance ToJSON FileEntry where+ toJSON e = object+ [ "path" .= fePath e+ , "depth" .= feDepth e+ , "parent" .= feParent e+ , "exists" .= feExists e+ ]++-- | The files command.+files :: CliOpts -> Journal -> IO ()+files opts@CliOpts{rawopts_=rawopts, reportspec_=rspec} j = do+ let args = listofstringopt "args" rawopts+ regex <- mapM (either fail pure . toRegex . T.pack) $ headMay args+ es <- mapM setExists $ fileEntries j+ let+ matches = maybe (const True) regexMatch regex . fePath+ matched = filter matches es+ -- text output shows only existing files, and warns about missing ones+ existing = filter feExists es+ warnMissing = mapM_ (warnIO . ("file not found: " <>) . fePath) $ filter (not . feExists) matched+ case outputFormatFromOpts opts of+ "json" -> writeOutputLazyText opts $ toJsonText matched+ "txt"+ | tree_ $ _rsReportOpts rspec -> do+ warnMissing+ -- show each file whose subtree has a match, keeping the tree visible+ writeLines [ replicate (2 * feDepth e) ' ' ++ feShortPath e+ | e:rest <- tails existing+ , any matches $ e : takeWhile ((> feDepth e) . feDepth) rest+ ]+ | otherwise -> do+ warnMissing+ writeLines $ map fePath $ filter matches existing+ fmt -> exitWithErrorMessage $ unsupportedOutputFormatError fmt+ where+ writeLines = writeOutputWithTitle opts . T.unlines . map T.pack+ setExists e = do+ exists <- if fePath e == "-" then return True else doesFileExist $ fePath e+ return e{feExists=exists}++-- | The journal's files in the order they were read, each followed by any auxiliary files+-- used to read it (eg a CSV file's rules file, or a rules file's included rules files and data file),+-- which appear one level deeper in the tree. (Whether they exist is checked later.)+fileEntries :: Journal -> [FileEntry]+fileEntries j = snd $ mapAccumL entry [] filesanddepths+ where+ filesanddepths = concat+ [ (jfpath jf, jfdepth jf) : [(a, jfdepth jf + 1) | a <- fromMaybe [] $ lookup (jfpath jf) (jauxfiles j)]+ | jf <- jfiles j ]+ -- the accumulator is the chain of parent files' paths, most recent first+ entry parents0 (f, d) = (f : parents, FileEntry f shortpath d mparent True)+ where+ parents = drop (length parents0 - d) parents0+ mparent = headMay parents+ -- For a file included by a literal path, this is the path as written in the include directive.+ shortpath = maybe f (\p -> makeRelative (takeDirectory p) f) mparent
+ Hledger/Cli/Commands/Files.txt view
@@ -0,0 +1,80 @@+files++List all input files used by the journal(s), in the order they were+read. This includes the files used to read CSV data: each CSV file is+followed by its rules file and any rules files that includes, and each+rules file is followed by any rules files it includes and the data file+it read (if any). With a REGEX argument, only file names matching the+regular expression (case sensitive) are shown.++To find the files, hledger reads them only as far as needed, without+processing their data. So this command works even when the journal has+errors, such as unbalanced entries or failing balance assertions (but+not syntax errors), and it does not run source commands. If an included+file does not exist (or an include's glob pattern matches no files), it+is omitted from the list, with a warning; this is not an error. (This+helps tools which generate included files, and need to find them before+they exist.) If a rules file's source pattern matches several files,+only the one it would read is shown.++With -t/--tree, the files are shown as a tree: each included file is+indented below the file that includes it, and shown with its path+relative to that file's directory (for a file included by name, the path+as written in the include directive). The files used to read a CSV or+rules file are shown one level below it, in the same way. A file+included more than once appears at each place it is included. With a+REGEX argument (which is matched against full paths), the files+including a matched file are also shown.++Flags:+ -l --flat list/tree mode: show files as a flat list+ (default)+ -t --tree list/tree mode: show files as a tree, indenting+ included files below the file that includes them+ -O --output-format=FMT select the output format. Supported formats:+ txt, json.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.++With -O json, the files are listed as JSON, for use by other tools. Each+file is an object with these fields: path (the file's path, or - for+standard input), depth (0 for a main file, 1 for a file it includes or+uses, and so on), parent (the path of the file that included or used+this one, or null for a main file), and exists (false for a missing+included file, or an include's glob pattern which matched nothing).+--tree does not affect JSON output, and a REGEX argument selects just+the matching files.++Examples:++$ hledger -f main.journal files+/home/user/finance/main.journal+/home/user/finance/2024.journal++$ hledger -f main.journal files 2024+/home/user/finance/2024.journal++$ hledger -f main.journal files --tree+/home/user/finance/main.journal+ 2024.journal+ 2025.journal+ prices/2025.prices+ checking.rules+ common.rules+ data/checking.csv++$ hledger -f main.journal files -O json checking+[+ {+ "depth": 1,+ "exists": true,+ "parent": "/home/user/finance/main.journal",+ "path": "/home/user/finance/checking.rules"+ },+ {+ "depth": 2,+ "exists": true,+ "parent": "/home/user/finance/checking.rules",+ "path": "/home/user/finance/data/checking.csv"+ }+]
+ Hledger/Cli/Commands/Get.hs view
@@ -0,0 +1,311 @@+{-|++The @get@ command fetches data for the journal:++1. Transactions, by running a @getdata@ helper script in the journal's+ @data/@ directory (creating the directory if missing).+2. Market prices, by running a @getprices@ helper script in the journal's+ @prices/@ directory (creating the directory if missing).++Each phase is skipped (with a notice) when its helper is not present.++-}++{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Get (+ getmode+ ,getcmd+) where++import Control.Exception (IOException, try)+import Control.Monad (unless, when, (>=>))+import Data.List (nub, sortOn)+#if !MIN_VERSION_base(4,20,0)+import Data.List (foldl')+#endif+import Data.Map.Strict qualified as M+import Data.Maybe (catMaybes)+import Data.Set qualified as S+import Data.Text qualified as T+import Data.Text.IO qualified as T+import Data.Time.Calendar (Day)+import System.Console.CmdArgs.Explicit+import System.Directory (createDirectoryIfMissing, doesFileExist)+import System.Exit (ExitCode(..))+import System.FilePath (takeDirectory, (</>))+import System.IO (hPutStr, hPutStrLn, stderr)+import System.Process (cwd, proc, readCreateProcessWithExitCode)++import Hledger+import Hledger.Cli.CliOptions+++-- ====================================================================+-- 1. Command entry point+-- ====================================================================++-- | Command line options for this command.+getmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Get.txt")+ [flagNone ["transactions"] (setboolopt "transactions") "fetch transactions only"+ ,flagNone ["prices"] (setboolopt "prices") "fetch prices only"+ ,flagNone ["dry-run"] (setboolopt "dry-run") "just print the commands that would be run"+ -- The -o/--output flag is disabled for now: it only meaningfully applies+ -- to the prices phase, which is awkward in the combined command.+ -- The supporting code paths below are preserved so this can be re-enabled+ -- easily later.+ -- ,flagReq ["output","o"] (\s opts -> Right $ setopt "output" s opts) "FILE"+ -- "write all prices to FILE (or - for stdout) instead of per-commodity prices/<COMM>.prices files"+ ]+ cligeneralflagsgroups2+ hiddenflags+ ([], Nothing)++-- | The get command. By default runs both phases (data then prices);+-- with -t/--transactions or -p/--prices, runs only the selected phase(s).+getcmd :: CliOpts -> Journal -> IO ()+getcmd opts@CliOpts{rawopts_=rawopts} j = do+ let+ txns = boolopt "transactions" rawopts+ prices = boolopt "prices" rawopts+ noflags = not txns && not prices+ when (txns || noflags) $ fetchData opts j+ when (prices || noflags) $ fetchPrices opts j++-- | Like 'warn' but throws away the trailing-action argument; for the common+-- "log a warning, then continue" pattern.+warn_ :: String -> IO ()+warn_ msg = warn msg (return ())++-- | Show a helper script's command line on stderr (stdout is kept for data).+logCommand :: Bool -> String -> IO ()+logCommand dryRun cmdline = hPutStrLn stderr $ (if dryRun then "would run: " else "running: ") <> cmdline+++-- ====================================================================+-- 2. Data fetching (transactions)+-- ====================================================================++dataScriptName :: FilePath+dataScriptName = "getdata"++-- | Run the data-fetching phase. Ensures the journal's data/ directory exists,+-- then if data/getdata is present, runs it with cwd = data/, forwarding both+-- its stdout and its stderr to our stderr (it saves its data in files, so its+-- output is progress information, and stdout is kept for data). If the helper+-- is missing, logs a skip notice and returns.+fetchData :: CliOpts -> Journal -> IO ()+fetchData CliOpts{rawopts_=rawopts} j = do+ let+ dryRun = boolopt "dry-run" rawopts+ jdir = takeDirectory (journalFilePath j)+ dataDir = jdir </> dataDirName+ script = dataDir </> dataScriptName+ createDirectoryIfMissing True dataDir+ exists <- doesFileExist script+ if not exists+ then hPutStrLn stderr $ "no " <> script <> " script, skipping data fetch"+ else do+ let cmdline = "cd " <> dataDir <> " && " <> dataScriptName+ logCommand dryRun cmdline+ unless dryRun $ do+ eres <- try (readCreateProcessWithExitCode (proc script []){cwd = Just dataDir} "")+ :: IO (Either IOException (ExitCode, String, String))+ case eres of+ Left e ->+ warn_ $ dataScriptName <> " failed: " <> show e+ Right (ec, out, err) -> do+ hPutStr stderr out+ hPutStr stderr err+ case ec of+ ExitFailure n -> warn_ $ dataScriptName <> " exited " <> show n+ ExitSuccess -> return ()+++-- ====================================================================+-- 3. Prices fetching+-- ====================================================================++pricesScriptName :: FilePath+pricesScriptName = "getprices"++pricesDirName :: FilePath+pricesDirName = "prices"++-- | The path of the per-commodity prices file in 'dir' for the given code.+pricesFileFor :: FilePath -> CurrencyCode -> FilePath+pricesFileFor dir code = dir </> pricesDirName </> T.unpack code <> ".prices"++-- | Parse a journal-format text blob and extract its P directives.+parsePrices :: T.Text -> IO (Either String [PriceDirective])+parsePrices txt = do+ hdl <- textToHandle txt+ fmap jpricedirectives <$> runExceptT (readJournal definputopts Nothing hdl)++-- | How the command's stdout will be presented, used only for logging.+-- The actual file write is done by the merge code at the end of the run.+data Redirect+ = ToStdout -- ^ stdout (-o -); shown without any "> ..." suffix+ | ToFile FilePath -- ^ collected into a file; shown as " >FILE"++redirSuffix :: Redirect -> String+redirSuffix ToStdout = ""+redirSuffix (ToFile f) = " >" <> f++-- | Run the prices-fetching phase. Ensures the journal's prices/ directory+-- exists, then if prices/getprices is present, iterates over journal commodities+-- and invokes the helper once per commodity, merging results into+-- prices/<COMM>.prices files. If the helper is missing, logs a skip notice+-- and returns.+fetchPrices :: CliOpts -> Journal -> IO ()+fetchPrices CliOpts{rawopts_=rawopts} j = do+ let+ dryRun = boolopt "dry-run" rawopts+ moutput = case stringopt "output" rawopts of+ "" -> Nothing+ s -> Just s+ jdir = takeDirectory (journalFilePath j)+ pricesDir = jdir </> pricesDirName+ script = pricesDir </> pricesScriptName+ createDirectoryIfMissing True pricesDir+ exists <- doesFileExist script+ if not exists+ then hPutStrLn stderr $ "no " <> script <> " script, skipping prices fetch"+ else do+ today <- getCurrentDay+ let+ base = journalBaseCurrencyCode j+ commspans = commodityDateSpansByCode (journalPostings j)+ codes = nub . filter (/= base) . map toCurrencyCode $ journalCommoditiesUsed j+ runFor = runFetch script base commspans today dryRun+ case moutput of+ Just "-" ->+ mapM_ (\code -> runFor ToStdout code >>= maybe (return ()) T.putStr) codes+ Just outfile -> do+ outs <- mapM (runFor (ToFile outfile)) codes+ let combined = T.concat (catMaybes outs)+ unless (T.null combined) $+ mergeAndWritePrices outfile combined >>= reportOutcome outfile+ Nothing ->+ mapM_ (\code -> do+ let outfile = pricesFileFor jdir code+ mout <- runFor (ToFile outfile) code+ maybe (return ()) (mergeAndWritePrices outfile >=> reportOutcome outfile) mout)+ codes++-- | Fetch prices for one commodity. Logs the command line (see 'logCommand'),+-- runs the script (unless dry-run), and forwards its stderr.+-- Returns 'Nothing' if there are no prices to write — either because the+-- script failed (in which case a warning has been logged to stderr) or+-- because it produced no output. Otherwise returns 'Just' the captured stdout.+runFetch :: FilePath -> CurrencyCode -> M.Map CurrencyCode (Day, Day) -> Day -> Bool+ -> Redirect -> CurrencyCode -> IO (Maybe T.Text)+runFetch script base commspans today dryRun redir code =+ case M.lookup code commspans of+ Nothing -> return Nothing+ Just (start, _end) -> do+ let code' = T.unpack code+ args = [T.unpack base, code', show start, show today]+ cmdline = unwords (pricesScriptName : args) <> redirSuffix redir+ logCommand dryRun cmdline+ if dryRun+ then return Nothing+ else do+ eres <- try (readCreateProcessWithExitCode (proc script args) "")+ :: IO (Either IOException (ExitCode, String, String))+ case eres of+ Left e -> do+ warn_ $ pricesScriptName <> " failed for " <> code' <> ": " <> show e+ return Nothing+ Right (ec, out, err) -> do+ hPutStr stderr err+ case ec of+ ExitFailure n -> do+ warn_ $ pricesScriptName <> " exited " <> show n <> " for " <> code'+ return Nothing+ ExitSuccess ->+ return $ if null out then Nothing else Just (T.pack out)++-- | Key by which we deduplicate two P directives.+priceKey :: PriceDirective -> (Day, CommoditySymbol, CommoditySymbol)+priceKey pd = (pddate pd, pdcommodity pd, acommodity (pdamount pd))++-- | Outcome of attempting to merge new prices into a file.+data MergeOutcome+ = MergedWritten Int Int -- ^ wrote the file: existing kept, new added+ | NothingNew -- ^ no new keys; file untouched+ | NotPureFileRefused -- ^ existing file has non-price content; refused+ | PriceParseError String -- ^ couldn't parse a prices blob++-- | Quick textual safeguard: file contains only P directives and blank lines.+isPurePricesFile :: T.Text -> Bool+isPurePricesFile =+ all (\line -> let l = T.strip line in T.null l || "P" `T.isPrefixOf` l)+ . T.lines++-- | Load existing P directives from a file. Empty list if file is missing.+-- Returns Left if the file exists but contains content other than P+-- directives / blank lines, or if it can't be parsed.+loadExistingPrices :: FilePath -> IO (Either MergeOutcome [PriceDirective])+loadExistingPrices f = do+ exists <- doesFileExist f+ if not exists+ then return (Right [])+ else do+ txt <- T.readFile f+ if not (isPurePricesFile txt)+ then return (Left NotPureFileRefused)+ else either (Left . PriceParseError) Right <$> parsePrices txt++-- | Merge new prices into a destination file (creating if needed).+-- 'newcontent' is the raw text we'd otherwise write — a journal-format+-- blob produced by the helper. Existing prices win on key conflicts;+-- new prices on unseen keys are added. The merged set is written sorted+-- ascending by (date, from, to). If nothing new would be added, the file+-- is left untouched.+mergeAndWritePrices :: FilePath -> T.Text -> IO MergeOutcome+mergeAndWritePrices outfile newcontent = do+ eexisting <- loadExistingPrices outfile+ case eexisting of+ Left outcome -> return outcome+ Right existing -> do+ enew <- parsePrices newcontent+ case enew of+ Left e -> return (PriceParseError ("could not parse new prices: " <> e))+ Right newpds -> do+ let existingKeys = S.fromList (map priceKey existing)+ added = filter ((`S.notMember` existingKeys) . priceKey) newpds+ if null added+ then return NothingNew+ else do+ let merged = sortOn priceKey (existing <> added)+ out = T.unlines (map showPriceDirective merged)+ createDirectoryIfMissing True (takeDirectory outfile)+ T.writeFile outfile out+ return (MergedWritten (length existing) (length added))++-- | Write a one-line summary of a merge outcome to stderr.+reportOutcome :: FilePath -> MergeOutcome -> IO ()+reportOutcome outfile outcome = hPutStrLn stderr $ case outcome of+ MergedWritten ex ad ->+ "wrote " <> outfile <> " (existing " <> show ex <> ", added " <> show ad <> ")"+ NothingNew ->+ outfile <> ": no new prices"+ NotPureFileRefused ->+ "Refusing to overwrite " <> outfile <>+ ": it contains content other than P directives, which would be lost."+ PriceParseError msg ->+ outfile <> ": could not read existing prices: " <> msg++-- | Identify the (earliest, latest) posting date for each commodity used in these postings' main amounts.+commodityDateSpansByCode :: [Posting] -> M.Map CurrencyCode (Day, Day)+commodityDateSpansByCode = foldl' addPosting M.empty+ where+ addPosting m p = foldl' (addCode (postingDate p)) m (codesIn p)+ addCode d m c = M.insertWith merge c (d, d) m+ merge (s1, e1) (s2, e2) = (min s1 s2, max e1 e2)+ codesIn p = map (toCurrencyCode . acommodity) $ amountsRaw (pamount p)
+ Hledger/Cli/Commands/Get.txt view
@@ -0,0 +1,92 @@+get++Fetch new transactions and market prices for the journal, by running+getdata and getprices helper scripts. New prices are merged into prices+files automatically; new transaction data is just saved, for later+conversion & import by import.++Flags:+ --transactions fetch transactions only+ --prices fetch prices only+ --dry-run just print the commands that would be run++By default, this command fetches both transactions and prices.++Phase 1: transactions data++1. Creates a data/ directory next to the main journal file, if it does+ not exist.+2. If the data/getdata helper script exists, runs it in the data+ directory, so it can save downloaded files (CSV/TSV/JSON/OFX/etc.)+ there.++Phase 2: prices++1. Creates a prices/ directory next to the main journal file, if it+ does not exist.+2. If the prices/getprices helper script exists, hledger first guesses+ the journal's base currency (the commodity most used as the target+ in P price directives; or if there are no P directives, the+ commodity most used in postings; or if there are no postings,+ "USD"). Then for each other commodity in the journal, it fetches+ daily market prices in the base currency, from that commodity's+ earliest transaction until today, by running+ getprices BASECUR COMM START END. Each commodity's prices are merged+ into prices/<COMM>.prices, preserving existing prices.++Commands being run, and files being updated, are logged to stderr. With+--dry-run, you can preview the commands without running them.++Merging new prices++Complete historical price data can be hard to get, so the prices phase+is careful to preserve older prices. If prices files already exist, the+newly fetched prices will be merged as follows:++- Prices files will be updated only if they contain nothing but P+ directives (or blank lines).+- New prices for dates already seen are discarded. (So if you want to+ replace old prices, you must delete them before running get.)+- If no new prices remain to be added, the prices file is left as-is.+- Otherwise, the old prices plus the new prices are saved to the file,+ ordered by: date, from commodity, to commodity. Each price keeps the+ number format it was written with.++get's helper scripts++Data downloading varies for everyone, and needs to be easily+customisable, so it is done via helper scripts:++getdata++If you want get to download transaction data for you, make your own+getdata shell script (or executable program), and install it in the data+directory next to your main journal file.++It should download zero or more transaction data files into its current+directory. Anything it prints (on stdout or stderr) is shown on stderr,+as progress output. These are typically bank/brokerage CSV/TSV/SSV+files, but could be anything that your hledger rules files can read. The+hledger repo's getdata is a stub you can start from, with commented+examples.++getprices++If you want get to download historical market prices (useful for+currency conversions, and value or gains reports), install a getprices+script in the prices directory next to your main journal file.++You can start with the hledger repo's getprices, customising it if+needed. This script uses pricehist, so you will need to install that+python tool also (eg with uv tool install pricehist). Some price+providers limit the commodity pairs, history, or number of requests+available for free; you can get better data by paying them and setting+up their API keys as environment variables.++Or, you can make your own getprices script. It should accept 3-4+arguments:++- ISO code for the base currency+- ISO code for the commodity to be priced+- ISO start date+- optional ISO end date (default: today)
+ Hledger/Cli/Commands/Help.hs view
@@ -0,0 +1,124 @@+{-|++The help command.++|-}+--TODO rename manuals+--TODO substring matching++{-# LANGUAGE PackageImports #-}+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Help (++ helpmode+ ,manual++ ) where++import Control.Monad (void)+import Data.Char (toLower)+import Data.List (isInfixOf)+import Data.Maybe+import System.Console.CmdArgs.Explicit+import System.Environment+import System.IO++import Hledger.Cli.CliOptions+import Hledger.Cli.DocFiles+import Hledger.Cli.Utils (openBrowserOn)+import Hledger.Cli.Version (webManualUrl)+import Hledger.Data.RawOptions+import Hledger.Utils (embedFileRelative, runPager, titleLine)+--import Hledger.Utils.Debug++helpmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Help.txt")+ -- The help-* names avoid a clash with the --info and --man flags handled in Cli.hs.+ [flagNone ["i"] (setboolopt "help-i") "use info when showing the manual"+ ,flagNone ["m"] (setboolopt "help-m") "use man when showing the manual"+ ,flagNone ["p"] (setboolopt "help-p") "use less (or $PAGER) when showing the manual"+ ,flagNone ["w"] (setboolopt "help-w") "use a web browser when showing the manual"+ ,flagNone ["l"] (setboolopt "help-l") "just list the manual topics matching TOPIC"+ -- These three limit the commands list to one category of command; with none of them, all are shown.+ ,flagNone ["builtins"] (setboolopt "builtins") "with commands: show only builtin commands"+ ,flagNone ["addons"] (setboolopt "addons") "with commands: show only addon commands"+ ,flagNone ["aliases"] (setboolopt "aliases") "with commands: show only command aliases"+ ]+ [(helpflagstitle, helpflags)]+ hiddenflags -- accept --conf/--no-conf etc., eg so "help commands" can show config aliases+ ([], Just $ argsFlag "[TOPIC]")++-- | Display the hledger manual in various formats, optionally positioned at the given topic.+-- You can select a docs viewer with one of the `--info`, `--man`, `--pager` flags.+-- Otherwise it will use the first available of: info, man, $PAGER, less, stdout+-- (and always stdout if output is non-interactive, the terminal is dumb, or we are+-- in an Emacs buffer that can't render fullscreen viewers, eg shell/comint or eshell).+manual :: CliOpts -> Maybe Topic -> IO ()+manual opts mtopic+ -- With -l, just list the matching topics rather than showing the manual.+ | listonly = case manualTopicsMatching topic of+ [] -> notFound+ ts -> listTopics matchingHeading ts+ | otherwise = case resolveManualTopic topic of+ -- The title isn't a line the viewers can scroll to, so show that manual+ -- from the top for it (rather than searching for the title text, which eg+ -- makes info jump to the first node starting with the program name).+ TopicFound tool h+ | Just h == manualTitle tool -> showManualAt tool Nothing+ | otherwise -> showManualAt tool (Just h)+ -- No match: show a note on stderr and stop, rather than raising an error.+ TopicNotFound -> notFound+ -- Several matches (or none requested, ie the empty topic, which matches+ -- every heading): list them so the user can pick a specific topic. This+ -- is what `hledger help manual` (with no topic) does.+ TopicAmbiguous ts -> listTopics ambiguousHeading ts+ where+ listonly = boolopt "help-l" $ rawopts_ opts+ topic = fromMaybe "" mtopic+ -- Are we listing all the topics (rather than just those matching a TOPIC)?+ listall = null topic+ -- List the given topic names, in the pager if the list is long and one is available.+ -- When listing all topics, indent each by its manual heading level (minus one)+ -- to show the hierarchy; when listing just the matches, indent them all equally.+ listTopics heading nls = runPager $ unlines $ heading : map fmt nls+ where fmt (n, lvl) = replicate (if listall then lvl - 1 else 2) ' ' <> n+ notFound = hPutStrLn stderr $+ "\"" <> topic <> "\" does not match any manual section heading.\n"+ <> "Run `hledger help manual` to list all topics, or `hledger help` for the quick reference."+ ambiguousHeading+ | null topic = titleLine "HLEDGER MANUAL TOPICS"+ | otherwise = "\"" <> topic <> "\" matches several manual sections, try a more specific topic:"+ matchingHeading+ | null topic = titleLine "HLEDGER MANUAL TOPICS"+ | otherwise = "manual topics matching \"" <> topic <> "\":"+ -- Show the given tool's manual, positioned at the given heading if any, in the best viewer.+ showManualAt tool mtopic' = do+ exes <- likelyExecutablesInPath+ pagerprog <- fromMaybe "less" <$> lookupEnv "PAGER"+ interactive <- hIsTerminalDevice stdout+ -- A dumb terminal (eg TERM=dumb, as in emacs shells) can't run info, and+ -- degrades man/less, so fall back to plain text there like the non-interactive case.+ dumbterminal <- ((== "dumb") . map toLower . fromMaybe "") <$> lookupEnv "TERM"+ -- Inside Emacs, only its terminal-emulator modes (term/ansi-term/vterm, whose+ -- INSIDE_EMACS mode contains "term") can render fullscreen viewers like info/man/less;+ -- other modes (shell/comint, eshell) are line-oriented and would garble them, so fall+ -- back to plain text there like the dumb/non-interactive case.+ emacsnonterm <- (\m -> not (null m) && not ("term" `isInfixOf` m)) . fromMaybe "" <$> lookupEnv "INSIDE_EMACS"+ let+ [info, man, pager, cat] =+ [runInfoForTopic, runManForTopic, runPagerForTopic, printHelpForTopic]+ web t mt = void $ openBrowserOn $ webManualUrl t mt+ viewer+ | boolopt "help-w" $ rawopts_ opts = web+ | boolopt "help-i" $ rawopts_ opts = info+ | boolopt "help-m" $ rawopts_ opts = man+ | boolopt "help-p" $ rawopts_ opts = pager+ | not interactive || dumbterminal || emacsnonterm = cat+ | "info" `elem` exes = info+ | "man" `elem` exes = man+ | pagerprog `elem` exes = pager+ | "less" `elem` exes = pager+ | otherwise = cat+ viewer tool mtopic'
+ Hledger/Cli/Commands/Help.txt view
@@ -0,0 +1,57 @@+help++(h) ++Show some part of hledger's documentation.++Flags:+ -i use info when showing the manual+ -m use man when showing the manual+ -p use less (or $PAGER) when showing the manual+ -w use a web browser when showing the manual+ -l just list the manual topics matching TOPIC+ --builtins with commands: show only builtin commands+ --addons with commands: show only addon commands+ --aliases with commands: show only command aliases++The part shown is selected by arguments:++- quickref (or no args): a quick reference / overview+- commands: all commands, including addons and aliases (or just one+ category, with --builtins/--addons/--aliases)+- usage [CMD]: command line options help (like -h/--help)+- examples [CMD]: command line examples+- manual [TOPIC]: view a topic in the manual, or list them all+- TOPIC: (like manual TOPIC)+- home|install|relnotes|docs|support|sponsor: browse hledger.org pages++TOPIC is a section heading in the hledger, hledger-ui or hledger-web+manual, or part of one, matched case insensitively. Enclose it in quotes+if it contains spaces. With no TOPIC (hledger help manual), all manual+topics are listed, indented to show (most of) their hierarchy.++The manual will be shown in a default viewer (info, man, pager, web+browser), or you can choose with -i/-m/-p/-w.++The manual is built in to your hledger executable, so it can be useful+when offline, or when you prefer the terminal to a web browser, or when+the appropriate hledger manual or viewers are not installed properly on+your system.++By default it chooses the best viewer found in $PATH, trying in this+order: info, man, $PAGER, less, more, stdout. (If a TOPIC is specified,+$PAGER and more are not tried.) You can force the use of info, man, or a+pager with the -i, -m, or -p flags. If no viewer can be found, or if+running non-interactively, it just prints the manual to stdout.++Examples:++$ hledger help # show the quick reference+$ hledger help -h # show the help command's options+$ hledger help commands # list all commands+$ hledger help commands --aliases # list just the command aliases+$ hledger help 'time periods' # show the "Time periods" section in the manual+$ hledger help keys # show the "KEYS" section in the hledger-ui manual+$ hledger help -l # list the manual's topics+$ hledger help -l journal # list the manual topics matching "journal"+$ hledger help examples add # show examples for the add command
+ Hledger/Cli/Commands/Holdings.hs view
@@ -0,0 +1,1831 @@+{-|++The @holdings@ command shows a report of investment holdings (lot-tracked assets).++Work in progress; see doc/SPEC-holdings.md.+Currently it shows the Date, Age, Units, Unit/Avg cost, Price, Cost,+Value, Weight, UGain, UGain%, RGain and XIRR columns, one row per+account (or lot subaccount, with --lots) and held commodity. In tree+mode, positions are grouped into account sections: a heading row per+account showing its subtree's totals, its positions beneath it named+by their commodity, and with --lots each position's lots beneath it.++The report computation (holdingsReport) is exported for reuse by other+UIs; the holdings command renders it in the usual output formats.++-}++{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Holdings (+ holdingsmode+ ,holdings+ ,HoldingsReport(..)+ ,HoldingsReportOpts(..)+ ,HoldingsTotals(..)+ ,HoldingsLine(..)+ ,Holding(..)+ ,holdingsReport+ ,holdingsReportAsChart+ ,holdingsReportsAsChart+ ,holdingsPeriodReports+ ,holdingsPeriodsTitle+ ,holdingsUnpricedNote+ ,holdingsClosedHidden+ ,holdingsClosedNote+ ,totalsLeftOut+ ,showage+ ,showPercentWith+) where++import Control.Applicative ((<|>))+import Control.Monad (guard)+import Data.Aeson (Value, object, (.=))+import Data.Decimal (roundTo)+import Data.Default (def)+import Data.List.Extra (find, intercalate, intersperse, minimumBy, nubSort, nubSortOn, sortOn, transpose)+import Data.Map.Strict qualified as M+import Data.Set qualified as S+import Data.Maybe (catMaybes, fromMaybe, isJust, isNothing, maybeToList)+import Data.Ord (Down(..), comparing)+import Data.Text qualified as T+import Data.Text.Lazy qualified as TL+import Data.Time.Calendar (Day, addDays, diffDays)+import System.Console.ANSI (Color(..), ColorIntensity(..))+import System.Console.CmdArgs.Explicit (flagNone, flagReq)+import Safe (headMay)+import Text.Printf (printf)++import Hledger+import Hledger.Cli.Chart (chartFlag, chartRequested, chartWidthFlag, unitAmount, writeChart)+import Hledger.Cli.CliOptions+import Hledger.Cli.CompoundBalanceCommand (titleInterval)+import Hledger.Cli.Commands.Balance.Internal (addTotalBorders)+import Hledger.Cli.Commands.Print (roundFromRawOpts)+import Hledger.Cli.Utils (unsupportedOutputFormatError, warnIfLargeMultiPeriodReport, writeOutputLazyText)+import Hledger.Cli.Xirr (xirr)+import Hledger.Utils.I18n qualified as I18n+import Hledger.Write.Chart (Chart(..), ChartLabel(..), Mark(..), Panel(..), BarLayout(..), Series(..), SeriesRole(..), XAxis(..))+import Hledger.Write.Csv (CSV, printCSV, printTSV)+import Hledger.Write.Html (Html, htmlAsLazyText, titledTableHtml, toHtml)+import Hledger.Write.Ods (printFods)+import Hledger.Write.Spreadsheet (addHeaderBorders, headerCell)+import Hledger.Write.Spreadsheet qualified as Ods+import System.IO qualified as IO+import Text.Blaze.Html5 ((!))+import Text.Blaze.Html5 qualified as H+import Text.Blaze.Html5.Attributes qualified as A+import Text.Tabular.AsciiWide++-- | Command line options for this command.+holdingsmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Holdings.txt")+ (flattreeflags True +++ [flagNone ["no-elide"] (setboolopt "no-elide") "in tree mode, don't squash boring parent accounts; in list mode, also show parent accounts (usually zero, hidden without -E)"+ ,flagNone ["full-names"] (setboolopt "full-names") "in tree mode, show full account names instead of indented leaf names"+ ,flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "omit N leading account name parts; in tree mode, remove the first N levels"+ ,flagNone ["sort-amount","S"] (setboolopt "sort-amount") "sort by value (or with -B, cost) instead of account name, largest first"+ ,flagNone ["no-total","N"] (setboolopt "no-total") "omit the final total row"+ ,flagNone ["change"] (setboolopt "change") "show gains during the report period, or with a report interval, during each period (default with a start date and no interval)"+ ,flagNone ["cumulative"] (setboolopt "cumulative") "with a report interval, show gains from the report start date to each period's end"+ ,flagNone ["historical","H"] (setboolopt "historical") "show gains since acquisition, ignoring the report start date (default with a report interval)"+ ,flagReq ["round"] (\s opts -> Right $ setopt "round" s opts) "TYPE" $+ intercalate "\n"+ ["how much rounding or padding should be done when displaying amounts ?"+ ,"none - show original decimal digits"+ ,"soft - just add or remove decimal zeros"+ ," to match precision"+ ,"hard - round amounts to precision (default)"+ ,"all - also round cost amounts to precision"+ ]+ ,chartFlag+ ,chartWidthFlag+ ,outputFormatFlag ["txt","csv","tsv","html","fods","json","svg"]+ ,outputFileFlag+ ,outputViewFlag])+ cligeneralflagsgroups1+ hiddenflags+ ([], Just $ argsFlag "[QUERY]")++-- | One holding: one commodity held in one displayed account (or lot+-- subaccount), with its report attributes. Each holding is one row of+-- the text/html/fods table and one record of the csv/tsv/json output.+-- A commodity fully disposed from a displayed account also gets a+-- holding, with zero units, so its realised gain stays visible.+data Holding = Holding {+ hAccount :: AccountName+ ,hCommodity :: CommoditySymbol+ ,hDate :: Maybe Day -- ^ acquisition date, when the lots share one+ ,hAge :: Maybe Integer -- ^ days held at the report date+ ,hUnits :: Amount -- ^ units held, styled+ ,hUnitCost :: Maybe Amount -- ^ unit or average cost+ ,hPrice :: [Amount] -- ^ market price(s) at the valuation date (several if the lots' value commodities differ)+ ,hCost :: [Amount] -- ^ total cost basis (multiple amounts if cost commodities are mixed)+ ,hValue :: [Amount] -- ^ market value, when all lots are priced (multiple amounts if value commodities are mixed)+ ,hWeight :: Maybe Quantity -- ^ percentage of the portfolio's value, unrounded+ ,hUgain :: [Amount] -- ^ unrealised gain, when values and costs cover the same commodities+ ,hUgainPct :: Maybe Quantity -- ^ unrealised gain percent, unrounded+ ,hRgain :: [Amount] -- ^ realised gain, from disposals so far+ ,hXirr :: Maybe Double -- ^ annualised internal rate of return percent+ ,hFlows :: [(Day, Amount)] -- ^ its dated cashflows (negative = money invested), which XIRR is calculated from; not displayed+ }++-- Machine-readable fields for the csv/tsv output: full account name, age+-- in days, bare units and rounded gain percent numbers, machine-format+-- amounts (no digit group marks).+holdingCsv :: Holding -> [T.Text]+holdingCsv h =+ [hAccount h+ ,hCommodity h+ ,maybe "" showDate (hDate h)+ ,maybe "" (T.pack . show) (hAge h)+ ,T.pack $ showAmountWith machineFmt{displayCommodity=False} (hUnits h)+ ,maybe "" showamt (hUnitCost h)+ ,showamts (hPrice h)+ ,T.pack $ showMixedAmountWith machineFmt $ mixed $ hCost h+ ,showamts (hValue h)+ ,maybe "" (T.pack . show . roundTo 1) (hWeight h)+ ,showamts (hUgain h)+ ,maybe "" (T.pack . show . roundTo 1) (hUgainPct h)+ ,showamts (hRgain h)+ ,maybe "" (T.pack . printf "%.1f") (hXirr h)+ ]+ where+ showamt = T.pack . showAmountWith machineFmt+ showamts [] = ""+ showamts as = T.pack $ showMixedAmountWith machineFmt $ mixed as++-- | Machine-readable fields for a period's totals, in the csv/tsv output with a report interval: like 'holdingCsv'.+periodTotalsCsv :: Day -> (M.Map CommoditySymbol AmountStyle, HoldingsTotals) -> [T.Text]+periodTotalsCsv d (_, tot) =+ [showDate d+ ,maybe "" (T.pack . showAmountWith machineFmt{displayCommodity=False}) (htUnits tot)+ ,maybe "" showamt (htAvgCost tot)+ ,maybe "" showamt (htPrice tot)+ ,showamts (htCost tot)+ ,maybe "" showamts (htValue tot)+ ,maybe "" showamts (htUgain tot)+ ,maybe "" (T.pack . show . roundTo 1) (htUgainPct tot)+ ,showamts (htRgain tot)+ ,maybe "" (T.pack . printf "%.1f") (htXirr tot)+ ,T.intercalate ", " (htUnpriced tot)+ ]+ where+ showamt a = showamts [a]+ showamts [] = ""+ showamts as = T.pack $ showMixedAmountWith machineFmt $ mixed as++-- | A period's totals, in the json output with a report interval: like 'holdingJson'.+periodTotalsJson :: Day -> (M.Map CommoditySymbol AmountStyle, HoldingsTotals) -> Value+periodTotalsJson d (_, tot) = object+ ["date" .= d+ ,"units" .= (aquantity <$> htUnits tot)+ ,"avgcost" .= (showamts . (:[]) <$> htAvgCost tot)+ ,"unitprice" .= (showamts . (:[]) <$> htPrice tot)+ ,"totalcost" .= showamts (htCost tot)+ ,"totalvalue" .= (showamts <$> htValue tot)+ ,"ugain" .= (showamts <$> htUgain tot)+ ,"ugainpct" .= (roundTo 1 <$> htUgainPct tot)+ ,"rgain" .= mshowamts (htRgain tot)+ ,"xirr" .= htXirr tot+ ,"unpriced" .= htUnpriced tot+ ]+ where+ showamts = T.pack . showMixedAmountWith machineFmt . mixed+ mshowamts as = case as of [] -> Nothing; _ -> Just $ showamts as++holdingJson :: Holding -> Value+holdingJson h = object+ ["account" .= hAccount h+ ,"commodity" .= hCommodity h+ ,"date" .= hDate h+ ,"age" .= hAge h+ ,"units" .= aquantity (hUnits h)+ ,"unitcost" .= (showamt <$> hUnitCost h)+ ,"unitprice" .= mshowamts (hPrice h)+ ,"totalcost" .= showamts (hCost h)+ ,"totalvalue" .= mshowamts (hValue h)+ ,"weight" .= (roundTo 1 <$> hWeight h)+ ,"ugain" .= mshowamts (hUgain h)+ ,"ugainpct" .= (roundTo 1 <$> hUgainPct h)+ ,"rgain" .= mshowamts (hRgain h)+ ,"xirr" .= hXirr h+ ]+ where+ showamt = T.pack . showAmountWith machineFmt+ showamts = T.pack . showMixedAmountWith machineFmt . mixed+ mshowamts as = case as of [] -> Nothing; _ -> Just $ showamts as++-- | Show an age in days compactly: in days, or if a year or more,+-- in years with one decimal digit (approximating years as 365 days):+-- eg 44d, 1.1y.+showage :: Integer -> T.Text+showage d+ | d >= 365 = T.pack (show (roundTo 1 (fromIntegral d / 365))) <> "y"+ | otherwise = T.pack (show d) <> "d"++-- | Show a percentage (eg for the Weight, UGain% and XIRR columns) as a+-- "%" commodity amount, using the given styles' display style for the+-- "%" commodity (eg from a commodity directive or -c, or+-- holdingsReport's default): eg 64.3%.+showPercentWith :: M.Map CommoditySymbol AmountStyle -> Quantity -> T.Text+showPercentWith styles p =+ T.pack $ showAmountWith noCostFmt{displayZeroCommodity=True} $+ styleAmounts styles nullamt{acommodity="%", aquantity=p}++-- | Options for the holdings report, besides the usual ReportSpec.+data HoldingsReportOpts = HoldingsReportOpts {+ hroLots :: Bool -- ^ show each lot (one row per lot subaccount) rather than aggregating them per account, like --lots+ ,hroRounding :: Rounding -- ^ how much rounding or padding to apply to displayed amounts, like --round+ ,hroPriceOracle :: Maybe PriceOracle+ -- ^ the journal's price oracle, if already made (for the report options' --infer-market-prices),+ -- so that several reports can share it and its cache; otherwise the report makes one+ }++-- | The grand totals of a holdings report, summed over its topmost+-- displayed rows (which include everything below them) - except RGain+-- and XIRR, which cover all the lots within the query and end date,+-- including fully disposed lots, commodities and accounts, which have+-- no row unless -E is used; so the totals are the same in list or tree+-- mode, with or without --lots or -E (#2769). Absent components+-- (Nothing or empty) are shown as blank cells.+-- Units, and the average cost per unit, are present only when the+-- holdings are all in one commodity (a multi-commodity total would+-- widen the column for everyone, and a multi-commodity average is+-- not meaningful); the average also needs a single cost commodity.+-- Value and gains are absent unless all holdings have a market price.+data HoldingsTotals = HoldingsTotals {+ htUnits :: Maybe Amount -- ^ total units held, when all in one commodity+ ,htAvgCost :: Maybe Amount -- ^ their average unit cost, when also in one cost commodity+ ,htPrice :: Maybe Amount -- ^ their unit market price, when they are in one commodity with one price (shown with a report interval)+ ,htCost :: [Amount] -- ^ total cost basis, per cost commodity+ ,htValue :: Maybe [Amount] -- ^ total market value, per value commodity, of the holdings whose value is known (see htUnpriced)+ ,htWeight :: Maybe Quantity -- ^ percent of the portfolio's value, unrounded+ ,htUgain :: Maybe [Amount] -- ^ total unrealised gain, when values and costs are comparable (of the holdings whose value is known)+ ,htUgainPct :: Maybe Quantity -- ^ total unrealised gain percent, unrounded (likewise)+ ,htRgain :: [Amount] -- ^ total realised gain, per cost commodity+ ,htXirr :: Maybe Double -- ^ the portfolio's annualised internal rate of return percent (likewise)+ ,htFlows :: [(Day, Amount)] -- ^ the dated cashflows (negative = money invested) which XIRR is calculated from+ -- (of the holdings whose value is known); not displayed+ ,htValuedCost :: [Amount] -- ^ the total cost of the holdings counted in the value; not displayed+ ,htUnpriced :: [CommoditySymbol]+ -- ^ the commodities left out of the value, UGain, UGain%, XIRR and cashflows:+ -- those held with no market price for some lot, so whose value is unknown+ -- (and in period gains, those left out at the start or the end; see holdingsPeriodGains)+ }++-- | One display line of the holdings report.+data HoldingsLine+ -- | An account heading row (tree mode): an account with subaccounts+ -- or several commodities, showing its subtree's totals.+ = HoldingsHeading {+ hlIndent :: Int -- ^ tree indent depth, 0 at top level+ ,hlAccount :: AccountName -- ^ the full account name+ ,hlDisplay :: T.Text -- ^ the name to display: the leaf name, or a squashed chain like b:c+ ,hlTotals :: HoldingsTotals -- ^ the account's subtree totals (see hrAccountTotals)+ }+ -- | A holding's line: a position, lot, or depth-clipped aggregate,+ -- one line per held commodity.+ | HoldingsPosition {+ hlIndent :: Int -- ^ tree indent depth, 0 at top level and in list mode+ ,hlAccount :: AccountName -- ^ the account (or lot subaccount) the line belongs to+ ,hlDisplay :: T.Text -- ^ the name to display: the account name (list mode, or a combined tree row), its commodity (a position under its account's heading), or a lot's name+ ,hlIsLot :: Bool -- ^ is this a lot subaccount's line ?+ ,hlHolding :: Holding+ }++-- | A computed holdings report: the display lines and totals shown by+-- the holdings command, renderable by any UI.+data HoldingsReport = HoldingsReport {+ hrDate :: Day -- ^ the date holdings are shown at: the day before the (exclusive) report end date if specified, otherwise today+ ,hrLines :: [HoldingsLine]+ -- ^ the display lines in display order: flat holdings in list+ -- mode, or account sections in tree mode+ ,hrRows :: [(PeriodicReportRow DisplayName MixedAmount, Holding)]+ -- ^ the holdings as flat records, for machine-readable output:+ -- each holding, paired with its report row (a row holding+ -- several commodities repeats on several lines)+ ,hrTotals :: HoldingsTotals -- ^ the grand totals row's components+ ,hrAccountTotals :: AccountName -> HoldingsTotals+ -- ^ the totals of the lots at or under any one account, computed+ -- like the grand totals row (eg for an account heading row);+ -- Weight is relative to the whole portfolio's value+ ,hrTotalsExcluding :: [CommoditySymbol] -> HoldingsTotals+ -- ^ the grand totals as computed (before any period gains), leaving+ -- these commodities out of the value, gains and cashflows too+ -- (as if unpriced; see htUnpriced)+ ,hrAccountTotalsExcluding :: [CommoditySymbol] -> AccountName -> HoldingsTotals+ -- ^ likewise for an account's totals+ ,hrUnitCostHeading :: T.Text -- ^ what the unit cost column shows: "Unit cost", "Avg cost", or "Unit/Avg cost"+ ,hrStyles :: M.Map CommoditySymbol AmountStyle+ -- ^ the journal's display styles with hroRounding applied, plus a+ -- style for the "%" commodity, for showing the percent columns+ -- (see showPercentWith)+ ,hrGainsPeriod :: Maybe DateSpan+ -- ^ when the report has a start date: the report period, from it to+ -- the report date (inclusive), which the gain columns (UGain, UGain%,+ -- RGain, XIRR) then cover instead of each holding's whole life+ -- (see holdingsPeriodGains)+ ,hrKeepLot :: (AccountName, CommoditySymbol) -> Bool+ -- ^ which lots (lot subaccount, commodity) this report counts: all,+ -- or with change:/balance: terms, those of the lines shown+ }++-- | Chart a holdings report: a bar for each holding (a commodity in an account, or a lot), in each of its commodities' panels+-- (see 'holdingsBarsChart'). Holdings are labelled by account (with --drop applied) and commodity, also in tree mode,+-- since account headings are not drawn. Their values are not marked, since each bar's solid part reaches its value+-- (cost basis and gain, or the part of the cost basis still worth, with the part lost beyond it, hatched).+holdingsReportAsChart :: ReportOpts -> T.Text -> HoldingsReport -> Chart+holdingsReportAsChart ropts title rpt =+ holdingsBarsChart ropts MarkNone (hrStyles rpt) title (XCategories $ map label positions) [holdingBarParts h | (_, _, h) <- positions]+ where+ -- each holding's account, whether it is a lot, and the holding+ positions = [(a, islot, h) | HoldingsPosition{hlAccount = a, hlIsLot = islot, hlHolding = h} <- hrLines rpt]+ -- eg "assets:broker AAPL", or for a lot, "assets:broker AAPL {2024-01-10, $150}"+ label (acct, islot, h) = ChartLabel (name acct) (name $ accountNameDrop (drop_ ropts) acct) 0 Nothing True []+ where+ name a+ | islot = T.unwords [parentAccountName a, hCommodity h, accountLeafName a]+ | otherwise = a <> " " <> hCommodity h++-- | Chart holdings reports at the ends of some periods: a bar for each period, showing all the holdings then,+-- as their total cost basis and their net unrealised gain or loss (see 'holdingsBarsChart').+-- Periods are labelled by their end dates, the holdings' dates.+-- When the reports' gain columns cover each period, or the time since the first period's start+-- (see 'holdingsPeriodReports'), the chart shows those gains instead (see 'holdingsGainsChart'),+-- since the holdings' unrealised gains in this chart are always since acquisition.+-- As in the table, the periods whose values and gains exclude holdings with no market price are starred,+-- and a note says which.+holdingsReportsAsChart :: ReportOpts -> BalanceAccumulation -> T.Text -> [(DateSpan, HoldingsReport)] -> Chart+holdingsReportsAsChart ropts accum title rpts = chart{chNotes = maybeToList note}+ where+ chart = case accum of+ Historical -> holdingsBarsChart ropts MarkLine (maybe M.empty (hrStyles . snd) $ headMay rpts) title xaxis+ [ mconcat $ map (holdingBarParts . snd) $ hrRows r | (_, r) <- rpts ]+ _ -> holdingsGainsChart ropts title xaxis+ [ (fromMaybe [] $ htUgain tot, htRgain tot) | (_, r) <- rpts, let tot = hrTotals r ]+ xaxis = XPeriods [(spn, showDate (hrDate r) <> if null (leftout r) then "" else "*") | (spn, r) <- rpts]+ leftout = totalsLeftOut . hrTotals+ note = case nubSort $ concatMap (leftout . snd) rpts of+ [] -> Nothing+ cs -> Just $ ("* " <>) $+ -- TRANSLATORS: a note below a holdings chart with a report interval, about its starred periods; {commodities} is a list of commodity symbols, like "AAPL, VTI".+ I18n.trf (translations_ ropts) "Values and gains exclude holdings with no market price: {commodities}"+ [("commodities", T.intercalate ", " $ map quoteCommoditySymbolIfNeeded cs)]++-- | A chart of holdings' gains at some x positions (eg period ends), from their unrealised and realised gains there:+-- a bar for each, in each commodity's panel, diverging from zero: gains (revenue colour) above, losses (expense colour) below,+-- the realised ones solid, the unrealised ones hatched, since they are not yet final. The net gain is their total,+-- drawn as a line over time, like other reports' totals.+holdingsGainsChart :: ReportOpts -> T.Text -> XAxis -> [([Amount], [Amount])] -> Chart+holdingsGainsChart ReportOpts{translations_} title xaxis gains =+ Chart{chTitle = title, chXAxis = xaxis, chPanels = map panel $ commoditiesByUse amts, chNotes = []}+ where+ amts = concat [us ++ rs | (us, rs) <- gains]+ tr = I18n.tr translations_+ panel c = Panel+ { pnUnit = unitAmount c amts+ , pnSeries = [ Series (ChartLabel name name 0 typ False []) role mark vals 0 0+ | (name, typ, role, mark, valueof) <- specs+ , let vals = [valueof (quantityOf us) (quantityOf rs) | (us, rs) <- gains]+ , any isJust vals ]+ , pnGroupNames = []+ , pnScale = Nothing+ , pnLayout = Diverging+ , pnCounts = False+ , pnSummary = []+ , pnValueLabels = []+ }+ where+ -- each series: its name, type, role, mark, and value from the unrealised and realised gains, if any+ specs =+ [ (tr "Realised gain", Just Revenue, SeriesItem, MarkBar, \_ r -> r >>= positive)+ , (tr "Unrealised gain", Just Revenue, SeriesProvisional, MarkBar, \u _ -> u >>= positive)+ , (tr "Realised loss", Just Expense, SeriesItem, MarkBar, \_ r -> r >>= negative)+ , (tr "Unrealised loss", Just Expense, SeriesProvisional, MarkBar, \u _ -> u >>= negative)+ , (tr "Net gain", Nothing, SeriesTotal, MarkLine, \u r -> if isJust u || isJust r then Just (fromMaybe 0 u + fromMaybe 0 r) else Nothing)+ ]+ positive q = if q > 0 then Just q else Nothing+ negative q = if q < 0 then Just q else Nothing+ quantityOf as = case [aquantity a | a <- as, acommodity a == c] of+ [] -> Nothing+ qs -> Just $ sum qs++-- | The commodities of these amounts, most used first (then by name): a chart's panels, in order.+commoditiesByUse :: [Amount] -> [CommoditySymbol]+commoditiesByUse amts = map fst $ sortOn (\(c, n) -> (Down n, c)) $ M.toList $ M.fromListWith (+) [(acommodity a, 1 :: Int) | a <- amts]++-- | A holding's amounts, for a bar in a holdings chart: its market value and cost basis, if it has a market price+-- (or if its value is not comparable with its cost basis, its value twice, as having no gain or loss);+-- and its cost basis, if it has no market price.+holdingBarParts :: Holding -> ([Amount], [Amount], [Amount])+holdingBarParts h+ | null (hValue h) = ([], [], hCost h)+ | comparable = (hValue h, hCost h, [])+ | otherwise = (hValue h, hValue h, [])+ where+ -- the value and cost are in the same commodities (as for UGain, which can't be+ -- checked instead, since with a start date it can be blank for another reason)+ comparable = not (null $ hCost h) && commodities (hValue h) == commodities (hCost h)+ commodities = nubSort . map acommodity++-- | A chart of holdings: a bar at each x position, in each commodity's panel, from the market value, cost basis+-- and cost basis without a market price, of one or more holdings there (see 'holdingBarParts').+-- Holdings with a market price are drawn as their cost basis and their unrealised gain, stacked, reaching their value;+-- or with an unrealised loss, as the part of their cost basis they are worth, and the part lost (hatched), reaching their cost basis.+-- Holdings without a market price are drawn as their cost basis, beyond those, in a muted colour.+-- The market values are the chart's total, drawn with the given mark: none for separate holdings, whose bars' solid parts+-- reach their values (shown as text), or a line over time, like other reports' totals. Graphical charts show the unrealised gain percents+-- instead (with these styles, for the % commodity), where there is a market price, since the axis shows the values.+holdingsBarsChart :: ReportOpts -> Mark -> M.Map CommoditySymbol AmountStyle -> T.Text -> XAxis -> [([Amount], [Amount], [Amount])] -> Chart+holdingsBarsChart ReportOpts{translations_} totalmark styles title xaxis parts =+ Chart{chTitle = title, chXAxis = xaxis, chPanels = map panel $ commoditiesByUse amts, chNotes = []}+ where+ amts = concat [vs ++ ks ++ us | (vs, ks, us) <- parts]+ tr = I18n.tr translations_+ panel c = Panel+ { pnUnit = unitAmount c amts+ , pnSeries = [ Series (ChartLabel name name 0 typ False []) role mark vals 0 0+ | ((name, typ, role, mark), vals) <- zip specs $ transpose [barValues vs ks us | (vs, ks, us) <- parts]+ , any isJust vals || role == SeriesTotal ] -- the values, even if none, so that a cost is not shown as one+ , pnGroupNames = []+ , pnScale = Nothing+ , pnLayout = Diverging+ , pnCounts = False+ , pnSummary = []+ , pnValueLabels = [gainPercent (quantityOf vs) (quantityOf ks) | (vs, ks, _) <- parts]+ }+ where+ -- eg +12.5%, -3.0%+ gainPercent mv mk = case (mv, mk) of+ (Just v, Just k) | k /= 0 -> let p = (v - k) / abs k * 100 in Just $ (if p > 0 then "+" else "") <> showPercentWith styles p+ _ -> Nothing+ specs =+ [ (tr "Cost", Just Asset, SeriesItem, MarkBar)+ , (tr "Unrealised gain", Just Revenue, SeriesItem, MarkBar)+ , (tr "Unrealised loss", Just Expense, SeriesShortfall, MarkBar)+ , (tr "No market price", Nothing, SeriesOther, MarkBar)+ , (tr "Value", Nothing, SeriesTotal, totalmark)+ ]+ -- A bar's values for those series, in this commodity: the value and cost basis, the smaller of them+ -- stacked with the difference, a gain or loss; then the cost basis without a market price.+ -- (Values and costs are of one sign, negative for a short position, whose gain is a smaller value.)+ barValues vs ks us = case (quantityOf vs, quantityOf ks) of+ (Just v, Just k) ->+ let (base, end) = if abs v <= abs k then (v, k) else (k, v)+ ugain = v - k+ in [Just base, nonzero (ugain > 0) (end - base), nonzero (ugain < 0) (end - base), quantityOf us, Just v]+ _ -> [Nothing, Nothing, Nothing, quantityOf us, Nothing]+ quantityOf as = case [aquantity a | a <- as, acommodity a == c] of+ [] -> Nothing+ qs -> Just $ sum qs+ nonzero ok q = if ok && q /= 0 then Just q else Nothing++-- | Compute the holdings report: the assets held in lot-tracked accounts+-- as of the report end date, one line per account (or per lot, with+-- hroLots) and held commodity, plus grand totals. In tree mode the+-- display lines are instead account sections (see holdingsTreeLines),+-- while the flat records (hrRows) keep the list-mode shape.+--+-- The journal must have its lot detail (lot subaccounts and synthetic+-- postings) uncollapsed, as the holdings command receives it+-- (see maybePrepareLotDetail); this report aggregates lots itself.+-- A --value=then valuation strategy is not supported; callers reject it.+holdingsReport :: HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport+holdingsReport hro0 rspec@ReportSpec{_rsReportOpts=ropts'} j'+ | accountlistmode_ ropts' == ALTree = treeHoldingsReport hro rspec j'+ | otherwise = flatHoldingsReport hro rspec j'+ where+ -- one price oracle for all the flat reports this needs (making one, and+ -- filling its cache, is costly with many prices)+ hro = hro0{hroPriceOracle = hroPriceOracle hro0 <|> Just (journalPriceOracle (infer_prices_ ropts') j')}++-- | -S's sort key for a holding, or an account's holdings, with this+-- market value (empty if unpriced) and cost: priced things first, largest+-- value first, then unpriced things, largest cost first; or at cost+-- (-B), everything by cost. Amounts of different commodities are+-- compared, and summed, by their quantities alone.+holdingsSortKey :: Bool -> [Amount] -> [Amount] -> (Bool, Down Quantity)+holdingsSortKey atcost val cost+ | atcost = (False, Down $ sumq cost)+ | null val = (True, Down $ sumq cost)+ | otherwise = (False, Down $ sumq val)+ where sumq = sum . map aquantity++-- | The tree-mode holdings report: the flat report, with its display+-- lines grouped into account sections. With hroLots, a second flat+-- report gives each position's lots, shown beneath it, and provides+-- the flat records and unit cost heading, as list mode would.+treeHoldingsReport :: HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport+treeHoldingsReport hro rspec@ReportSpec{_rsReportOpts=ropts'} j' =+ prpt{ hrLines = holdingsTreeLines ropts' prpt mlrpt+ , hrRows = hrRows mrpt+ , hrUnitCostHeading = hrUnitCostHeading mrpt+ }+ where+ flatrspec = rspec{_rsReportOpts = ropts'{accountlistmode_ = ALFlat}}+ prpt = flatHoldingsReport hro{hroLots = False} flatrspec j'+ mlrpt | hroLots hro = Just $ flatHoldingsReport hro{hroLots = True} flatrspec j'+ | otherwise = Nothing+ mrpt = fromMaybe prpt mlrpt++-- | Group a flat holdings report's lines into account sections, as tree+-- mode displays them: an account with subaccounts or several+-- commodities is a heading line showing its subtree's totals, with its+-- own positions beneath it named by their commodity, then its+-- subaccounts; an account holding one commodity with no subaccounts is+-- a single combined line carrying its figures. Boring parents - those+-- with no positions of their own and a single child - are squashed into+-- their child like the balance reports' tree mode, unless no-elide is+-- set; only accounts with holdings exist here, so the squashing+-- considers holding rows alone (#2779). With a lots report given, each+-- position's lots are beneath it. Sibling accounts, the top level+-- included, are in account name order, or with -S, sorted by their+-- subtree's totals, as on their headings (see holdingsSortKey); an+-- account's positions, and their lots, keep the flat report's order.+-- --drop removes the first N levels: the tree's roots are the accounts+-- at level N+1 (a shallower account's own positions, a rare case, show+-- as top-level rows).+holdingsTreeLines :: ReportOpts -> HoldingsReport -> Maybe HoldingsReport -> [HoldingsLine]+holdingsTreeLines ropts prpt mlrpt =+ concatMap node $ sortOn (acctOrder . fst) $+ [(a, False) | a <- allaccts, accountNameLevel a == dropn + 1] +++ [(a, True) | dropn > 0, a <- M.keys posByAcct, accountNameLevel a <= dropn]+ where+ dropn = drop_ ropts+ noelide = no_elide_ ropts+ -- sibling accounts' order: with -S, by their subtree's totals; then+ -- by their first row in the flat report (without -S, account name order)+ acctOrder a = (subtreeSortKey, M.lookup a subtreeIxMap)+ where+ subtreeSortKey+ | sort_amount_ ropts = Just $ holdingsSortKey (conversionop_ ropts == Just ToCost) (fromMaybe [] $ htValue t) (htCost t)+ | otherwise = Nothing+ where t = hrAccountTotals prpt a+ node (a, False) = treeNode 0 a+ node (a, True) =+ concat [ HoldingsPosition 0 a (accountNameDrop dropn a) False h : lotLines 1 a h+ | h <- M.findWithDefault [] a posByAcct ]+ posByAcct = M.fromListWith (flip (++)) [(hAccount h, [h]) | (_, h) <- hrRows prpt]+ lotsByPos = case mlrpt of+ Nothing -> M.empty+ Just lr -> M.fromListWith (flip (++))+ [ ((lotBaseAccount a, hCommodity h), [h])+ | (_, h) <- hrRows lr, let a = hAccount h, isJust (lotSubaccountName a) ]+ -- each account's subtree's first flat row, ordering subtrees as the+ -- flat report's sort ordered their rows+ subtreeIxMap = M.fromListWith min+ [(a, ix) | (ix, (_, h)) <- zip [0 :: Int ..] (hrRows prpt), a <- expandAccountName (hAccount h)]+ allaccts = M.keys subtreeIxMap+ kidsMap = M.map (sortOn acctOrder) $ M.fromListWith (++)+ [(parentAccountName a, [a]) | a <- allaccts, accountNameLevel a > 1]+ kidsOf a = M.findWithDefault [] a kidsMap+ -- squash boring parents into their child+ elide disp acct+ | not noelide, M.notMember acct posByAcct, [c] <- kidsOf acct =+ elide (disp <> ":" <> accountLeafName c) c+ | otherwise = (disp, acct)+ treeNode d acct0 = case (M.findWithDefault [] acct posByAcct, kidsOf acct) of+ ([h], []) -> HoldingsPosition d acct disp False h : lotLines (d+1) acct h+ (own, kids) ->+ HoldingsHeading d acct disp (hrAccountTotals prpt acct) :+ concat [ HoldingsPosition (d+1) acct (hCommodity h) False h : lotLines (d+2) acct h+ | h <- own ] +++ concatMap (treeNode (d+1)) kids+ where (disp, acct) = elide (accountLeafName acct0) acct0+ lotLines d acct h =+ [ HoldingsPosition d (hAccount lh) (fromMaybe (hAccount lh) $ lotSubaccountName $ hAccount lh) True lh+ | lh <- M.findWithDefault [] (acct, hCommodity h) lotsByPos ]++-- | The flat (list-mode) holdings report; also the building block of+-- the tree-mode report. When the query has a start date, the gain+-- columns cover the report period (see holdingsPeriodGains); this needs+-- a second report, of the same lots as of the day before the start date.+flatHoldingsReport :: HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport+flatHoldingsReport hro rspec@ReportSpec{_rsQuery=q, _rsReportOpts=ropts} j =+ case queryStartDate False q of+ Nothing -> endrpt+ Just start -> holdingsPeriodGains start startrpt endrpt+ where+ startrpt = flatHoldingsReportAt (Just $ hrKeepLot endrpt) hro startrspec j+ -- empty_, so that holdings sold off before the start date are seen too+ startrspec = rspec{ _rsQuery = And [filterQuery (not . queryIsDateOrDate2) q, Date $ DateSpan Nothing (Just $ Exact start)]+ , _rsRowQuery = Any+ , _rsReportOpts = ropts{empty_ = True} }+ where+ endrpt = flatHoldingsReportAt Nothing hro rspec j++-- | Make a holdings report's gain columns cover the period since this+-- start date, given the report of the same lots as of the day before it:+--+-- - UGain is the change in unrealised gain during the period+--+-- - UGain% is that as a percentage of the value at the start plus the+-- net cost added since (so with nothing held at the start, it is the+-- usual gain relative to cost)+--+-- - XIRR is the annualised rate of return over the period, counting the+-- value at the start as money invested then.+--+-- (RGain and the cashflows are already limited to the period, by+-- flatHoldingsReportAt.) These are left blank when a value needed is not+-- known (no market price) or the amounts are in several commodities.+holdingsPeriodGains :: Day -> HoldingsReport -> HoldingsReport -> HoldingsReport+holdingsPeriodGains start startrpt rpt = rpt+ { hrLines = map periodLine $ hrLines rpt+ , hrRows = [(r, periodHolding h) | (r, h) <- hrRows rpt]+ , hrTotals = periodTotals (hrTotalsExcluding startrpt) (hrTotalsExcluding rpt)+ , hrAccountTotals = accountPeriodTotals+ , hrGainsPeriod = Just $ DateSpan (Just $ Exact start) (Just $ Exact $ addDays 1 $ hrDate rpt)+ }+ where+ periodLine l@HoldingsHeading{} = l{hlTotals = accountPeriodTotals $ hlAccount l}+ periodLine l@HoldingsPosition{} = l{hlHolding = periodHolding $ hlHolding l}++ startholdings = M.fromList [((hAccount h, hCommodity h), h) | (_, h) <- hrRows startrpt]++ periodHolding h = h{hUgain = fromMaybe [] mugain, hUgainPct = mpct, hXirr = mxirr}+ where+ (mugain, mpct, mxirr) = periodFigures mstartvalue mstartugain (maybe [] hCost mstarth) mendvalue mendugain (hCost h) (hFlows h)+ mstarth = M.lookup (hAccount h, hCommodity h) startholdings+ (mstartvalue, mstartugain) = maybe (Just [], Just []) valueAndUgain mstarth+ (mendvalue, mendugain) = valueAndUgain h+ -- a holding's value and unrealised gain, if known; nothing held is worth nothing+ valueAndUgain h'+ | amountLooksZero (hUnits h') = (Just [], Just [])+ | otherwise = (nonEmpty $ hValue h', nonEmpty $ hUgain h')+ nonEmpty as = if null as then Nothing else Just as++ -- Period totals from the start and end totals leaving out some+ -- commodities. Both leave out the same ones, those whose value is+ -- unknown at the start or the end, so the period's figures compare+ -- the same holdings.+ periodTotals stx tx = t{htUgain = mugain, htUgainPct = mpct, htXirr = mxirr}+ where+ excl = nubSort $ htUnpriced (stx []) ++ htUnpriced (tx [])+ st = stx excl+ t = tx excl+ (mugain, mpct, mxirr) = periodFigures (htValue st) (totalUgain st) (htValuedCost st) (htValue t) (totalUgain t) (htValuedCost t) (htFlows t)+ totalUgain t'+ | htValue t' == Just [] && all amountLooksZero (htValuedCost t') = Just [] -- nothing (valued) held+ | otherwise = htUgain t'+ accountPeriodTotals a = periodTotals (\x -> hrAccountTotalsExcluding startrpt x a) (\x -> hrAccountTotalsExcluding rpt x a)++ -- From the value and unrealised gain (when known) and the cost, at the+ -- start and at the end, and the period's cashflows: the period's UGain,+ -- UGain% and XIRR.+ periodFigures :: Maybe [Amount] -> Maybe [Amount] -> [Amount] -> Maybe [Amount] -> Maybe [Amount] -> [Amount] -> [(Day, Amount)]+ -> (Maybe [Amount], Maybe Quantity, Maybe Double)+ periodFigures mv0 mu0 cost0 mv1 mu1 cost1 flows = (mugain, mpct, mxirr)+ where+ mugain = do+ u0 <- mu0+ u1 <- mu1+ Just $ case u1 ++ map negate u0 of+ [] -> []+ as -> amounts $ mixed as+ mpct = do+ [g] <- mugain+ v0 <- mv0+ let costs = filter (not . amountLooksZero) $ cost0 ++ cost1+ total = sum . map aquantity+ guard $ all ((== acommodity g) . acommodity) $ v0 ++ costs+ let base = total v0 + total cost1 - total cost0+ guard $ base /= 0+ Just $ 100 * aquantity g / abs base+ mxirr = do+ v0 <- mv0+ opening <- case filter (not . amountLooksZero) v0 of+ [] -> Just []+ [v] -> Just [(addDays (-1) start, negate v)]+ _ -> Nothing+ let flows' = opening ++ flows+ -- the value at the end; nothing held is worth zero of the cashflows' commodity+ v1 <- case (mv1, flows') of+ (Just [v], _) -> Just v+ (Just [], (_, a):_) -> Just a{aquantity = 0}+ _ -> Nothing+ holdingsXirr (hrDate rpt) flows' v1++-- | The annualised internal rate of return, as a percentage, implied by+-- dated cashflows (negative = money invested) plus a final value amount+-- at the report date, when they are all in one commodity. Calculated+-- like roi's IRR (see xirr for the special cases, eg -100% when nothing+-- is left of the money invested). Nothing if it has no solution (eg an+-- infinite rate) or can not be solved.+-- Not for a short position, whose flows are a long position's with the+-- signs reversed: the rate solving those is the same, so it would report+-- a winning short as a loss. A short is recognised by a negative final+-- value (units owed), or when closed, by money received rather than+-- invested in the earliest flow.+holdingsXirr :: Day -> [(Day, Amount)] -> Amount -> Maybe Double+holdingsXirr reportdate flows finalv = do+ guard $ not $ null flows+ guard $ all ((== acommodity finalv) . acommodity . snd) flows+ let earliest = aquantity $ snd $ minimumBy (comparing fst) flows+ isshort = aquantity finalv < 0 || (aquantity finalv == 0 && earliest > 0)+ guard $ not isshort+ either (const Nothing) Just $ xirr reportdate $ (reportdate, aquantity finalv) : [(d, aquantity a) | (d, a) <- flows]++-- | The flat holdings report with its gain columns covering each+-- holding's whole life up to the report end date - except RGain and the+-- cashflows (and so XIRR), which are limited to the report period when+-- the query has a start date (flatHoldingsReport then finishes the job).+-- If a lot filter is given, just those lots are counted, and the query's+-- change:/balance: terms are not consulted.+flatHoldingsReportAt :: Maybe ((AccountName, CommoditySymbol) -> Bool) -> HoldingsReportOpts -> ReportSpec -> Journal -> HoldingsReport+flatHoldingsReportAt mkeeplot HoldingsReportOpts{hroLots=showlots, hroRounding=rounding, hroPriceOracle=mpriceoracle}+ rspec@ReportSpec{_rsQuery=q, _rsReportOpts=ropts} j =+ HoldingsReport+ { hrDate = reportdate+ , hrLines = displaylines+ , hrRows = rowlines+ , hrTotals = totalsExcluding []+ , hrAccountTotals = accountTotalsExcluding []+ , hrTotalsExcluding = totalsExcluding+ , hrAccountTotalsExcluding = accountTotalsExcluding+ , hrUnitCostHeading = unitcostheading+ , hrStyles = pctstyles+ , hrGainsPeriod = Nothing+ , hrKeepLot = keeplot+ }+ where+ -- The date this report shows holdings at: the day before the (exclusive)+ -- report end date if specified, otherwise today.+ mend = queryEndDate False q+ reportdate = maybe (_rsDay rspec) (addDays (-1)) mend++ -- The report start date, if any. Realised gains and cashflows are+ -- limited to the period from then on.+ mstart = queryStartDate False q+ inperiod d = maybe True (d >=) mstart++ -- The query used to select lot subaccount postings: the report query+ -- without its date terms (holdings are cumulative to the end date,+ -- added here) and depth terms (--depth only clips the displayed rows;+ -- the lots beneath still count).+ endq = And [filterQuery (\x -> not $ queryIsDateOrDate2 x || queryIsDepth x) q+ ,Date $ DateSpan Nothing (Exact <$> mend)]++ -- The postings contributing to each lot subaccount, keyed by account+ -- and commodity (so amounts in different commodities, not expected in+ -- a lot subaccount but possible, don't merge wrongly).+ lotpostings :: [((AccountName, CommoditySymbol), (Day, Amount))]+ lotpostings =+ [ ((paccount p, acommodity a), (postingDate p, a))+ | p <- journalPostings j+ , isJust $ lotSubaccountName $ paccount p+ , endq `matchesPosting` p+ , a <- amountsRaw $ pamount p+ ]++ -- The units held in each lot subaccount.+ lotmap :: M.Map (AccountName, CommoditySymbol) Amount+ lotmap = M.fromListWith (+) [(k, amountStripCost a) | (k, (_, a)) <- lotpostings]++ -- Each lot subaccount's cashflows in the cost commodity, for XIRR:+ -- each posting's transacted cost if any (so, proceeds when disposing),+ -- otherwise its cost basis value. Negative = money invested.+ -- A posting with no transacted cost (eg a transfer between accounts, or+ -- an opening balance) is dated on its lot's acquisition date, not its own+ -- date, so that an account receiving lots measures from when they were+ -- acquired, like its UGain and Age (and the totals row, in which a+ -- transfer's two postings cancel). With a start date, no earlier than+ -- that, since gains are measured from then.+ flowmap :: M.Map (AccountName, CommoditySymbol) [(Day, Amount)]+ flowmap = matchingLots $ M.fromListWith (++)+ [ (k, [(fd, negate flowamt)])+ | (k, (d, a)) <- lotpostings+ , inperiod d+ , Just (fd, flowamt) <- [case acost a of+ Just _ -> Just (d, amountCost a)+ Nothing -> do+ cb <- acostbasis a+ c <- cbCost cb+ let acqdate = maybe d (\acq -> maybe acq (max acq) mstart) $ cbDate cb+ Just (acqdate, multiplyAmount (aquantity a) c)]+ ]++ -- Each lot subaccount's realised gains, in the cost commodity: for each+ -- dispose posting with a transacted price and a cost basis, its cost+ -- basis minus its transacted cost. For a sale (negative) that is the+ -- proceeds minus the basis of the units sold; for a short cover+ -- (positive, in a liability account) it is the short-sale basis minus+ -- the cost of buying the units back.+ -- The gains get their commodity's display style, since the cost bases+ -- they are derived from can have more precision (eg from inferred+ -- per-unit costs).+ rgainmap :: M.Map (AccountName, CommoditySymbol) Amount+ rgainmap = matchingLots allrgainmap+ allrgainmap = M.map (styleAmounts styles) $ M.fromListWith (+)+ [ ((paccount p, acommodity a), basis - transacted)+ | p <- journalPostings j+ , isDisposePosting p+ , isJust $ lotSubaccountName $ paccount p+ , endq `matchesPosting` p+ , inperiod $ postingDate p+ , a <- amountsRaw $ pamount p+ , isJust $ acost a+ , isJust $ cbCost =<< acostbasis a+ , let basis = amountCostBasis a+ transacted = amountCost a+ , acommodity basis == acommodity transacted+ ]++ -- The current average unit cost of each AVERAGE/AVERAGEALL pool, as of+ -- the report end date, keyed by (base account, commodity). Computed+ -- from all of the pool's lot postings, whatever the query (see+ -- journalAveragePoolTotals). Used to fill in the cost missing from+ -- AVERAGE lots' costless subaccount names (see lotsUnder).+ poolavgmap :: M.Map (AccountName, CommoditySymbol) Amount+ poolavgmap = M.map (\(units, costtot) -> styleAmounts styles $ avgcost nullamt{aquantity=units} costtot)+ (journalAveragePoolTotals j mend)++ -- The per-row lookups below (lotsOf, rgainsOf, flowsOf and the+ -- *Under forms) used to scan a whole per-lot map for every displayed+ -- row, making the report roughly O(rows × lots) (#2779). Instead,+ -- each map is indexed by account up front, in two groupings:+ --+ -- "under": a key's data appears under its account and every ancestor,+ -- answering "at or under this account" queries directly.+ --+ -- "own": a key's data appears under its owning row account - the+ -- deepest candidate row account at or above it, if any - answering+ -- "in this row's own scope" queries. This is what makes overlapping+ -- rows disjoint, eg when lots are held in both an account and its+ -- subaccount (each of which then gets its own row).+ --+ -- Each group keeps the map's ascending (account, commodity) key+ -- order, as the full scans produced.++ underIx :: M.Map (AccountName, CommoditySymbol) v -> M.Map AccountName [(CommoditySymbol, v)]+ underIx m = groupIx [(anc, (c, v)) | ((sub, c), v) <- M.toAscList m+ , anc <- sub : parentAccountNames sub]++ ownIx :: M.Map (AccountName, CommoditySymbol) v -> M.Map AccountName [(CommoditySymbol, v)]+ ownIx m = groupIx [(owner, (c, v)) | ((sub, c), v) <- M.toAscList m+ , Just owner <- [ownerOf sub]]++ -- Group an ascending association list by account, each group keeping+ -- the input order (fromListWith prepends, hence the reverse).+ groupIx :: [(AccountName, a)] -> M.Map AccountName [a]+ groupIx = M.fromListWith (++) . reverse . map (fmap (:[]))++ -- A lot subaccount's owning row account: the deepest candidate row+ -- account at or above it, if any.+ ownerOf :: AccountName -> Maybe AccountName+ ownerOf sub = find (`S.member` candaccset) (sub : parentAccountNames sub)+ candaccset = S.fromList candaccts++ ownFlowIx = ownIx flowmap+ ownRgainIx = ownIx rgainmap+ underFlowIx = underIx flowmap+ underRgainIx = underIx rgainmap+ allUnderRgainIx = underIx allrgainmap++ -- Narrow an indexed group to one held commodity, if specified.+ inComm :: Maybe CommoditySymbol -> [(CommoditySymbol, v)] -> [v]+ inComm mc kvs = [v | (c, v) <- kvs, maybe True (== c) mc]++ -- The cashflows of the lots in a row account's own scope.+ flowsOf :: AccountName -> Maybe CommoditySymbol -> [(Day, Amount)]+ flowsOf acct mc = concat $ inComm mc $ M.findWithDefault [] acct ownFlowIx++ -- The realised gains of the lots at or under an account, optionally of one held commodity.+ rgainsUnder :: AccountName -> Maybe CommoditySymbol -> [Amount]+ rgainsUnder acct mc = inComm mc $ M.findWithDefault [] acct underRgainIx++ -- The realised gains of the lots in a row account's own scope.+ rgainsOf :: AccountName -> Maybe CommoditySymbol -> [Amount]+ rgainsOf acct mc = inComm mc $ M.findWithDefault [] acct ownRgainIx++ -- A lot subaccount's cost basis, parsed from its name+ -- (which by construction contains the acquisition date and unit cost).+ -- The cost gets its commodity's display style, including display+ -- precision (lot names can have more precision, eg from inferred+ -- per-unit costs), so derived amounts (Unit cost, Cost) are displayed+ -- with the standard display precision.+ lotBasis :: AccountName -> Maybe CostBasis+ lotBasis acct = do+ name <- lotSubaccountName acct+ cb <- either (const Nothing) Just $ parseLotName parseAmt name+ Just cb{cbCost = styleAmounts styles <$> cbCost cb}+ where parseAmt = either (const Nothing) Just . parseamount++ -- Amounts are displayed normalised to their commodity's display+ -- precision by default; hroRounding can choose another rounding strategy.+ styles = journalCommodityStylesWith rounding j++ priceoracle = fromMaybe (journalPriceOracle (infer_prices_ ropts) j) mpriceoracle++ -- The valuation strategy requested with -V/-X/--value, if any.+ -- It selects the valuation date and/or the valuation commodity;+ -- --value=then is rejected above.+ mvalue = value_ ropts+ (valuationdate, mtargetcomm) = case mvalue of+ Nothing -> (reportdate, Nothing)+ Just (AtEnd mc) -> (reportdate, mc)+ Just (AtNow mc) -> (_rsDay rspec, mc)+ Just (AtDate d mc) -> (d, mc)+ Just (AtThen mc) -> (reportdate, mc) -- not supported, rejected above++ -- The valuation target commodity for a lot: the commodity requested+ -- with -V/-X/--value if any, otherwise the lot's own cost commodity+ -- when known, otherwise none (the price oracle picks a default).+ lotValuationComm :: Maybe CostBasis -> Maybe CommoditySymbol+ lotValuationComm mcb = case mvalue of+ Nothing -> acommodity <$> (cbCost =<< mcb)+ Just _ -> mtargetcomm++ -- Value one lot at the valuation date: Just (unit price, total value)+ -- if it has a market price to its target commodity.+ lotValuation :: (Amount, Maybe CostBasis) -> Maybe (Amount, Amount)+ lotValuation (a, mcb) = do+ (pcomm, rate) <- priceoracle (valuationdate, acommodity a, lotValuationComm mcb)+ let mkamt n = styleAmounts styles $ amountSetFullPrecisionUpTo Nothing+ nullamt{acommodity=pcomm, aquantity=n}+ Just (mkamt rate, mkamt (rate * aquantity a))++ -- Value some lots at the valuation date: Just (their distinct unit+ -- prices, their total value per value commodity) if every lot has a+ -- market price, otherwise Nothing. Each lot is valued separately in+ -- its own target commodity, so values (and their sums, like the+ -- totals row) don't depend on how lots are grouped into display rows+ -- (by --depth, --pivot, tree mode etc).+ lotsValuation :: [(Amount, Maybe CostBasis)] -> Maybe ([Amount], [Amount])+ lotsValuation lots = do+ pvs <- mapM lotValuation lots+ Just (nubSortOn (\a -> (acommodity a, aquantity a)) $ map fst pvs+ ,sumAmounts $ map snd pvs)++ -- The market value of the lots at or under an account whose value is+ -- known (see mvalueExcluding), per value commodity.+ mvalueUnder :: AccountName -> Maybe [Amount]+ mvalueUnder acct = mvalueExcluding (unpricedCommodities lots) lots+ where lots = lotsUnder acct++ -- How to convert cost amounts (Cost, Unit/Avg cost, RGain, and the+ -- cost side of UGain) for display when -V/-X/--value is in effect:+ -- convert to the requested commodity, or to the given fallback+ -- commodity (the row's or portfolio's value commodity), at the+ -- valuation date. Costs already in the target commodity, or with no+ -- target or no market price, are left unchanged.+ costValuerTo :: Maybe CommoditySymbol -> Amount -> Amount+ costValuerTo mfallback = case mvalue of+ Nothing -> id+ Just _ -> case mtargetcomm <|> mfallback of+ Nothing -> id+ -- styleAmounts is reapplied after conversion, since+ -- amountValueAtDate leaves full precision displayed+ Just tc -> \a -> if acommodity a == tc then a+ else styleAmounts styles $+ amountValueAtDate priceoracle styles (Just tc) valuationdate a++ rowCostValuer :: PeriodicReportRow DisplayName MixedAmount -> Amount -> Amount+ rowCostValuer r = costValuerTo $ singleCommodity $ mvalueUnder (prrFullName r)++ xirrOf = holdingsXirr reportdate++ -- The total value of those lots which have a market price, per value+ -- commodity.+ pricedValue :: [(Amount, Maybe CostBasis)] -> [Amount]+ pricedValue lots = sumAmounts [v | Just (_, v) <- map lotValuation lots]++ -- The total value of all the priced holdings, including any lines+ -- hidden by change: or balance: terms. Weight is relative to this, so+ -- those terms hide lines without changing the others' weights, and+ -- unpriced holdings (which get no Weight) don't prevent the others'.+ wholevalue :: [Amount]+ wholevalue = pricedValue [l | ((sub, _), l) <- M.toList alllotbases, isJust $ ownerOf sub]++ -- A value's percentage of the priced portfolio's value (wholevalue),+ -- when both are single amounts in the same commodity.+ weightPct :: [Amount] -> Maybe Quantity+ weightPct val = do+ [t] <- Just wholevalue+ [v] <- Just val+ guard $ acommodity v == acommodity t && aquantity t /= 0+ Just $ 100 * aquantity v / aquantity t++ -- The commodity display styles, plus a default style for the "%"+ -- commodity if none is declared or inferred: one decimal digit,+ -- and the % sign on the right with no space.+ pctstyles = M.union styles $ M.singleton "%" $+ amountstyle{ascommodityside=R, asprecision=Precision 1, asrounding=HardRounding}++ -- The unrealised gains implied by value and cost amounts: value minus+ -- cost per commodity, when they cover exactly the same (nonempty) set+ -- of commodities; otherwise Nothing.+ gainAmounts :: [Amount] -> [Amount] -> Maybe [Amount]+ gainAmounts vals costs = do+ guard $ not (null vs) && map acommodity vs == map acommodity cs+ Just $ zipWith gain1 vs cs+ where+ vs = sumAmounts vals+ cs = sumAmounts costs+ gain1 v c = styleAmounts styles $ amountSetFullPrecisionUpTo Nothing+ nullamt{acommodity=acommodity v, aquantity=aquantity v - aquantity c}++ -- The percent gain, when the gains and the costs are single amounts+ -- in the same commodity and the cost is nonzero. Relative to the cost's+ -- magnitude, so a short position's gain (its cost being negative) keeps+ -- its sign.+ gainPct :: [Amount] -> [Amount] -> Maybe Quantity+ gainPct gains costs = do+ [g] <- Just gains+ [c] <- Just $ sumAmounts costs+ guard $ acommodity g == acommodity c && aquantity c /= 0+ Just $ 100 * aquantity g / abs (aquantity c)++ -- A row's units of lot-tracked commodities: the sum of the lots in+ -- its own scope, one amount per commodity. (Not the row's report+ -- balance: a depth-clipped or pivoted row could also aggregate+ -- same-commodity balances from non-lot-tracked accounts, which would+ -- make Units inconsistent with the lot-derived Cost and gain columns.)+ rowUnitAmounts :: PeriodicReportRow DisplayName MixedAmount -> [Amount]+ rowUnitAmounts r =+ filter (not . amountLooksZero) $ sumAmounts $+ map fst $ lotsOf $ prrFullName r++ -- The nonempty lots as (units, cost basis), keyed like lotmap.+ -- A lot's cost basis comes from its subaccount name, parsed once+ -- here; when the name has no cost part (AVERAGE lots' names omit it,+ -- staying stable across re-averaging), the pool's current average+ -- cost is filled in instead.+ alllotbases :: M.Map (AccountName, CommoditySymbol) (Amount, Maybe CostBasis)+ alllotbases = M.mapWithKey mklot $ M.filter (not . amountLooksZero) lotmap+ mklot (sub, _) a = (a, addPoolAvg sub a <$> lotBasis sub)+ where+ addPoolAvg sub' a' cb@CostBasis{cbCost=Nothing} =+ cb{cbCost = M.lookup (lotBaseAccount sub', acommodity a') poolavgmap}+ addPoolAvg _ _ cb = cb++ lotbases = matchingLots alllotbases++ underLotIx = underIx lotbases+ ownLotIx = ownIx lotbases+ allUnderLotIx = underIx alllotbases+ allOwnLotIx = ownIx alllotbases++ -- The query's change: and balance: terms. In this report they test each+ -- displayed line: one commodity in one row account (see lineMatches).+ -- The lots, realised gains and cashflows of the other lines are left out+ -- (by matchingLots), so that the totals and tree mode's headings follow+ -- the lines shown (but Weight stays relative to all the holdings; see+ -- wholevalue). Row ownership is decided from all lots.+ rowq = _rsRowQuery rspec++ matchingLots :: M.Map (AccountName, CommoditySymbol) v -> M.Map (AccountName, CommoditySymbol) v+ matchingLots+ | isJust mkeeplot || not (queryIsNull rowq) = M.filterWithKey (\k _ -> keeplot k)+ | otherwise = id+ keeplot :: (AccountName, CommoditySymbol) -> Bool+ keeplot = case mkeeplot of+ Just keep -> keep+ Nothing | queryIsNull rowq -> const True+ | otherwise -> \(sub, c) -> maybe False (\o -> (o, c) `S.member` matchinglines) $ ownerOf sub+ matchinglines = S.fromList+ [(o, c) | (o, c) <- nubSort [(o, c) | (sub, c) <- M.keys lotmap, Just o <- [ownerOf sub]], lineMatches o c]++ -- Each lot subaccount's change in units during the report period (all of+ -- its units, if the report has no start date), with its cost basis; the+ -- unchanged ones are left out.+ lotchanges :: M.Map (AccountName, CommoditySymbol) (Amount, Maybe CostBasis)+ lotchanges = M.mapWithKey mklot $ M.filter (not . amountLooksZero) $ M.fromListWith (+)+ [(k, amountStripCost a) | (k, (d, a)) <- lotpostings, inperiod d]+ ownLotChangeIx = ownIx lotchanges++ -- Does a row account's line for this commodity match the change: and+ -- balance: terms ? A line has two balances, its units and their market+ -- value (if all are priced), and likewise two changes: its change in+ -- units during the report period, and that valued (at the valuation+ -- date, as in the balance reports). A term with no commodity symbol tests+ -- the units; one with a symbol tests whichever of the two amounts is in+ -- that commodity, so eg balance:'>$1000' tests the value, and doesn't+ -- match an unpriced line. With -B/--cost, the cost is tested instead of+ -- the value, as displayed in Total cost (the known costs; and with+ -- -V/-X, converted like the row's costs).+ lineMatches :: AccountName -> CommoditySymbol -> Bool+ lineMatches acct c = go rowq+ where+ (balunits, balvalue) = unitsAndValue allOwnLotIx+ (chgunits, chgvalue) = unitsAndValue ownLotChangeIx+ unitsAndValue ix = (mixed $ map fst lots, if atcost then cost else mktvalue)+ where+ lots = [l | (c', l) <- M.findWithDefault [] acct ix, c' == c]+ mktvalue = maybe nullmixedamt (mixed . snd) $ lotsValuation lots+ cost = mixed [costvaluer $ multiplyAmount (aquantity a) cb | (a, mcb) <- lots, Just cb <- [cbCost =<< mcb]]+ -- like rowCostValuer, but from all lots, since this decides which are kept+ costvaluer = costValuerTo $ case lotsValuation $ map snd $ M.findWithDefault [] acct allUnderLotIx of+ Just (_, [v]) -> Just $ acommodity v+ _ -> Nothing+ go (And qs) = all go qs+ go (Not t) = not $ go t+ go (Change ord n mc) = Amt ord n mc `matchesMixedAmount` pick mc chgunits chgvalue+ go (Balance ord n mc) = Amt ord n mc `matchesMixedAmount` pick mc balunits balvalue+ go _ = True+ pick Nothing units _ = units+ pick _ units val = maPlus units val++ -- The lots held at or under the given account, excluding empty ones.+ lotsUnder :: AccountName -> [(Amount, Maybe CostBasis)]+ lotsUnder acct = map snd $ M.findWithDefault [] acct underLotIx++ -- The lots in a row account's own scope, excluding empty ones.+ lotsOf :: AccountName -> [(Amount, Maybe CostBasis)]+ lotsOf acct = map snd $ M.findWithDefault [] acct ownLotIx++ -- Report rows come from a single-period, end-balances multiBalanceReport:+ -- on the lot-detailed journal with --lots (rows are lot subaccounts),+ -- on the collapsed journal otherwise (rows are the base accounts).+ -- Non-holding accounts are filtered out.+ -- Cost conversion and valuation (-B/-V/--value) are disabled:+ -- holdings does its own valuation, and units should stay units.+ -- Nor does it apply the change:/balance: terms; they are tested here (see rowq).+ -- Its query has no start date, since holdings are cumulative (a start date+ -- after the last posting would otherwise leave an empty report span).+ mbr = multiBalanceReport rspec' j'+ where+ rspec' = rspec{_rsRowQuery = Any+ ,_rsQuery = And [filterQuery (not . queryIsDateOrDate2) q, Date $ DateSpan Nothing (Exact <$> mend)]+ ,_rsReportOpts=ropts{balanceaccum_=Historical, interval_=NoInterval+ ,conversionop_=Just NoConversionOp, value_=Nothing+ ,sort_amount_=False}} -- -S sorts by value/cost below, not by units+ j' = if showlots then j else journalCollapseLotDetail j+ -- Candidate rows: those with lots at or beneath them; with -E/--empty,+ -- also those with realised gains at or beneath them (fully disposed+ -- accounts/lots, normally hidden).+ candidates = filter isholdingrow $ prRows mbr+ where+ isholdingrow r = not (null (M.findWithDefault [] acct allUnderLotIx))+ || (empty_ ropts && any (not . amountLooksZero . snd) (M.findWithDefault [] acct allUnderRgainIx))+ where acct = prrFullName r+ candaccts = map prrFullName candidates++ -- Rows to display: the candidates, except those with nothing in+ -- their own scope (eg a base account row whose lots all appear in+ -- displayed lot subaccount rows). A row holding lots directly is+ -- kept even when a deeper row also displays; it shows just its own+ -- lots (see ownIx).+ rows = filter keeprow candidates+ where+ keeprow r = not (null (lotsOf acct))+ || (empty_ ropts && not (null $ rgainOnlyCommodities acct))+ where acct = prrFullName r++ -- The commodities with nonzero realised gains in this row account's own+ -- scope but no units held there (eg fully sold off).+ rgainOnlyCommodities :: AccountName -> [CommoditySymbol]+ rgainOnlyCommodities acct =+ nubSort [ c | (c, g) <- M.findWithDefault [] acct ownRgainIx, not $ amountLooksZero g+ , c `notElem` map fst (M.findWithDefault [] acct allOwnLotIx) ]++ -- The topmost displayed rows: those not contained in another displayed+ -- row. Totals are computed from these, to avoid double counting.+ toprows = [ r | r <- rows+ , not $ any (`S.member` rowaccset) (parentAccountNames $ prrFullName r) ]+ where rowaccset = S.fromList $ map prrFullName rows++ -- With -B/--cost, -S sorts and the change:/balance: terms test cost instead of value.+ atcost = conversionop_ ropts == Just ToCost++ -- The displayed table lines: each report row's holdings, one line per+ -- commodity, with the report row kept for rendering the account cell+ -- (repeated on each of its lines). They are in account name order, or+ -- with -S, each line is sorted by its own amounts (see+ -- holdingsSortKey), ties keeping the account name order. Tree mode+ -- groups these into account sections, keeping this order within each.+ rowlines :: [(PeriodicReportRow DisplayName MixedAmount, Holding)]+ rowlines+ | sort_amount_ ropts = sortOn (\(_, h) -> holdingsSortKey atcost (hValue h) (hCost h)) namelines+ | otherwise = namelines+ where namelines = [(r, h) | r <- rows, h <- rowHoldings r]++ -- One display line per report line.+ displaylines :: [HoldingsLine]+ displaylines =+ [ HoldingsPosition+ { hlIndent = prrIndent r+ , hlAccount = prrFullName r+ , hlDisplay = prrDisplayName r+ , hlIsLot = isJust $ lotSubaccountName $ prrFullName r+ , hlHolding = h }+ | (r, h) <- rowlines ]++ -- The cost column's heading matches what's shown: "Avg cost" on rows+ -- aggregating multiple lots (the default) or when the lots shown all+ -- belong to AVERAGE/AVERAGEALL pools (whose per-lot rows show the+ -- pool's average cost); "Unit cost" when each lot shows its own cost;+ -- "Unit/Avg cost" when both kinds of lot are shown.+ -- TRANSLATORS: the holdings table's cost column heading, translated where it is displayed.+ unitcostheading :: T.Text+ unitcostheading+ | not showlots || allavg = I18n.i18n "Avg cost"+ | anyavg = I18n.i18n "Unit/Avg cost"+ | otherwise = I18n.i18n "Unit cost"+ where+ avgs = [ fst (resolveReductionMethodForAccount j (lotBaseAccount sub) c)+ `elem` [AVERAGE, AVERAGEALL]+ | (sub, c) <- M.keys lotmap ]+ allavg = not (null avgs) && and avgs+ anyavg = or avgs++ -- Sum amounts per commodity, keeping an empty list empty+ -- (unlike amounts . mixed, which would make it a single zero).+ sumAmounts :: [Amount] -> [Amount]+ sumAmounts [] = []+ sumAmounts as = amounts $ mixed as++ -- A report row's holdings, one per commodity, in the same order as its+ -- unit amounts. With -E/--empty, these are followed by a zero-units+ -- holding for each commodity no longer held at or under the row's+ -- account but with realised gains, keeping those visible (eg a+ -- commodity fully sold off); without -E such rows are hidden (their+ -- gains still count in the totals row).+ rowHoldings :: PeriodicReportRow DisplayName MixedAmount -> [Holding]+ rowHoldings r = map rec $ heldamts ++ rgainonlyamts+ where+ acct = prrFullName r+ heldamts = rowUnitAmounts r+ rgainonlyamts+ | not $ empty_ ropts = []+ | otherwise = [nullamt{acommodity=c} | c <- rgainOnlyCommodities acct]+ rec qa = Holding+ { hAccount = acct+ , hCommodity = c+ , hDate = mdate+ , hAge = diffDays reportdate <$> mdate+ , hUnits = styleAmounts styles qa+ , hUnitCost = mucost+ , hCost = sumAmounts ccosts+ , hPrice = prices+ , hValue = vals+ , hWeight = weightPct vals+ , hUgain = gains+ , hUgainPct = gainPct gains ccosts+ , hRgain = sumAmounts $ map (rowCostValuer r) $ rgainsOf acct (Just c)+ , hXirr = mxirr+ , hFlows = flowsOf acct (Just c)+ }+ where+ c = acommodity qa+ clots = filter ((==c) . acommodity . fst) $ lotsOf acct+ dates = nubSort [cbDate =<< mcb | (_, mcb) <- clots]+ mdate = case dates of+ [Just dt] -> Just dt+ _ -> Nothing+ ccosts+ -- a line with no units held (shown for its realised gain) costs zero, in the gain's commodity+ | null clots = [g{aquantity = 0} | g <- take 1 $ rgainsOf acct (Just c)]+ | otherwise = [rowCostValuer r $ multiplyAmount (aquantity a) cb | (a, mcb) <- clots, Just cb <- [cbCost =<< mcb]]+ mucost = case (clots, ccosts) of+ ([(_, mcb)], _) -> rowCostValuer r <$> (cbCost =<< mcb)+ (_, _:_) | [totcost] <- amounts (mixed ccosts)+ , not $ amountLooksZero qa+ -> Just $ avgcost qa totcost+ _ -> Nothing+ -- The line's lots to value; a zero-units (rgain-only) line+ -- values a synthetic zero lot, so a market price and a zero+ -- value can still be shown.+ vlots = if null clots then [(qa, Nothing)] else clots+ (prices, vals) = fromMaybe ([], []) $ lotsValuation vlots+ gains = fromMaybe [] $ gainAmounts vals ccosts+ mxirr = do+ [v] <- Just vals+ xirrOf (flowsOf acct (Just c)) v++ -- The grand totals, summed over the topmost displayed rows; the+ -- RGain and XIRR components cover all the lots within the query and+ -- end date, whatever rows are displayed (#2769; see HoldingsTotals).+ -- The value, gains and cashflows leave out the holdings whose value is+ -- unknown, and those of the given commodities (see htUnpriced).+ totalsExcluding :: [CommoditySymbol] -> HoldingsTotals+ totalsExcluding excl0 = HoldingsTotals+ { htUnits = case totunits of [u] -> Just u; _ -> Nothing+ , htAvgCost = case (totunits, sumAmounts totcosts) of+ ([u], [c]) -> Just $ avgcost u c+ _ -> Nothing+ , htCost = amounts $ mixed totcosts+ , htPrice = singlePrice toplots+ , htValue = mvalue'+ , htWeight = weightPct $ pricedValue toplots+ , htUgain = mgains+ , htUgainPct = gainPct (fromMaybe [] mgains) valuedcosts+ , htRgain = case map (costValuerTo mvaluecomm) $ M.elems rgainmap of+ [] -> []+ rs -> amounts $ mixed rs+ , htXirr = do+ [tv] <- mvalue'+ xirrOf flows tv+ , htFlows = flows+ , htValuedCost = amounts $ mixed valuedcosts+ , htUnpriced = excl+ }+ where+ toplots = concatMap (lotsUnder . prrFullName) toprows+ excl = nubSort $ excl0 ++ unpricedCommodities toplots+ mvalue' = mvalueExcluding excl toplots+ mvaluecomm = singleCommodity mvalue'+ totunits = filter (not . amountLooksZero) $ sumAmounts $ map fst toplots+ -- each lot's cost, with its units+ lotcosts = [ (a, rowCostValuer r $ multiplyAmount (aquantity a) c)+ | r <- toprows, (a, mcb) <- lotsUnder (prrFullName r), Just c <- [cbCost =<< mcb] ]+ totcosts = map snd lotcosts+ valuedcosts = [k | (a, k) <- lotcosts, acommodity a `notElem` excl]+ mgains = mvalue' >>= \v -> gainAmounts v valuedcosts+ flows = concat [fs | ((_, c), fs) <- M.toList flowmap, c `notElem` excl]++ -- The totals of the lots at or under one account, computed like the+ -- grand totals row: an account heading row's figures. Like those,+ -- RGain and XIRR cover all the subtree's lots within the query and+ -- end date, including fully disposed ones with no row (#2769), and+ -- the value, gains and cashflows leave out the holdings whose value is+ -- unknown, and those of the given commodities. Weight is relative to+ -- the whole portfolio's value.+ accountTotalsExcluding :: [CommoditySymbol] -> AccountName -> HoldingsTotals+ accountTotalsExcluding excl0 acct = HoldingsTotals+ { htUnits = case units of [u] -> Just u; _ -> Nothing+ , htAvgCost = case (units, sumAmounts costs) of+ ([u], [c]) -> Just $ avgcost u c+ _ -> Nothing+ , htCost = sumAmounts costs+ , htPrice = singlePrice lots+ , htValue = msubvalue+ , htWeight = weightPct $ pricedValue lots+ , htUgain = mgains+ , htUgainPct = gainPct (fromMaybe [] mgains) valuedcosts+ , htRgain = sumAmounts $ map (costValuerTo msubvaluecomm) $ rgainsUnder acct Nothing+ , htXirr = do+ [v] <- msubvalue+ xirrOf flows v+ , htFlows = flows+ , htValuedCost = sumAmounts valuedcosts+ , htUnpriced = excl+ }+ where+ lots = lotsUnder acct+ excl = nubSort $ excl0 ++ unpricedCommodities lots+ units = filter (not . amountLooksZero) $ sumAmounts $ map fst lots+ -- each lot's cost, with its units+ lotcosts = [ (a, costValuerTo msubvaluecomm $ multiplyAmount (aquantity a) c)+ | (a, mcb) <- lots, Just c <- [cbCost =<< mcb] ]+ costs = map snd lotcosts+ valuedcosts = [k | (a, k) <- lotcosts, acommodity a `notElem` excl]+ msubvalue = mvalueExcluding excl lots+ msubvaluecomm = singleCommodity msubvalue+ mgains = msubvalue >>= \subvalue -> gainAmounts subvalue valuedcosts+ flows = concat [fs | (c, fs) <- M.findWithDefault [] acct underFlowIx, c `notElem` excl]++ -- The commodities of these lots which have a lot with no market price,+ -- so whose holdings' value is unknown.+ unpricedCommodities :: [(Amount, Maybe CostBasis)] -> [CommoditySymbol]+ unpricedCommodities lots = nubSort [acommodity a | l@(a, _) <- lots, isNothing $ lotValuation l]++ -- The market value of these lots, per value commodity, leaving out+ -- those of the given commodities (eg the unpriced ones); Nothing if+ -- some of the others can't be valued.+ mvalueExcluding :: [CommoditySymbol] -> [(Amount, Maybe CostBasis)] -> Maybe [Amount]+ mvalueExcluding excl lots = snd <$> lotsValuation (filter ((`notElem` excl) . acommodity . fst) lots)++ -- The commodity of a value, when it is a single amount.+ singleCommodity :: Maybe [Amount] -> Maybe CommoditySymbol+ singleCommodity mv = case mv of+ Just [v] -> Just $ acommodity v+ _ -> Nothing++ -- The unit market price of some lots, when they are all of one commodity+ -- and have the same price.+ singlePrice :: [(Amount, Maybe CostBasis)] -> Maybe Amount+ singlePrice lots = do+ [_] <- Just $ nubSort $ map (acommodity . fst) lots+ ([p], _) <- lotsValuation lots+ Just p++ -- An average cost: total cost / total units, shown like other amounts+ -- in the cost commodity's display precision - but with at least 2+ -- decimal digits when the division is inexact and the display+ -- precision is less, so eg an average of $56.666... is not shown as+ -- the misleading $57.+ avgcost qtya costa = amountSetPrecision (Precision p) avg+ where+ avg = divideAmountAndUpdatePrecision (aquantity qtya) costa+ p = clamp pstyle (max 2 pstyle) pdiv+ clamp lo hi = max lo . min hi+ pdiv = case asprecision (astyle avg) of Precision n -> n; _ -> defaultMaxDisplayPrecision+ pstyle = case asprecision (astyle costa) of Precision n -> n; _ -> 2++-- | The commodities whose holdings some totals leave out of their value, gains and XIRR,+-- having no market price, when they show those of other holdings. (When they show none,+-- those are simply blank.)+totalsLeftOut :: HoldingsTotals -> [CommoditySymbol]+totalsLeftOut tot = case htValue tot of+ Just (_:_) -> htUnpriced tot+ _ -> []++-- | A note saying which commodities' holdings the totals' value, gains and XIRR+-- leave out, having no market price (see 'htUnpriced'), if there are any.+holdingsUnpricedNote :: I18n.Translations -> [CommoditySymbol] -> Maybe T.Text+holdingsUnpricedNote _ [] = Nothing+holdingsUnpricedNote trs cs = Just $+ -- TRANSLATORS: a note below the holdings table; {commodities} is a list of commodity symbols, like "AAPL, VTI".+ I18n.trf trs "Total value, UGain, UGain% and XIRR totals exclude holdings with no market price: {commodities}"+ [("commodities", T.intercalate ", " $ map quoteCommoditySymbolIfNeeded cs)]++-- | How many closed positions (an account's commodity, fully disposed, with+-- a realised gain) a holdings report of this spec and journal leaves out of its+-- rows, for lack of -E/--empty. The totals' RGain and XIRR still include them.+holdingsClosedHidden :: HoldingsReportOpts -> ReportSpec -> Journal -> Int+holdingsClosedHidden hropts rspec j+ | empty_ ropts = 0+ | otherwise = length [() | (_, h) <- hrRows rpt, aquantity (hUnits h) == 0]+ where+ ropts = _rsReportOpts rspec+ rpt = holdingsReport hropts{hroLots = False} rspec{_rsReportOpts = ropts{empty_ = True, sort_amount_ = False}} j++-- | A note saying how many closed positions are not shown, though the totals'+-- RGain and XIRR include them (see 'holdingsClosedHidden'), if there are any.+holdingsClosedNote :: I18n.Translations -> Int -> Maybe T.Text+holdingsClosedNote _ 0 = Nothing+holdingsClosedNote trs n = Just $+ -- TRANSLATORS: a note below the holdings table; {n} is the number of closed (fully disposed) positions.+ I18n.trn trs n "RGain and XIRR totals include {n} closed position, not shown" "RGain and XIRR totals include {n} closed positions, not shown"++-- | A report spec with these start and end dates in place of its query's dates+-- (Nothing for the end date keeps the query's end date).+holdingsSpecWithDates :: ReportSpec -> Maybe EFDay -> Maybe EFDay -> ReportSpec+holdingsSpecWithDates rspec mb me =+ rspec{_rsQuery = And [ filterQuery (not . queryIsDateOrDate2) $ _rsQuery rspec+ , Date $ DateSpan mb (me <|> (Exact <$> queryEndDate False (_rsQuery rspec)))]}++-- | Holdings reports at the end of each of the report spec's periods (it should have a report interval),+-- like the single-date report computed at each period's end. Their gain columns cover the time since acquisition+-- (Historical), each period (PerPeriod), or the time since the first period's start (Cumulative).+-- List/tree mode and lots don't matter here (only the reports' totals are meant to be shown),+-- so these are flat and without lots.+holdingsPeriodReports :: HoldingsReportOpts -> BalanceAccumulation -> ReportSpec -> Journal -> [(DateSpan, HoldingsReport)]+holdingsPeriodReports hropts accum rspec j =+ [ (spn, holdingsReport hropts{hroLots = False} (rspecFor mb e) j)+ | spn@(DateSpan mb (Just e)) <- periodspans ]+ where+ -- each period's report: as of its end, with gains since acquisition, or+ -- during the period, or since the first period's start+ rspecFor mb e = (holdingsSpecWithDates rspec mstart (Just e)){_rsReportOpts = (_rsReportOpts rspec){accountlistmode_ = ALFlat}}+ where mstart = case accum of+ Historical -> Nothing+ PerPeriod -> mb+ Cumulative -> mfirststart+ mfirststart = case periodspans of+ DateSpan mb _ : _ -> mb+ [] -> Nothing+ -- The periods: as usual (with no end date, ending with the journal's last+ -- postings), but since values change with market prices, with no end date+ -- they always extend to today, and the period containing today ends today,+ -- like the single-date report. (Periods after it, from future-dated+ -- postings, are kept.)+ periodspans+ | isJust (queryEndDate False $ _rsQuery rspec) = defspans+ | reachestoday defspans = map clip defspans+ | otherwise = map clip $ spansOf rspec{_rsQuery = And [_rsQuery rspec, Date $ DateSpan Nothing (Just $ Exact tomorrow)]}+ where+ spansOf = maybeDayPartitionToDateSpans . snd . reportSpanBothDates j+ defspans = spansOf rspec+ tomorrow = addDays 1 $ _rsDay rspec+ reachestoday = any (\(DateSpan _ me) -> maybe False ((>= tomorrow) . fromEFDay) me)+ clip spn@(DateSpan mb (Just e))+ | fromEFDay e > tomorrow && maybe True ((< tomorrow) . fromEFDay) mb = DateSpan mb (Just $ Exact tomorrow)+ | otherwise = spn+ clip spn = spn++-- | The default title of some holdings reports at period ends (see 'holdingsPeriodReports'),+-- saying their interval, which dates they cover and what their gain columns cover.+holdingsPeriodsTitle :: I18n.Translations -> Interval -> BalanceAccumulation -> [(DateSpan, HoldingsReport)] -> T.Text+holdingsPeriodsTitle trs ivl accum rpts = case (map (hrDate . snd) rpts, accum) of+ ([], _) -> ivltitle+ -- TRANSLATORS: the title of the holdings report with a report interval; {holdings} is eg "Monthly holdings", {dates} a date range like 2026-01-31..2026-06-30.+ (ds, Historical) -> trf "{holdings}, {dates}" [("holdings", ivltitle), ("dates", showdates ds)]+ -- TRANSLATORS: the title of the holdings report with a report interval and --change; {holdings} is eg "Monthly holdings", {dates} a date range like 2026-01-31..2026-06-30.+ (ds, PerPeriod) -> trf "{holdings}, {dates}, gains in each period" [("holdings", ivltitle), ("dates", showdates ds)]+ -- TRANSLATORS: the title of the holdings report with a report interval and --cumulative; {holdings} is eg "Monthly holdings", {dates} a date range like 2026-01-31..2026-06-30, {start} the report start date.+ (ds, Cumulative) -> trf "{holdings}, {dates}, gains since {start}" [("holdings", ivltitle), ("dates", showdates ds), ("start", maybe "" (showDate . fromEFDay) mfirststart)]+ where+ trf = I18n.trf trs+ ivltitle = I18n.tr trs $ holdingsIntervalTitle $ titleInterval ivl+ showdates ds = showDate (minimum ds) <> ".." <> showDate (maximum ds)+ mfirststart = case rpts of+ (DateSpan mb _, _) : _ -> mb+ [] -> Nothing++-- | The start of the holdings report's title with a report interval.+holdingsIntervalTitle :: Interval -> T.Text+holdingsIntervalTitle = \case+ -- TRANSLATORS: the start of the holdings report's title, with its reporting interval. Each is a+ -- whole phrase, so put the words in the order and form your language needs.+ Days 1 -> I18n.i18n "Daily holdings"+ Weeks 1 -> I18n.i18n "Weekly holdings"+ Weeks 2 -> I18n.i18n "Biweekly holdings"+ Months 1 -> I18n.i18n "Monthly holdings"+ Months 2 -> I18n.i18n "Bimonthly holdings"+ Months 3 -> I18n.i18n "Quarterly holdings"+ Months 6 -> I18n.i18n "Half-yearly holdings"+ Years 1 -> I18n.i18n "Yearly holdings"+ Years 2 -> I18n.i18n "Biennial holdings"+ _ -> I18n.i18n "Periodic holdings"++-- | Show the holdings report: the assets held in lot-tracked accounts+-- as of the report end date, one row per account (or per lot, with --lots).+--+-- This command receives the journal with lot detail (lot subaccounts and+-- synthetic postings) uncollapsed, regardless of --lots+-- (see maybePrepareLotDetail); holdingsReport aggregates lots itself.+holdings :: CliOpts -> Journal -> IO ()+holdings opts@CliOpts{rawopts_=rawopts, reportspec_=rspec@ReportSpec{_rsReportOpts=ropts}} j = do+ warnIfLargeMultiPeriodReport rspec j+ if (case value_ ropts of Just (AtThen _) -> True; _ -> False)+ then error' "holdings: --value=then is not supported"+ else rounding `seq` -- validate the --round value before any output+ if | chartRequested opts && periodic ->+ writeChart opts (Just $ (<>"\n") $ htmlAsLazyText $ (titledTableHtml ptitle phtmltable <> htmlnote (("* " <>) <$> pnote))) $ holdingsReportsAsChart ropts paccum ptitle periodrpts+ | chartRequested opts ->+ writeChart opts (Just $ (<>"\n") $ htmlAsLazyText $ (titledTableHtml title htmltable <> foldMap (htmlnote . Just) notes)) $ holdingsReportAsChart ropts title rpt+ | periodic -> writeOutputLazyText opts $ case outputFormatFromOpts opts of+ "txt" -> ptxtoutput+ "csv" -> printCSV pcsvoutput+ "tsv" -> printTSV pcsvoutput+ "html" -> (<>"\n") $ htmlAsLazyText $ (titledTableHtml ptitle phtmltable <> htmlnote (("* " <>) <$> pnote))+ "fods" -> printFods IO.localeEncoding $ M.singleton (tr "Holdings") ((1,0), pfodstable)+ "json" -> (<>"\n") $ toJsonText $ map (uncurry periodTotalsJson) ptotals+ fmt -> error' $ unsupportedOutputFormatError fmt+ | otherwise -> writeOutputLazyText opts $ case outputFormatFromOpts opts of+ "txt" -> txtoutput+ "csv" -> printCSV csvoutput+ "tsv" -> printTSV csvoutput+ "html" -> (<>"\n") $ htmlAsLazyText $ (titledTableHtml title htmltable <> foldMap (htmlnote . Just) notes)+ "fods" -> printFods IO.localeEncoding $ M.singleton (tr "Holdings") ((1,0), fodstable)+ "json" -> (<>"\n") $ toJsonText $ map holdingJson holdingrecords+ fmt -> error' $ unsupportedOutputFormatError fmt+ where+ -- Amounts are displayed normalised to their commodity's display+ -- precision by default; --round can choose another rounding strategy.+ rounding = fromMaybe HardRounding $ roundFromRawOpts rawopts+ tr = I18n.tr (translations_ ropts)+ trf = I18n.trf (translations_ ropts)++ rpt = holdingsReport hropts rptspec j+ hropts = HoldingsReportOpts{hroLots = boolopt "lots" rawopts, hroRounding = rounding, hroPriceOracle = Just priceoracle}+ rptspec = if maccum == Just Historical then holdingsSpecWithDates rspec Nothing Nothing else rspec++ -- --change, --cumulative or --historical/-H, if specified: which period the+ -- gain columns cover. In the single-date report, a start date gives the gains+ -- during the report period (--change, or the same, --cumulative), unless+ -- --historical asks for the gains since acquisition. With a report interval,+ -- the default is --historical.+ maccum = balanceAccumulationOverride rawopts++ -- one price oracle for all the reports (eg one per period)+ priceoracle = journalPriceOracle (infer_prices_ ropts) j+ paccum = fromMaybe Historical maccum++ rowlines = hrRows rpt+ reportdate = hrDate rpt++ -- With a report interval, the holdings at the end of each period (their totals, in a row per period).+ periodic = interval_ ropts /= NoInterval+ periodrpts = holdingsPeriodReports+ HoldingsReportOpts{hroLots = False, hroRounding = rounding, hroPriceOracle = Just priceoracle} paccum rspec j+ ptotals = [(hrDate r, (hrStyles r, hrTotals r)) | (_, r) <- periodrpts]+ ptitle = effectiveTitle ropts $ holdingsPeriodsTitle (translations_ ropts) (interval_ ropts) paccum periodrpts+ -- The Units, Avg cost and Unit price columns are shown only when some period has a single commodity+ -- (they are blank otherwise); Weight is always 100%, and Date and Age don't apply.+ showunits = any (isJust . htUnits . snd . snd) ptotals+ pcolheadings = [h | (h, shown) <- zip allpcolheadings pcolshown, shown]+ allpcolheadings = [tr "Units", tr "Avg cost", tr "Unit price", tr "Total cost", tr "Total value", tr "UGain", tr "UGain%", tr "RGain", tr "XIRR"]+ pcolshown = replicate 3 showunits ++ replicate 6 True+ -- a period's cells: those of the totals row's cells which make sense over time, and its unit price+ periodcells c (styles, tot) = [ps | (ps, shown) <- zip (take 2 cells ++ [price] ++ drop 2 cells) pcolshown, shown]+ where+ cells = [ps | (i, ps) <- zip [0 :: Int ..] (totalsCellParts c styles tot), i `elem` [2, 3, 5, 6, 8, 9, 10, 11]]+ price = maybe [] ((:[]) . showAmountB noCostFmt) (htPrice tot)+ -- for the html and fods tables: whether each shown column is an amount, and its class+ pcolinfo = [ci | (ci, shown) <- zip [(True,"units"),(True,"unitcost"),(True,"unitprice"),(True,"totalcost"),(True,"totalvalue"),(True,"ugain"),(False,"ugainpct"),(True,"rgain"),(False,"xirr")] pcolshown, shown]+ ptxtoutput =+ (case ptitle of+ "" -> ""+ t -> TL.fromStrict t <> "\n\n")+ <>+ if null ptotals+ then TL.fromStrict (tr "(no holdings)") <> "\n"+ else renderTable def{tableBorders=False} (textCell TopLeft) (textCell TopRight) (Cell TopRight . pure) (Table+ (Group NoLine [Header $ pdate d st | (d, st) <- ptotals])+ (Group NoLine $ map Header pcolheadings)+ [map joinParts $ periodcells (color_ ropts) st | (_, st) <- ptotals])+ <> txtnote (("* " <>) <$> pnote)+ -- A period's date, starred if its totals leave out unpriced holdings,+ -- which the note below the table names.+ pdate d (_, tot) = showDate d <> if null (totalsLeftOut tot) then "" else "*"+ pnote = holdingsUnpricedNote (translations_ ropts) $ nubSort $ concatMap (totalsLeftOut . snd . snd) ptotals+ pcsvoutput :: CSV+ pcsvoutput = ["date","units","avgcost","unitprice","totalcost","totalvalue","ugain","ugainpct","rgain","xirr","unpriced"] : map (uncurry periodTotalsCsv) ptotals+ -- spreadsheet-shaped tables for the html and fods output, like the text table+ pspreadsheetWith :: forall content. (T.Text -> content) -> (Bool -> [T.Text] -> content) -> [[Ods.Cell Ods.NumLines content]]+ pspreadsheetWith plain parts =+ addHeaderBorders [plain <$> (headerCell t){Ods.cellClass = Ods.Class cls} | (t, cls) <- zip (tr "Date" : pcolheadings) ("date" : map snd pcolinfo)]+ : [ (Ods.defaultCell (plain $ pdate d st)){Ods.cellType = Ods.TypeString, Ods.cellClass = Ods.Class "date"}+ : [ (Ods.defaultCell (parts isamount ps)){Ods.cellType = Ods.TypeMixedAmount, Ods.cellClass = Ods.Class cls}+ | ((isamount, cls), ps) <- zip pcolinfo (textParts $ periodcells False st) ]+ | (d, st) <- ptotals ]+ phtmltable = pspreadsheetWith toHtml htmlParts+ pfodstable = pspreadsheetWith id (\_ -> T.intercalate ", " . filter (not . T.null))++ -- The default title can be customised or suppressed with --title.+ -- TRANSLATORS: the holdings report's title; {date} is the report date, {period} the report period (eg 2026-11, or 2026-11-01..2026-11-14) if it has a start date.+ title = effectiveTitle ropts $ case hrGainsPeriod rpt of+ Nothing -> trf "Holdings on {date}" [("date", showDate reportdate)]+ Just spn -> trf "Holdings on {date}, gains in {period}" [("date", showDate reportdate), ("period", showDateSpan spn)]+ txtoutput =+ (case title of+ "" -> ""+ t -> TL.fromStrict t <> "\n\n")+ <>+ if null rowlines+ then TL.fromStrict (tr "(no holdings)") <> "\n"+ else renderTable+ def{tableBorders=False}+ (textCell TopLeft)+ (textCell TopRight)+ (Cell TopRight . pure)+ tbl+ <> foldMap (txtnote . Just) notes++ -- Notes about the totals, when there are totals (a totals row, or+ -- tree mode's headings): that they leave out unpriced holdings, if+ -- any, and that their RGain and XIRR include closed positions which+ -- are not shown, if any.+ notes+ | no_total_ ropts && accountlistmode_ ropts /= ALTree = []+ | otherwise = catMaybes+ [ holdingsUnpricedNote (translations_ ropts) $ totalsLeftOut $ hrTotals rpt+ -- TRANSLATORS: follows the holdings report's closed positions note, naming the flag that shows them.+ , (<> " " <> tr "(see -E)") <$> holdingsClosedNote (translations_ ropts) (holdingsClosedHidden hropts rptspec j)+ ]+ -- A note below a text table, after a blank line.+ txtnote = maybe "" (\n -> "\n" <> TL.fromStrict n <> "\n")+ -- A note below an html table.+ htmlnote :: Maybe T.Text -> Html+ htmlnote = maybe mempty (H.p . toHtml)++ tbl = maybe id addtotalrow (map joinParts <$> mtotalrowparts (color_ ropts)) $ Table+ (Group NoLine $ map (Header . lineacct) displaylines)+ (Group NoLine $ map Header colheadings)+ (map (map joinParts . linecells (color_ ropts)) displaylines)+ where+ addtotalrow totalrow tbl' = concatTables SingleLine tbl' $+ Table (Group NoLine [Header ""]) (Header []) [totalrow]+ -- TRANSLATORS: the holdings table's column headings. The cost heading is "Unit cost", "Avg cost", or "Unit/Avg cost".+ colheadings = [tr "Date", tr "Age", tr "Units", tr (hrUnitCostHeading rpt), tr "Unit price", tr "Total cost", tr "Total value", tr "Weight", tr "UGain", tr "UGain%", tr "RGain", tr "XIRR"]+ displaylines = hrLines rpt++ -- A display line's account cell: indented display names in tree+ -- mode, full (possibly dropped) account names otherwise.+ lineacct :: HoldingsLine -> T.Text+ lineacct l+ | accountlistmode_ ropts == ALTree && not (full_names_ ropts) =+ T.replicate (hlIndent l * 2) " " <> hlDisplay l+ | otherwise = accountNameDrop (drop_ ropts) (hlAccount l)++ -- A display line's data cells, each as a list of parts,+ -- with gains and losses coloured if the flag is true (see gainColour).+ linecells :: Bool -> HoldingsLine -> [[WideBuilder]]+ linecells c HoldingsHeading{hlTotals} = totalsCellParts c (hrStyles rpt) hlTotals+ linecells c HoldingsPosition{hlHolding} = holdingCellParts c hlHolding++ -- A text table cell from its parts, comma-separated.+ joinParts :: [WideBuilder] -> WideBuilder+ joinParts = mconcat . intersperse (wbFromText ", ")+ -- Cells' parts as plain text, for the html and fods tables.+ textParts :: [[WideBuilder]] -> [[T.Text]]+ textParts = map (map wbToText)++ -- Colour a gain (or the like, eg an XIRR) green if positive and a loss red, if the flag is true.+ -- Colouring a WideBuilder keeps its width, so text tables stay aligned.+ gainColour :: Bool -> Quantity -> WideBuilder -> WideBuilder+ gainColour c q+ | c && q > 0 = colorB Dull Green+ | c && q < 0 = colorB Dull Red+ | otherwise = id++ showpct = showPercentWith (hrStyles rpt)+ -- Show an XIRR percentage, like showpct: eg 12.3%.+ showxirr :: Double -> T.Text+ showxirr = showpct . realToFrac++ -- A holding's cells, each as a list of parts: possibly several in Cost+ -- and RGain (when cost commodities are mixed), at most one elsewhere.+ -- Units show a commodity symbol even when zero (for rgain-only rows).+ holdingCellParts :: Bool -> Holding -> [[WideBuilder]]+ holdingCellParts c h =+ [ [wbFromText $ maybe "" showDate (hDate h)]+ , [wbFromText $ maybe "" showage (hAge h)]+ , [showamtz (hUnits h)]+ , [maybe mempty showamt (hUnitCost h)]+ , map showamt $ hPrice h+ , map showamtz $ hCost h+ , map showamtz $ hValue h+ , [wbFromText $ maybe "" showpct (hWeight h)]+ , map (gainamt showamtz) $ hUgain h+ , [maybe mempty (\p -> gainColour c p $ wbFromText $ showpct p) (hUgainPct h)]+ , map (gainamt showamt) $ hRgain h+ , [maybe mempty (\x -> gainColour c (realToFrac x) $ wbFromText $ showxirr x) (hXirr h)]+ ]+ where+ showamt = showAmountB noCostFmt+ showamtz = showAmountB noCostFmt{displayZeroCommodity=True}+ gainamt sh a = gainColour c (aquantity a) (sh a)++ -- A totals row's cells (the grand total, or an account heading row+ -- in tree mode), each as a list of parts like holdingCellParts.+ totalsCellParts :: Bool -> M.Map CommoditySymbol AmountStyle -> HoldingsTotals -> [[WideBuilder]]+ totalsCellParts c styles tot =+ [ []+ , []+ , maybe [] ((:[]) . showamt) (htUnits tot)+ , maybe [] ((:[]) . showamt) (htAvgCost tot)+ , []+ , map showamt (htCost tot)+ , maybe [] (map showamt) (htValue tot)+ , [wbFromText $ maybe "" pct (htWeight tot)]+ , maybe [] (map (gainamt showamtz)) (htUgain tot)+ , [maybe mempty (\p -> gainColour c p $ wbFromText $ pct p) (htUgainPct tot)]+ , map (gainamt showamt) (htRgain tot)+ , [maybe mempty (\x -> gainColour c (realToFrac x) $ wbFromText $ pct $ realToFrac x) (htXirr tot)]+ ]+ where+ pct = showPercentWith styles+ showamt = showAmountB noCostFmt+ showamtz = showAmountB noCostFmt{displayZeroCommodity=True}+ gainamt sh a = gainColour c (aquantity a) (sh a)++ -- The grand totals row as cell parts (coloured if the flag is true), unless --no-total is in effect.+ mtotalrowparts :: Bool -> Maybe [[WideBuilder]]+ mtotalrowparts c+ | no_total_ ropts = Nothing+ | otherwise = Just $ totalsCellParts c (hrStyles rpt) $ hrTotals rpt++ -- Spreadsheet-shaped tables for the html and fods output: like the+ -- text table, but with single-line cells, an Account column heading,+ -- and a Total: row heading. Parameterised on how to convert plain+ -- text, and a cell's list of (possibly amount) parts, to content.+ spreadsheetWith :: forall content. (T.Text -> content) -> (Bool -> [T.Text] -> content)+ -> [[Ods.Cell Ods.NumLines content]]+ spreadsheetWith plain parts =+ addHeaderBorders (zipWith hcell colclasses (tr "Account" : colheadings))+ : [ zipWith3 bodycell [0..] (lineclasses l)+ (plain (acctcell l) : zipWith parts amountcols (textParts $ linecells False l))+ | l <- displaylines ]+ ++ maybe [] (\tot -> addTotalBorders+ [zipWith3 totalcell [0..] colclasses+ (plain (tr "Total:") : zipWith parts amountcols (textParts tot)) :: [Ods.Cell () content]])+ (mtotalrowparts False)+ where+ -- per-column css classes, so the html cells can be styled+ colclasses = ["account","date","age","units","unitcost","unitprice","totalcost","totalvalue","weight","ugain","ugainpct","rgain","xirr"]+ -- which of the other columns' cell parts are amounts+ amountcols = [False, False, True, True, True, True, True, False, True, False, True, False]+ hcell cls t = plain <$> (headerCell t){Ods.cellClass = Ods.Class cls}+ -- account heading rows get an extra class, so html can style them+ lineclasses HoldingsHeading{} = "account acctheading" : drop 1 colclasses+ lineclasses HoldingsPosition{} = colclasses+ -- body cells are right-aligned, except the first two columns+ -- (Account and Date); headings are unaffected+ bodycell :: Ods.Lines border => Int -> T.Text -> content' -> Ods.Cell border content'+ bodycell i cls t = (Ods.defaultCell t)+ {Ods.cellType = if i < 2 then Ods.TypeString else Ods.TypeMixedAmount+ ,Ods.cellClass = Ods.Class cls}+ totalcell i cls = bodycell i (cls <> " coltotal")+ -- indent tree-mode account names with no-break spaces+ acctcell l = T.replicate (hlIndent l * 2) "\160" <> hlDisplay l++ -- Each commodity amount gets its own span with an "amount" class,+ -- so eg wrapping within amounts can be prevented with css.+ htmltable :: [[Ods.Cell Ods.NumLines Html]]+ htmltable = spreadsheetWith toHtml htmlParts+ htmlParts isamount parts =+ mconcat $ intersperse (toHtml (", "::T.Text)) $+ map (\p -> if isamount then (H.span ! A.class_ "amount") (toHtml p) else toHtml p) $+ filter (not . T.null) parts++ fodstable :: [[Ods.Cell Ods.NumLines T.Text]]+ fodstable = spreadsheetWith id (\_ -> T.intercalate ", " . filter (not . T.null))++ -- Machine-readable records for the csv/tsv/json output, one per+ -- displayed table line. No totals records.+ holdingrecords :: [Holding]+ holdingrecords = map snd rowlines++ csvoutput :: CSV+ csvoutput =+ ["account","commodity","date","age","units","unitcost","unitprice","totalcost","totalvalue","weight","ugain","ugainpct","rgain","xirr"]+ : map holdingCsv holdingrecords
+ Hledger/Cli/Commands/Holdings.txt view
@@ -0,0 +1,300 @@+holdings++Show a report of investment holdings.++Flags:+ -l --flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth-clipped.+ -t --tree list/tree mode: show accounts as a tree. Amounts+ include subaccount amounts.+ --no-elide in tree mode, don't squash boring parent+ accounts; in list mode, also show parent accounts+ (usually zero, hidden without -E)+ --full-names in tree mode, show full account names instead of+ indented leaf names+ --drop=N omit N leading account name parts; in tree mode,+ remove the first N levels+ -S --sort-amount sort by value (or with -B, cost) instead of+ account name, largest first+ -N --no-total omit the final total row+ --change show gains during the report period, or with a+ report interval, during each period (default with a+ start date and no interval)+ --cumulative with a report interval, show gains from the+ report start date to each period's end+ -H --historical show gains since acquisition, ignoring the report+ start date (default with a report interval)+ --round=TYPE how much rounding or padding should be done when+ displaying amounts ?+ none - show original decimal digits+ soft - just add or remove decimal zeros+ to match precision+ hard - round amounts to precision (default)+ all - also round cost amounts to precision+ --chart[=net,SCALE] show a chart: instead of the table (txt), above+ it (html), or as data (csv, tsv, json). net: also+ draw the net total (a line, or marks in text+ charts). SCALE: the amount that fills the chart (eg+ 1000 or 1000 USD; one per commodity), for+ comparable charts.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)+ -O --output-format=FMT select the output format. Supported formats:+ txt, csv, tsv, html, fods, json, svg.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ --view write output to FILE, or to view.FMT in hledger's+ cache directory, and open it in the system's+ default viewer for its format (eg a web browser for+ html). The default format is html.++This command shows your lot-tracked assets (see Lots and capital gains),+and their performance, as of the report end date. An example:++$ hledger holdings -e 2023-04-02+Holdings on 2023-04-01++ || Date Age Units Avg cost Unit price Total cost Total value Weight UGain UGain% RGain XIRR +===========================++===========================================================================================================================+ assets:investments:stocks || 2022-04-07 359d 10 INFY 2.00 ₹ 100.00 ₹ 20.00 ₹ 1,000.00 ₹ 6.4% 980.00 ₹ 4900.0% 5252.4% + assets:investments:stocks || 73 LTTS 4.79 ₹ 200.00 ₹ 350.00 ₹ 14,600.00 ₹ 93.6% 14,250.00 ₹ 4071.4% 140.00 ₹ 4290.2% +---------------------------++---------------------------------------------------------------------------------------------------------------------------+ || 370.00 ₹ 15,600.00 ₹ 100.0% 15,230.00 ₹ 4116.2% 140.00 ₹ 4342.1% ++With --lots, the individual lots are shown:++$ hledger holdings --lots -e 2023-04-02+Holdings on 2023-04-01++ || Date Age Units Unit cost Unit price Total cost Total value Weight UGain UGain% RGain XIRR +=========================================================++============================================================================================================================+ assets:investments:stocks:{2022-04-06, "0002", 10.00 ₹} || 2022-04-06 360d 13 LTTS 10.00 ₹ 200.00 ₹ 130.00 ₹ 2,600.00 ₹ 16.7% 2,470.00 ₹ 1900.0% 140.00 ₹ 3876.1% + assets:investments:stocks:{2022-04-07, 2.00 ₹} || 2022-04-07 359d 10 INFY 2.00 ₹ 100.00 ₹ 20.00 ₹ 1,000.00 ₹ 6.4% 980.00 ₹ 4900.0% 5252.4% + assets:investments:stocks:{2022-05-06, "0002", 11.00 ₹} || 2022-05-06 330d 20 LTTS 11.00 ₹ 200.00 ₹ 220.00 ₹ 4,000.00 ₹ 25.6% 3,780.00 ₹ 1718.2% 5032.7% + assets:investments:stocks:{2022-06-06, "0002", 0.00 ₹} || 2022-06-06 299d 40 LTTS 0 200.00 ₹ 0 8,000.00 ₹ 51.3% 8,000.00 ₹ +---------------------------------------------------------++----------------------------------------------------------------------------------------------------------------------------+ || 370.00 ₹ 15,600.00 ₹ 100.0% 15,230.00 ₹ 4116.2% 140.00 ₹ 4342.1% ++The columns show:++- each holding's acquisition date (or earlier basis date) and age+- the number of units held+- the unit cost basis (Unit cost; or Avg cost, the average unit cost of+ several lots, or for accounts using the AVERAGE method, the pool's+ running average on the report date)+- the unit market price on the report date (Unit price)+- the total cost basis (Total cost)+- the total market value (Total value)+- the percentage of the portfolio's total value (Weight). A holding with+ no market price has no Weight and isn't counted in that total, so the+ others' weights are a little overstated. No weights are shown if the+ holdings are valued in more than one commodity.+- the unrealised gain and gain percent (UGain, UGain%)+- the realised gain from disposals so far (RGain)+- and the annualised rate of return, as of the report end date (XIRR,+ calculated from the holding's dated cashflows and current value, like+ roi's IRR; it includes realised gains). Lots received without a+ transacted cost (eg transferred from another account) count as+ invested at their cost basis on their acquisition date.++Fully disposed commodities and accounts ("closed positions") are not+shown, unless you add -E/--empty. But the totals row's RGain and XIRR+always include them, so those columns may not add up to their totals; a+note below the table then says how many closed positions are not shown.++To see a commodity's performance, a market price should be declared for+it (as of the report end date). Market prices come from P directives or+(with --infer-market-prices) from transacted prices, as usual. Each lot+is valued in its cost commodity. A holding with no market price has no+value or gains; the totals' Total value, UGain, UGain% and XIRR are then+those of the other holdings, and a note below the table names the+excluded ones. (With a report interval, the periods whose totals exclude+some are starred; and a period's gains exclude the holdings with no+market price at either its start or its end, so that they compare the+same holdings.) In a multi-currency portfolio, aggregated values may+contain multiple currencies; use -X COMM for a single-currency view.++With -V, -X COMM or --value (Valuation), holdings are valued in the+default or given valuation commodity instead, and the cost columns are+also converted to it (at the valuation date, so percent gain is+unaffected). Cashflows are not converted, however, so the XIRR column is+left blank for holdings whose cashflows are in a different commodity.+--value=then is not supported, and -B/--cost doesn't change the report's+figures (but see sorting and balance: below).++-S/--sort-amount sorts the lines by their Total value, largest first,+wherever their account. Holdings with no market price come after the+priced ones, sorted by their Total cost. In tree mode, sibling accounts+are sorted likewise by their subtree's totals, as shown on their+headings (an account sorts with the unpriced ones only when none of its+holdings has a market price), and the holdings under each account as in+list mode. With -B, everything is sorted by Total cost. Values in+different commodities are compared by their numbers alone; to compare+them properly, convert them to one commodity with -X COMM.++Amounts are displayed with their commodity's display precision. --round+can select another rounding strategy. The percent columns (Weight,+UGain%, XIRR) are shown with the display style configured for the %+commodity (eg by -c '0.00 %'). With colour enabled, the gain columns+(UGain, UGain%, RGain, XIRR) show gains in green and losses in red.++Query arguments and report flags like --depth, --title etc. work as+usual. balance: and change: query terms test each line (one commodity in+one account). A line has two amounts, its units and its Total value, and+the term's commodity symbol selects which is tested:++- holdings balance:'>100' - holdings of more than 100 units (with no+ symbol, units are tested)+- holdings balance:'>100 AAPL' - holdings of more than 100 AAPL+- holdings balance:'>$1000' - holdings worth more than $1000. Lines with+ no market price have no value, and don't match.+- holdings -B balance:'>$1000' - holdings which cost more than $1000+ (with -B, Total cost is tested instead of Total value)++change: tests the line's change in units during the report period (so it+needs a start date, eg -b), or with the value's commodity symbol, the+value of that change at the valuation date. Unlike in other reports,+-V/-X don't change which amount is tested; to test the value, write its+commodity symbol. But as in other reports, -B tests cost: the line's+Total cost, or the cost of its change, instead of their value. The+totals and tree mode's account headings then cover just the lines shown.+But Weight is still each line's share of all the holdings, including the+hidden ones (so the total Weight shows what share the lines shown make+up).++With -t/--tree, holdings are grouped into account sections: an account+with subaccounts or several commodities becomes a heading row, showing+its subtree's totals computed like the totals row, with its own holdings+beneath it named by their commodity; an account holding one commodity+with no subaccounts is a single combined row; and with --lots, each+holding's lots appear beneath it. Boring parent accounts are squashed+into their child as usual (considering only accounts with holdings),+unless --no-elide is used.++With -O html, an HTML table is produced instead. With -O fods, a+spreadsheet document readable by LibreOffice etc. is produced. With+-O csv or -O tsv, machine-readable output is produced: one record per+holding (or lot, with --lots), with full account names, age in days,+bare units and gain percent numbers, and no totals or tree-mode heading+records. With -O json, a JSON array of holding objects is produced. In+both, the cost and value fields are named unitcost, unitprice, totalcost+and totalvalue.++Gains during a period++Normally the gain columns show each holding's gains since it was+acquired. With a report start date (eg -b, -p, or date:), they show the+gains during the report period instead, and the report title says so (eg+"gains in 2026-11"):++$ hledger holdings -p today # today's gains+$ hledger holdings -p thisyear # this year's gains so far+$ hledger holdings -b 2026-10-01 # gains since a date (until today)+$ hledger holdings -p 2026-q3 # gains in a past period (the report shows holdings at its end)++The units, cost, price, value and Weight columns are unchanged; they+show holdings as of the report end date. But:++- UGain is the change in unrealised gain during the period: the+ unrealised gain at the end, minus that on the day before the start+ date. (Note that selling realises gains: UGain decreases and RGain+ increases.)+- UGain% is that as a percentage of the holding's value on the day+ before the start date, plus the net cost added since.+- RGain is the realised gain from disposals during the period.+- XIRR is the annualised rate of return for the period, counting the+ value on the day before the start date as invested then. For a short+ period this can be a very large number (or blank, when too large to+ calculate); UGain% shows the period's un-annualised gain.++The start date is the first day of the period, so gains are measured+from the previous day's closing prices: -p today shows today's gains+(today's market prices compared with the latest ones before today), and+-b yesterday shows yesterday's and today's. This way consecutive+periods' gains add up, and a month's gains start from the previous+month's last prices, as in a broker's statement. If a market price is+missing at the start or the end, the gains depending on it are left+blank. With -E, holdings fully disposed during the period are shown too.++A report start date before your first acquisition gives the same gains+as no start date. -H/--historical shows the gains since acquisition+despite a start date. (With a report interval, gains are since+acquisition unless you ask otherwise; see below.)++Holdings over time++With a report interval (eg -M, -Q, -Y), holdings shows how your holdings+changed: their totals at the end of each period, each computed as on+that date (eg valued at its market prices). When the holdings are all of+one commodity (eg with a cur: query), their Units, Avg cost and Unit+price are shown too.++The gain columns' period is selected as in other periodic reports+(accumulation mode):++- -H/--historical (the default): gains since acquisition, up to each+ period's end+- --change: gains during each period, as in a single-date report of that+ period (above); these add up: the periods' UGain and RGain sum to+ those of the whole report period+- --cumulative: gains from the report start date up to each period's+ end.++With no end date, the periods continue up to today, even after your last+transaction (since values change with market prices), and the current+period's row shows today's holdings, like the report without an+interval. List/tree mode and --lots make no difference to these totals,+and are ignored. With -O csv, tsv or json, there is one record per+period end, whose unpriced field lists the commodities excluded from its+totals for having no market price.++$ hledger holdings -M -e 2026-04-01+Monthly holdings, 2026-01-31..2026-03-31++ || Units Avg cost Unit price Total cost Total value UGain UGain% RGain XIRR +============++======================================================================================+ 2026-01-31 || 10 AAA $10 $12 $100 $120 $20 20.0% 820.5% + 2026-02-28 || 6 AAA $10 $15 $60 $90 $30 50.0% $20 1566.4% + 2026-03-31 || 6 AAA $10 $9 $60 $54 $-6 -10.0% $20 108.0% ++Holdings charts++With --chart, holdings are shown as a chart: a bar for each holding (or+lot, with --lots), labelled by account and commodity. A holding's bar+shows its cost basis, and its unrealised gain stacked on top, reaching+its market value (which is shown); or if it has lost value, the part of+its cost basis it is still worth, reaching its market value, and the+part lost beyond it (hatched). So the solid part of a bar always reaches+the market value. In graphical charts these are coloured like assets+(blue), revenues (green) and expenses (red). Each bar's unrealised gain+percent is shown after its value, in green if positive or red if+negative. Graphical charts show it instead of the value (which the axis+shows), at the right of the bars, which are horizontal so that there is+room for all of them. With a report interval, each period's gain percent+is above its bar, when there is room for them all. A holding without a+market price is shown as its cost basis, in grey. There is a chart panel+for each commodity the holdings are valued in; use -X COMM to see them+all in one. With a report interval, there is a bar for each period end+instead, showing all the holdings then: their total cost basis, and+their net unrealised gain or loss (with --chart=net, also their value:+in graphical charts, a line joining the periods, like other reports'+totals). With --change or --cumulative, the bars show the gains the+table shows instead: realised gains, and unrealised gains (hatched,+since they are not yet final), with losses below zero, and with+--chart=net, the net gain (in graphical charts, a line joining the+periods, like other reports' totals). As in the table, the periods whose+values and gains exclude holdings with no market price are starred, with+a note below the chart. With SVG output (eg -o holdings.svg, or --view)+it is a graphical chart, and with HTML output it is shown above the+report's table. See Charts for more.++$ hledger holdings --chart -w 70+Holdings on 2024-12-31++USD+█ Cost ▒ Unrealised gain ╱ Unrealised loss ▓ No market price++assets:broker AAPL 2,500.00 USD +66.7% █████████████████▒▒▒▒▒▒▒▒▒▒▒+assets:broker NEW ▓+assets:broker XYZ 450.00 USD -40.0% █████╱╱╱
+ Hledger/Cli/Commands/Import.hs view
@@ -0,0 +1,143 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE NamedFieldPuns #-}++module Hledger.Cli.Commands.Import (+ importmode+ ,importcmd+)+where++import Control.Monad+import Data.List+import Data.Text.IO qualified as T+import System.Console.CmdArgs.Explicit+import Text.Printf++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Commands.Add (journalAddTransaction, journalFileTextAfterAppends)+import Hledger.Cli.Utils (journalCheckChange)+import Hledger.Cli.Commands.Get (getcmd)+import Hledger.Cli.Commands.Print (layoutFlag, layoutFromRawOpts)+import System.Directory (doesDirectoryExist, listDirectory)+import System.IO (stderr)+import System.FilePath (takeDirectory, takeFileName, (</>))++importmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Import.txt")+ [flagNone ["get","g"] (setboolopt "get") "fetch new data first by running the get command"+ ,flagNone ["catchup"] (setboolopt "catchup") "just mark all transactions as already imported"+ ,flagNone ["dry-run"] (setboolopt "dry-run") "just show the transactions to be imported"+ ,layoutFlag+ ]+ cligeneralflagsgroups1+ hiddenflags+ ([], Just $ argsFlag "[-f JOURNALFILE] [DATAFILES]")++importcmd opts@CliOpts{rawopts_=rawopts,inputopts_=iopts} j = do+ -- With -g/--get, run the get command first to fetch new data before importing.+ when (boolopt "get" rawopts) $ getcmd opts j+ -- XXX could be helpful to show the last-seen date, and number of old transactions, too+ let+ argfiles = listofstringopt "args" rawopts+ rulesdir = takeDirectory (journalFilePath j) </> rulesDirName+ catchup = boolopt "catchup" rawopts+ dryRun = boolopt "dry-run" rawopts+ postinglayout = layoutFromRawOpts rawopts+ combinedStyles = + let+ maybeInputStyles = commodity_styles_ . balancingopts_ $ iopts+ inferredStyles = journalCommodityStyles j+ in+ case maybeInputStyles of+ Nothing -> Just inferredStyles+ Just inputStyles -> Just $ inputStyles <> inferredStyles++ -- Note: inputOptsSetJournalDir is needed here because this is a secondary+ -- read after the main journal has been loaded; without it the CSV rules+ -- reader would fall back to the rules file's directory for source/archive+ -- lookups instead of the main journal's data/ directory.+ iopts' = inputOptsSetJournalDir j $ iopts{+ new_=True, -- read only new transactions since last time+ new_save_=False, -- defer saving .latest files until the end+ strict_=False, -- defer strict checks until the end+ _importing=True, -- let the CSV rules reader do its import-specific things (oldest source file, archiving)+ _dryrun=dryRun, -- but with --dry-run, archive nothing, remove no data file, and run no data generating command+ balancingopts_=defbalancingopts{commodity_styles_= combinedStyles} -- use amount styles from both when balancing txns+ }++ inputfiles <- case argfiles of+ [] -> discoverRulesFiles rulesdir+ fs -> return fs+ let inputstr = intercalate ", " $ map (quoteIfNeeded.takeFileName) inputfiles++ case inputfiles of+ [] -> error' $ -- PARTIAL:+ "please specify one or more data files to import from,\n"+ ++ "or add .rules files in a rules/ directory next to the journal."+ fs -> do+ enewjandlatestdatesforfiles <- runExceptT $ readJournalFilesAndLatestDates iopts' fs+ case enewjandlatestdatesforfiles of+ Left err -> error' err+ Right (newj, latestdatesforfiles) ->+ case sortOn tdate $ jtxns newj of+ [] -> hPrintf stderr "no new transactions found in %s\n" inputstr++ newts | catchup ->+ if dryRun+ then hPrintf stderr "would skip %d new transactions (dry run)\n\n" (length newts)+ else do+ hPrintf stderr "marked %s as caught up, skipping %d transactions\n\n" inputstr (length newts)+ saveLatestDatesForFiles latestdatesforfiles++ newts -> do+ if dryRun+ then do+ -- show txns to be imported+ hPrintf stderr "would import %d new transactions from %s:\n\n" (length newts) inputstr+ mapM_ (T.putStr . showTransactionWithLayout postinglayout) newts++ -- then check that the journal would be readable with them added+ checkImport++ else do+ -- first check that the journal would be readable with them added+ checkImport++ -- then append the transactions to the main journal file.+ -- XXX This writes unix line endings (\n), some at least,+ -- even if the file uses dos line endings (\r\n), which could leave+ -- mixed line endings in the file. See also writeFileWithBackupIfChanged.+ foldM_ (`journalAddTransaction` opts) j newts -- gets forced somehow.. (how ?)++ hPrintf stderr "imported %d new transactions from %s to %s\n" (length newts) inputstr (journalFilePath j)++ -- and if we got this far, update each file's .latest file+ saveLatestDatesForFiles latestdatesforfiles++ where+ -- Check that the journal would still be readable with the new transactions+ -- appended to the main file, as the next read would check it, with these options+ -- (balancing, balance assertions, lots, strict checks if enabled..). Or stop with its error.+ -- (journalAddTransaction appends them with appendToJournalFileOrStdout.)+ checkImport = do+ let f = journalFilePath j+ newtxt <- journalFileTextAfterAppends f $ map (showTransactionWithLayout postinglayout) newts+ runExceptT (journalCheckChange opts f newtxt) >>= either error' (const $ return ())++-- | List the .rules files in the given directory, in alphabetical order,+-- skipping files whose name begins with '.' (hidden) or '_'+-- (disabled, or shared rules included by others).+-- Returns an empty list if the directory does not exist.+discoverRulesFiles :: FilePath -> IO [FilePath]+discoverRulesFiles dir = do+ exists <- doesDirectoryExist dir+ if not exists+ then return []+ else do+ names <- listDirectory dir+ return $ sort [ dir </> n | n <- names+ , ".rules" `isSuffixOf` n+ , not (any (`isPrefixOf` n) [".", "_"]) ]
+ Hledger/Cli/Commands/Import.txt view
@@ -0,0 +1,296 @@+import++Import new transactions from one or more data files to the main journal.+Or with no arguments, import from the rules files in rules/.++Flags:+ -g --get fetch new data first by running the get command+ --catchup just mark all transactions as already imported+ --dry-run just show the transactions to be imported+ --layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 - right-align amounts, as in hledger 1+ COL - align decimal marks at column COL+ (default: 53)++This command detects new transactions in one or more data files+specified as arguments, and appends them to the main journal.++You can import from any input file format hledger supports, but+CSV/SSV/TSV files, downloaded from financial institutions, are the most+common import source.++The import destination is the default journal file, or another specified+in the usual way with $LEDGER_FILE or -f/--file. It should be in journal+format.++Before writing anything, import checks that the journal will still be+readable with the new transactions added, as the next read with the same+options will check it (eg balance assertions must pass, lots must be+valid, and with --strict, the strict checks must pass). If not, it shows+the error and imports nothing (and updates no .latest files). A dry run+does this check too.++Examples:++$ hledger import bank1-checking.csv bank1-savings.csv++$ hledger import *.csv++Default import sources++If import is run with no file arguments, it looks in the journal's+rules/ directory (next to the main journal file) and imports from every+.rules file found there, in alphabetical order. Files whose name begins+with . or _ are skipped: the _ prefix is for rules files that are either+disabled, or shared/common rules included by other rules files and not+meant to be read directly.++So a typical setup might be:++~/finance/2026.journal+~/finance/rules/bank1-checking.rules+~/finance/rules/bank1-savings.rules+~/finance/rules/_common.rules # included by others, not read directly+~/finance/rules/_brokerage.rules # disabled++and hledger import reads bank1-checking.rules then bank1-savings.rules.++If the rules/ directory does not exist or contains no usable .rules+files, import reports an error.++Fetching new data first++With -g/--get, import runs the get command first, which runs your+data/getdata and prices/getprices scripts (if any) to download new+transaction and price data. The import then proceeds normally, with the+new transaction data (if any) readable by your rules files' source+rules.++Import dry run++It's useful to preview the import by running first with --dry-run, to+sanity check the range of dates being imported, and to check the effect+of your conversion rules if converting from CSV. Eg:++$ hledger import bank.csv --dry-run++A dry run archives no data files and updates no .latest files. With -g,+the get command does a dry run too. But source rules' data cleaning and+data generating commands do run, since their output is needed for the+preview; so these should be safe to repeat.++The dry run output is valid journal format, so hledger can re-parse it.+If the output is large, you could show just the uncategorised+transactions like so:++$ hledger import --dry-run bank.csv | hledger -f- -I print unknown++You could also run this repeatedly to see the effect of edits to your+conversion rules:++$ watchexec -- "hledger import --dry-run bank.csv | hledger -f- -I print unknown"++Once the conversion and dates look good enough to import to your+journal, perhaps with some manual fixups to follow, you would do the+actual import:++$ hledger import bank.csv++Overlap detection++Reading CSV files is built in to hledger, and not specific to import; so+you could also import by doing hledger -f bank.csv print >>$LEDGER_FILE.++But import is easier and provides some advantages. The main one is that+it avoids re-importing transactions it has seen on previous runs. This+means you don't have to worry about overlapping data in successive+downloads of your bank CSV; just download and import as often as you+like, and only the new transactions will be imported each time.++We don't call this "deduplication", as it's generally not possible to+reliably detect duplicates in bank CSV. Instead, import remembers the+latest date processed previously in each CSV file (saving it in a hidden+file), and skips any records prior to that date. This works well for+most real-world CSV, where:++1. the data file name is stable (does not change) across imports+2. the item dates are stable across imports+3. the order of same-date items is stable across imports+4. the newest items have the newest dates++(Occasional violations of 2-4 are often harmless; you can reduce the+chance of disruption by downloading and importing more often.)++Overlap detection is automatic, and shouldn't require much attention+from you, except perhaps at first import (see below). But here's how it+works:++- For each FILE being imported from:++ 1. hledger reads a file named .latest.FILE file in the same+ directory, if any. This file contains the latest record date+ previously imported from FILE, in YYYY-MM-DD format. If multiple+ records with that date were imported, the date is repeated on N+ lines.++ 2. hledger reads records from FILE. If a latest date was found in+ step 1, any records before that date, and the first N records on+ that date, are skipped.++- After a successful import from all FILEs, without error and without+ --dry-run, hledger updates each FILE's .latest.FILE for next time.++If this goes wrong, it's relatively easy to repair:++- You'll notice it before import when you preview with import --dry-run.+- Or after import when you try to reconcile your hledger account+ balances with your bank.+- hledger print -f FILE.csv will show all recently downloaded+ transactions. Compare these with your journal. Copy/paste if needed.+- Update your conversion rules and print again, if needed.+- You can manually update or remove the .latest file, or use+ import --catchup FILE.+- Download and import more often, eg twice a week, at least while you+ are learning. It's easier to review and troubleshoot when there are+ fewer transactions.++First import++The first time you import from a file, when no corresponding .latest+file has been created yet, all of the records will be imported.++But perhaps you have been entering the data manually, so you know that+all of these transactions are already recorded in the journal. In this+case you can run hledger import --catchup once. This will create a+.latest file containing the latest CSV record date, so that none of+those records will be re-imported.++Or, if you know that some but not all of the transactions are in the+journal, you can create the .latest file yourself. Eg, let's say you+previously recorded foobank transactions up to 2024-10-31 in the+journal. Then in the directory where you'll be saving foobank.csv, you+would create a .latest.foobank.csv file containing++2024-10-31++Or if you had three foobank transactions recorded with that date, you+would repeat the date that many times:++2024-10-31+2024-10-31+2024-10-31++Then hledger import foobank.csv [--dry-run] will import only the newer+records.++Importing balance assignments++Journal entries added by import will have all posting amounts made+explicit (like print -x).++This means that any balance assignments in the imported entries would+need to be evaluated. But this generally isn't possible, as the main+file's account balances are not visible during import. So try to avoid+generating balance assignments with your CSV rules, or importing from a+journal that contains balance assignments. (Balance assignments are best+avoided anyway.)++But if you must use them, eg because your CSV includes only balances:+you can import with print, which leaves implicit amounts implicit.+(print can also do overlap detection like import, with the --new flag):++$ hledger print --new -f bank.csv >> $LEDGER_FILE++(If you think import should preserve implicit balances, please test that+and send a pull request.)++Import and commodity styles++Amounts in entries added by import will be formatted according to the+journal's canonical commodity styles, as declared by commodity+directives or inferred from the journal's amounts.++Related: CSV > Amount decimal places.++Import archiving++When importing from a CSV rules file (hledger import bank.rules), you+can use the archive rule to enable automatic archiving of the data file.++After a successful import, the data file specified by source will be+moved (or data generated by a command will be saved) to an archive+directory. This can be useful for troubleshooting, detecting variations+in your banks' CSV data, regenerating entries with improved rules, etc.++The archive directory is data/archive/, next to the main journal file,+auto-created. The archive file name will be similar to the rules file,+with a date added: the original data file's modification date, or+today's date if the data was command-generated.++The archive rule also causes import to handle source glob patterns+differently: when there are multiple matched files, it will pick the+oldest, not the newest.++Import special cases++Multiple journals in the same directory++You might want to keep each journal you are importing to in its own+directory. That way, each will have its own rules/, data/, and+data/archive/ directories (if those are used).++Otherwise, imports to the same-directory journals will potentially use+the same rules/, data/ and data/archive/ directories (depending on+commands and rules configuration). This is not necessarily a problem; it+might even be desirable in some cases. But see below:++Import configurations to avoid++A few unusual workflows which you should generally avoid:++- Don't import from one input file to different journals. The imports'+ overlap detection would overwrite the same .latest.FILE state file.+ (In effect, the journals would compete for the new records.)++- Don't import from multiple data files on the same day, reusing the+ same rules file for all, with archive enabled. The archived file names+ in data/archive/ would clash, causing some archives to be overwritten.++- Don't do argument-less hledger import to more than one journal in the+ same directory. That would read from the same files in rules/,+ potentially disrupting both overlap detection and archiving.++Deduplication++Here are two kinds of "deduplication" which import does not handle (and+should not, because these can happen legitimately in financial data):++- Two or more of the new CSV records are identical, and generate+ identical new journal entries.+- A new CSV record generates a journal entry identical to one(s) already+ in the journal.++Varying file name++If you have a download whose file name varies, you could rename it to a+fixed name after each download. Or you could use a CSV source rule with+a suitable glob pattern, and import from the .rules file.++Multiple versions++Say you download bank.csv, import it, but forget to delete it from your+downloads folder. The next time you download it, your web browser will+save it as (eg) bank (2).csv. The source rule's glob patterns are for+just this situation: instead of specifying source bank.csv, specify+source bank*.csv. Then hledger -f bank.rules CMD or+hledger import bank.rules will automatically pick the newest matched+file (bank (2).csv).++Alternately, what if you download, but forget to import or delete, then+download again ? Now each of bank.csv and bank (2).csv might contain+data that's not in the other, and not in your journal. In this case,+it's best to import each of them in turn, oldest first (otherwise,+overlap detection could cause new records to be skipped). Enabling+import archiving ensures this. Then+hledger import bank.rules; hledger import bank.rules will import and+archive first bank.csv, then bank (2).csv.
+ Hledger/Cli/Commands/Incomestatement.hs view
@@ -0,0 +1,81 @@+{-# LANGUAGE QuasiQuotes #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE OverloadedStrings #-}+{-|++The @incomestatement@ command prints a simple income statement (profit & loss report).++-}++module Hledger.Cli.Commands.Incomestatement (+ incomestatementmode+ ,incomestatement+ ,incomestatementSpec+) where++import System.Console.CmdArgs.Explicit++import Hledger.Utils.I18n (i18n)+import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.CompoundBalanceCommand++incomestatementSpec :: CompoundBalanceCommandSpec+incomestatementSpec = CompoundBalanceCommandSpec {+ cbcdoc = $(embedFileRelative "Hledger/Cli/Commands/Incomestatement.txt"),+ -- TRANSLATORS: the report title, with its reporting interval if any. Each is a+ -- whole phrase, so put the words in the order and form your language needs.+ cbctitle = \case+ NoInterval -> i18n "Income Statement"+ Days 1 -> i18n "Daily Income Statement"+ Weeks 1 -> i18n "Weekly Income Statement"+ Weeks 2 -> i18n "Biweekly Income Statement"+ Months 1 -> i18n "Monthly Income Statement"+ Months 2 -> i18n "Bimonthly Income Statement"+ Months 3 -> i18n "Quarterly Income Statement"+ Months 6 -> i18n "Half-yearly Income Statement"+ Years 1 -> i18n "Yearly Income Statement"+ Years 2 -> i18n "Biennial Income Statement"+ _ -> i18n "Periodic Income Statement",+ cbcqueries = [+ CBCSubreportSpec{+ cbcsubreporttitle=i18n "Revenues"+ ,cbcsubreportquery=Type [Revenue]+ ,cbcsubreportoptions=(\ropts -> ropts{normalbalance_=Just NormallyNegative})+ ,cbcsubreporttransform=fmap maNegate+ ,cbcsubreportincreasestotal=True+ }+ ,CBCSubreportSpec{+ cbcsubreporttitle=i18n "Expenses"+ ,cbcsubreportquery=Type [Expense]+ ,cbcsubreportoptions=(\ropts -> ropts{normalbalance_=Just NormallyPositive})+ ,cbcsubreporttransform=id+ ,cbcsubreportincreasestotal=False+ }+ ],+ cbcaccum = PerPeriod+}++incomestatementmode :: Mode RawOpts+incomestatementmode = compoundBalanceCommandMode incomestatementSpec++incomestatement :: CliOpts -> Journal -> IO ()+incomestatement = compoundBalanceCommand incomestatementSpec+{- +Summary of code flow, 2021-11:++incomestatement+ compoundBalanceCommand+ compoundBalanceReport+ compoundBalanceReportWith+ colps = getPostingsByColumn+ startps = startingPostings+ generateSubreport+ startbals = startingBalances (startps restricted to this subreport)+ generateMultiBalanceReport startbals (colps restricted to this subreport)+ matrix = calculateReportMatrix startbals colps+ displaynames = displayedAccounts+ buildReportRows displaynames matrix+ -}+
+ Hledger/Cli/Commands/Incomestatement.txt view
@@ -0,0 +1,122 @@+incomestatement++(is)++Show revenue inflows and expense outflows during the report period.+Amounts are shown with normal positive sign, as in conventional+financial statements.++Flags:+ --sum calculation mode: show sum of posting amounts+ (default)+ --valuechange calculation mode: show total change of value+ of period-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ --gain calculation mode: show unrealised capital+ gain/loss (historical balance value minus cost+ basis)+ --count calculation mode: show the count of postings+ --change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports) (default)+ --cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. -b/--begin) to+ column end+ -H --historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date)+ -l --flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth-clipped.+ -t --tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ --drop=N in list mode, omit N leading account name+ parts+ --declared include non-parent declared accounts (best+ used with -E)+ -A --average show a row average column (in multicolumn+ reports)+ -T --row-total show a row total column (in multicolumn+ reports)+ --summary-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ -N --no-total omit the final total row+ --no-elide in tree mode, don't squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without -E)+ --full-names in tree mode, show full account names instead+ of indented leaf names+ --format=FORMATSTR use this custom line format (in simple+ reports)+ -S --sort-amount sort by amount instead of account code/name+ -% --percent express values in percentage of each column's+ total+ --layout=ARG how to show multi-commodity amounts:+ 'wide[,WIDTH]': all commodities on one line+ 'tall' : each commodity on a new line+ 'bare' : bare numbers, symbols in a+ column+ --base-url=URLPREFIX in html output, generate hyperlinks to+ hledger-web, with this prefix. (Usually the base+ url shown by hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ -o --output-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ --view write output to FILE, or to view.FMT in+ hledger's cache directory, and open it in the+ system's default viewer for its format (eg a web+ browser for html). The default format is html.+ --chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: diverging (sections above and below zero;+ the default) or grouped (sections side by side).+ net: also draw the net total (a line, or marks+ in text charts). SCALE: the amount that fills+ the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)++This command displays an income statement, showing revenues and expenses+during one or more periods.++It shows accounts declared with the Revenue or Expense type (see account+types). Or if no such accounts are declared, it shows top-level accounts+named revenue or income or expense (case insensitive, plurals allowed)+and their subaccounts.++Example:++$ hledger incomestatement+Income Statement 2008++ || 2008 +===================++======+ Revenues || +-------------------++------+ income:gifts || $1 + income:salary || $1 +-------------------++------+ || $2 +===================++======+ Expenses || +-------------------++------+ expenses:food || $1 + expenses:supplies || $1 +-------------------++------+ || $2 +===================++======+ Net: || 0 ++This command is a higher-level variant of the balance command, and+supports many of that command's features, such as multi-period reports.+It is similar to hledger balance '(revenues|income)' expenses, but with+smarter account detection, and revenues/income displayed with their sign+flipped.++This command also supports the output destination and output format+options The output formats supported are txt, csv, tsv, html, json, and+svg (a chart; see Balance charts).
+ Hledger/Cli/Commands/Init.hs view
@@ -0,0 +1,331 @@+{-|++The @init@ command writes starter files for a new hledger setup,+or adds missing ones to an existing setup.+The files are example file layouts, kept in hledger/embeddedfiles/file-layouts/+(also linked from examples/file-layouts/), and embedded in the executable.+Existing files are never changed.++-}++{-# LANGUAGE LambdaCase #-}+{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE TupleSections #-}++module Hledger.Cli.Commands.Init (+ initmode+ ,initcmd+ ,tests_Init+) where++import Control.Exception (IOException, try)+import Control.Monad (forM, forM_, unless, when)+import Data.ByteString (ByteString)+import Data.ByteString qualified as B+import Data.ByteString.Char8 qualified as B8+import Data.Char (toLower)+import Data.Containers.ListUtils (nubOrd)+import Data.List (find, intercalate, isInfixOf, stripPrefix)+import Data.Map.Strict qualified as M+import Data.Maybe (maybeToList)+import Data.Time.Calendar (toGregorian)+import Safe (maximumDef)+import System.Console.CmdArgs.Explicit+import System.Directory+import System.FilePath+import System.Info (os)++import Hledger+import Hledger.Read.JournalReader qualified as JournalReader+import Hledger.Cli.CliOptions+++initmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Init.txt")+ [flagReq ["layout"] (\s opts -> Right $ setopt "layout" s opts) "LAYOUT"+ ("which file layout to write: " <> intercalate ", " (map lName layouts) <> " (default: " <> lName defaultLayout <> ")")+ ,flagNone ["dry-run"] (setboolopt "dry-run") "just show the files that would be created"+ ]+ [generalflagsgroup3]+ hiddenflags+ ([], Just $ argsFlag "[DIR|FILE.journal]")++-- | A file in a layout: its path relative to the layout's root, whether it should be executable, and its content.+data LayoutFile = LayoutFile+ { lfPath :: FilePath+ , lfExecutable :: Bool+ , lfContent :: ByteString+ }++-- | A set of files which can be written by init.+data FileLayout = FileLayout+ { lName :: String+ , lDescription :: String+ , lFiles :: [LayoutFile] -- ^ in the order they are reported+ , lMainJournal :: FilePath -- ^ the journal to use day to day, relative to the layout's root+ , lCombinedJournal :: Maybe FilePath -- ^ a journal combining several main journals, if any+ }++-- | The built-in layouts.+-- Their files are in embeddedfiles/file-layouts/LAYOUT/; keep these definitions synced with those+-- (and with package.yaml's extra-source-files). The init functional tests compare the results with those directories.+layouts :: [FileLayout]+layouts = [simpleLayout, defaultLayout, yearsLayout]++simpleLayout, defaultLayout, yearsLayout :: FileLayout+simpleLayout = FileLayout "simple" "one journal file, with optional declarations commented out"+ [simpleMainJournal] "main.journal" Nothing+defaultLayout = FileLayout "default" "a main journal, declaration files, and directories for data, prices and rules"+ defaultFiles "main.journal" Nothing+yearsLayout = FileLayout "years" "like default, but with a journal for each year, and all.journal to combine them"+ ([ LayoutFile "2026.journal" False $(embedFileRelativeBytes "embeddedfiles/file-layouts/years/2026.journal")+ , LayoutFile "all.journal" False $(embedFileRelativeBytes "embeddedfiles/file-layouts/years/all.journal")+ ] ++ filter ((/= "main.journal") . lfPath) defaultFiles)+ "2026.journal" (Just "all.journal")++-- | Find a built-in layout by name.+lookupLayout :: String -> Maybe FileLayout+lookupLayout name = find ((== name) . lName) layouts++-- | The year used in layout file names and content, which init replaces with the current year.+layoutYear :: String+layoutYear = "2026"++-- | Adapt a layout to the given year: in files whose name contains 'layoutYear',+-- replace it with this year, in their name and their content.+layoutForYear :: Integer -> FileLayout -> FileLayout+layoutForYear y l = l{lFiles = map forYear $ lFiles l, lMainJournal = forYearPath $ lMainJournal l}+ where+ year = show y+ hasYear = (layoutYear `isInfixOf`) . takeFileName+ forYearPath p = if hasYear p then replaceString layoutYear year p else p+ forYear f+ | hasYear (lfPath f) = f{lfPath = forYearPath $ lfPath f, lfContent = replaceBytes (B8.pack layoutYear) (B8.pack year) $ lfContent f}+ | otherwise = f++-- | Replace all occurrences of a non-empty string (an empty one changes nothing).+replaceString :: String -> String -> String -> String+replaceString old new = go+ where+ go s | null old = s+ | Just rest <- stripPrefix old s = new ++ go rest+ | c:cs <- s = c : go cs+ | otherwise = []++-- | Replace all occurrences of a non-empty byte string (an empty one changes nothing).+replaceBytes :: ByteString -> ByteString -> ByteString -> ByteString+replaceBytes old new s+ | B.null old = s+ | otherwise = case B.breakSubstring old s of+ (before, rest) | B.null rest -> before+ | otherwise -> before <> new <> replaceBytes old new (B.drop (B.length old) rest)++-- | The simple layout's only file, which is also written to a journal file path argument.+simpleMainJournal :: LayoutFile+simpleMainJournal = LayoutFile "main.journal" False $(embedFileRelativeBytes "embeddedfiles/file-layouts/simple/main.journal")++-- | The default layout's files.+defaultFiles :: [LayoutFile]+defaultFiles =+ [ LayoutFile "main.journal" False $(embedFileRelativeBytes "embeddedfiles/file-layouts/default/main.journal")+ , LayoutFile "accounts.journal" False $(embedFileRelativeBytes "embeddedfiles/file-layouts/default/accounts.journal")+ , LayoutFile "commodities.journal" False $(embedFileRelativeBytes "embeddedfiles/file-layouts/default/commodities.journal")+ , LayoutFile "payees.journal" False $(embedFileRelativeBytes "embeddedfiles/file-layouts/default/payees.journal")+ , LayoutFile ("data" </> "getdata") True $(embedFileRelativeBytes "embeddedfiles/file-layouts/default/data/getdata")+ , LayoutFile ("data" </> "bankofireland-checking.csv") False $(embedFileRelativeBytes "embeddedfiles/file-layouts/default/data/bankofireland-checking.csv")+ , LayoutFile ("data" </> "archive" </> "README.md") False $(embedFileRelativeBytes "embeddedfiles/file-layouts/default/data/archive/README.md")+ , LayoutFile ("prices" </> "getprices") True $(embedFileRelativeBytes "embeddedfiles/file-layouts/default/prices/getprices")+ , LayoutFile ("rules" </> "bankofireland-checking.csv.rules") False $(embedFileRelativeBytes "embeddedfiles/file-layouts/default/rules/bankofireland-checking.csv.rules")+ ]++-- | Where to write: a directory (gets a whole layout) or a journal file path (gets the simple layout's main journal).+data InitTarget = InitDir FilePath | InitFile FilePath+ deriving (Eq, Show)++-- | What is at a path.+data PathState = Absent | IsDir | IsOther+ deriving (Eq, Show)++-- | What to do with one file.+data InitAction = Create FilePath LayoutFile | Skip FilePath++initcmd :: CliOpts -> Journal -> IO ()+initcmd CliOpts{rawopts_=rawopts} _ = do+ let dryRun = boolopt "dry-run" rawopts+ target <- case listofstringopt "args" rawopts of+ [] -> return $ InitDir "."+ [arg] -> do+ when (os == "mingw32" && isWindowsUnsafeDotPath arg) $+ error' $ "Part of file path " <> show arg <> " ends with a dot, which is unsafe on Windows; please use a different path."+ isdir <- doesDirectoryExist arg+ either usageError return $ classifyInitArg isdir arg+ _ -> usageError "init takes at most one argument, a directory or a journal file path."+ mlayout <- forM (maybestringopt "layout" rawopts) $ \name ->+ maybe (usageError $ unknownLayoutMsg name) return $ lookupLayout name+ (y, _, _) <- toGregorian <$> getCurrentDay+ flayout <- either usageError (return . layoutForYear y) $ chooseLayout mlayout target+ let+ dests = destinations flayout target+ paths = nubOrd $ map fst dests ++ concatMap (ancestors . fst) dests+ states <- M.fromList <$> mapM (\p -> (p,) <$> pathState p) paths+ actions <- either error' return $ planInit (\p -> M.findWithDefault Absent p states) dests+ forM_ actions $ \case+ Create p f+ | dryRun -> putStrLn $ "would create " <> p+ | otherwise -> writeLayoutFile p f >> putStrLn ("created " <> p)+ Skip p+ | dryRun -> putStrLn $ "would skip " <> p <> " (exists)"+ | otherwise -> warnIO $ "skipped " <> p <> ", it already exists"+ unless dryRun $ case target of+ InitFile f -> showNextSteps f Nothing+ InitDir d -> showNextSteps (normalise $ d </> lMainJournal flayout) ((normalise . (d </>)) <$> lCombinedJournal flayout)++-- | A usage error message for an unknown layout name, listing the layouts.+unknownLayoutMsg :: String -> String+unknownLayoutMsg name = unlines $+ ("There is no " <> show name <> " layout. The layouts are:")+ : [" " <> lName l <> replicate (width - length (lName l)) ' ' <> " " <> lDescription l | l <- layouts]+ where width = maximumDef 0 $ map (length . lName) layouts++-- | Choose the layout to write, given the --layout option's layout if any, and the target.+-- A journal file target can only have the simple layout.+chooseLayout :: Maybe FileLayout -> InitTarget -> Either String FileLayout+chooseLayout mlayout target = case (target, mlayout) of+ (InitDir _, Nothing) -> Right defaultLayout+ (InitDir _, Just l) -> Right l+ (InitFile _, Nothing) -> Right simpleLayout+ (InitFile f, Just l)+ | lName l == lName simpleLayout -> Right l+ | otherwise -> Left $ "The " <> lName l <> " layout needs a directory, not a journal file (" <> show f <> ")."++-- | Decide what kind of path the command argument is, given whether it is an existing directory.+-- A path ending with a path separator is a directory; a path with a journal file extension is a journal file;+-- a path with any other extension is an error (most likely a file name meant for some other purpose);+-- anything else is a directory.+classifyInitArg :: Bool -> FilePath -> Either String InitTarget+classifyInitArg isdir arg+ | isdir || hasTrailingPathSeparator arg = Right $ InitDir arg+ | ext `elem` journalExtensions = Right $ InitFile arg+ | not $ null ext = Left $ unlines+ [ show arg <> " has a ." <> ext <> " extension; init writes journal files or directories."+ , "For a journal file, use a " <> extensions <> " extension; for a directory with this name, add a trailing " <> [pathSeparator] <> "."+ ]+ | otherwise = Right $ InitDir arg+ where+ ext = map toLower $ drop 1 $ takeExtension arg+ journalExtensions = rExtensions (JournalReader.reader :: Reader IO)+ extensions = intercalate ", " $ map ('.':) journalExtensions++-- | The files to write, at their destination paths.+-- A journal file target gets the layout's main journal content.+destinations :: FileLayout -> InitTarget -> [(FilePath, LayoutFile)]+destinations l (InitFile f) = [(normalise f, mf) | mf <- take 1 $ filter ((== lMainJournal l) . lfPath) $ lFiles l]+destinations l (InitDir d) = [(normalise $ d </> lfPath f, f) | f <- lFiles l]++-- | All the directories above a path, nearest first, as far as the path reaches+-- (eg "a/b/c" -> ["a/b", "a", "."], "/a/b" -> ["/a", "/"]).+ancestors :: FilePath -> [FilePath]+ancestors = go . takeDirectory+ where+ go d = d : let d' = takeDirectory d in if d' == d then [] else go d'++-- | Decide what to do with each file, given what is at each destination path and the directories above it.+-- If something other than a directory is where a directory is needed, give an error.+-- Otherwise, files whose path is free are created and the rest are skipped.+planInit :: (FilePath -> PathState) -> [(FilePath, LayoutFile)] -> Either String [InitAction]+planInit stateOf dests =+ case filter ((== IsOther) . stateOf) $ nubOrd $ concatMap (ancestors . fst) dests of+ d:_ -> Left $ show d <> " needs to be a directory, but a file is there. Nothing was written."+ [] -> Right [if stateOf p == Absent then Create p f else Skip p | (p, f) <- dests]++-- | Check what is at a path. A symbolic link counts as present even when its target does not exist.+pathState :: FilePath -> IO PathState+pathState p = do+ isdir <- doesDirectoryExist p+ exists <- doesPathExist p+ islink <- either (const False) id <$> (try (pathIsSymbolicLink p) :: IO (Either IOException Bool))+ return $ if | isdir -> IsDir+ | exists || islink -> IsOther+ | otherwise -> Absent++-- | Write a layout file at the given path, creating directories as needed.+-- The content is written as is, with no line ending conversion.+writeLayoutFile :: FilePath -> LayoutFile -> IO ()+writeLayoutFile p f = do+ createDirectoryIfMissing True $ takeDirectory p+ B.writeFile p $ lfContent f+ when (lfExecutable f) $ getPermissions p >>= setPermissions p . setOwnerExecutable True++-- | Suggest some next steps for using this main journal file, and the combining journal if any.+-- The commands use -f unless LEDGER_FILE already selects the main journal.+showNextSteps :: FilePath -> Maybe FilePath -> IO ()+showNextSteps mainj mcombinedj = do+ absj <- makeAbsolute mainj+ isdefault <- defaultJournalPathSafely >>= \case+ Left _ -> return False+ Right f -> either (const False) id <$>+ (try (equalFilePath <$> canonicalizePath f <*> canonicalizePath absj) :: IO (Either IOException Bool))+ let+ fopt = if isdefault then "" else " -f " <> shellQuoteIfNeeded mainj+ commands =+ [ ("hledger" <> fopt <> " check", "check the journal")+ , ("hledger" <> fopt <> " bs", "show a balance sheet")+ , ("hledger" <> fopt <> " is", "show an income statement")+ , ("hledger" <> fopt <> " add", "add transactions")+ ] +++ [ ("hledger -f " <> shellQuoteIfNeeded cj <> " bs", "show a balance sheet using all years' journals") | cj <- maybeToList mcombinedj ] +++ [ ("hledger setup", "check/show more details about your hledger installation")+ ]+ width = maximumDef 0 $ map (length . fst) commands+ putStr $ unlines $+ [ ""+ , "Next steps:"+ ] +++ [ " " <> c <> replicate (width - length c) ' ' <> " # " <> desc | (c, desc) <- commands ] +++ [ l | not isdefault, l <-+ [ "To make this your default journal, so -f is not needed, set LEDGER_FILE to"+ , " " <> absj+ , "(see https://hledger.org/hledger.html#setting-ledger_file)."+ ]]++tests_Init = testGroup "Init" [+ testCase "classifyInitArg" $ do+ classifyInitArg True "x.journal" @?= Right (InitDir "x.journal")+ classifyInitArg False "x.journal" @?= Right (InitFile "x.journal")+ classifyInitArg False "a/x.J" @?= Right (InitFile "a/x.J")+ classifyInitArg False "a/x.j/" @?= Right (InitDir "a/x.j/")+ classifyInitArg False "finance" @?= Right (InitDir "finance")+ either (const True) (const False) (classifyInitArg False "x.csv") @?= True+ ,testCase "ancestors" $ do+ ancestors ("a" </> "b" </> "c") @?= ["a" </> "b", "a", "."]+ ancestors "c" @?= ["."]+ ,testCase "chooseLayout" $ do+ fmap lName (chooseLayout Nothing (InitDir "d")) @?= Right "default"+ fmap lName (chooseLayout (Just yearsLayout) (InitDir "d")) @?= Right "years"+ fmap lName (chooseLayout Nothing (InitFile "f.journal")) @?= Right "simple"+ fmap lName (chooseLayout (Just simpleLayout) (InitFile "f.journal")) @?= Right "simple"+ either (const True) (const False) (chooseLayout (Just yearsLayout) (InitFile "f.journal")) @?= True+ fmap lName (lookupLayout "years") @?= Just "years"+ fmap lName (lookupLayout "nosuch") @?= Nothing+ ,testCase "layoutForYear" $ do+ let l = layoutForYear 2031 yearsLayout+ yearfile = find ((== "2031.journal") . lfPath) (lFiles l)+ lMainJournal l @?= "2031.journal"+ map lfPath (take 2 $ lFiles l) @?= ["2031.journal", "all.journal"]+ fmap (B.isInfixOf "2026" . lfContent) yearfile @?= Just False+ fmap (B.isInfixOf "2031-01-01" . lfContent) yearfile @?= Just True+ map lfContent (drop 1 $ lFiles l) @?= map lfContent (drop 1 $ lFiles yearsLayout)+ ,testCase "replaceString, replaceBytes" $ do+ replaceString "26" "31" "a26b26" @?= "a31b31"+ replaceString "" "x" "ab" @?= "ab"+ replaceBytes "26" "31" "a26b26" @?= "a31b31"+ replaceBytes "" "x" "ab" @?= "ab"+ ,testCase "planInit" $ do+ let dests = destinations defaultLayout (InitDir "d")+ names = map (\case Create p _ -> "create " <> p; Skip p -> "skip " <> p)+ fmap (take 2 . names) (planInit (\p -> if p == "d" </> "main.journal" then IsOther else Absent) dests)+ @?= Right ["skip " <> ("d" </> "main.journal"), "create " <> ("d" </> "accounts.journal")]+ either (const True) (const False) (planInit (\p -> if p == "d" </> "data" then IsOther else Absent) dests) @?= True+ ]
+ Hledger/Cli/Commands/Init.txt view
@@ -0,0 +1,66 @@+init++Create starter files for a new hledger setup, or add missing ones to an+existing setup.++Flags:+ --layout=LAYOUT which file layout to write: simple, default, years+ (default: default)+ --dry-run just show the files that would be created++With no argument, or a directory argument, init writes a set of files in+that directory (the current directory by default), creating it if+needed. Which files depends on the layout chosen with --layout. Note,+these are just to help you get started; you can always change the file+layout to suit your needs.++simple:++Just one file. Good if you want simplicity and manual data entry.++- main.journal - the journal file, with optional declarations++default (the default):++Declarations are kept separate; subdirectories and starter scripts for+data-fetching are provided. This is a good maintainable layout that+hledger commands understand well.++- main.journal - the main journal file, with a few example transactions+- accounts.journal, commodities.journal, payees.journal - declarations+- data/ - downloaded CSV files go here, with data/getdata, a starter+ script for get+- prices/ - market prices go here, with prices/getprices, a starter+ script for get+- rules/ - CSV rules files go here+- an example CSV file and rules file++years:++Like default, but each year has its own journal file. This gives you a+choice of loading all years or one year at a time (see close). It makes+life a little more complicated, but it is worthwhile if you have enough+data that a single file becomes slow on your machine; or if you want to+compartmentalise the data for other reasons.++- YEAR.journal (eg 2026.journal) - this year's journal, with a few+ example transactions.+- all.journal - includes all the year journals, for multi-year reports+- the same declaration files, directories and examples as default++With a journal file argument (a path ending with .journal, .j, .hledger+or .ledger), you'll get the simple layout, written to that file.++Files that already exist are never changed; they are skipped, with a+warning. So you can run init again to add missing files. After writing+the files, it suggests some next steps.++These and other file layouts can also be seen in the hledger repo's+examples/file-layouts directory.++Examples:++$ hledger init --dry-run # show what would be created in the current directory+$ hledger init ~/finance # create a standard setup in ~/finance+$ hledger init --layout years ~/finance # create a setup with a journal per year in ~/finance+$ hledger init 2026.journal # create a single journal file
+ Hledger/Cli/Commands/Notes.hs view
@@ -0,0 +1,39 @@+{-|++The @notes@ command lists all unique notes (description part after a |) seen in transactions, sorted alphabetically.++-}++{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE CPP #-}++module Hledger.Cli.Commands.Notes (+ notesmode+ ,notes+) where++import Data.List.Extra (nubSort)+import Data.Text qualified as T++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils (writeOutputWithTitle)+++-- | Command line options for this command.+notesmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Notes.txt")+ []+ cligeneralflagsgroups1+ hiddenflags+ ([], Just $ argsFlag "[QUERY]")++-- | The notes command.+notes :: CliOpts -> Journal -> IO ()+notes opts@CliOpts{reportspec_=rspec} j = do+ let ts = entriesReport rspec j+ notes' = nubSort $ map transactionNote ts+ writeOutputWithTitle opts $ T.unlines notes'
+ Hledger/Cli/Commands/Notes.txt view
@@ -0,0 +1,17 @@+notes++List the unique notes that appear in transactions.++Flags:+no command-specific flags++This command lists the unique notes that appear in transactions, in+alphabetic order. You can add a query to select a subset of+transactions. The note is the part of the transaction description after+a | character (or if there is no |, the whole description).++Example:++$ hledger notes+Petrol+Snacks
+ Hledger/Cli/Commands/Payees.hs view
@@ -0,0 +1,67 @@+{-|++The @payees@ command lists all unique payees (description part before a |) seen in transactions, sorted alphabetically.++-}++{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Payees (+ payeesmode+ ,payees+) where++import Data.Text qualified as Text+import Data.Text qualified as T+import System.Console.CmdArgs.Explicit++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils (writeOutputWithTitle)+import Data.List ((\\))+import Data.List.Extra (nubSort)+++-- | Command line options for this command.+payeesmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Payees.txt")+ [flagNone ["used"] (setboolopt "used") "list payees used"+ ,flagNone ["declared"] (setboolopt "declared") "list payees declared"+ ,flagNone ["undeclared"] (setboolopt "undeclared") "list payees used but not declared"+ ,flagNone ["unused"] (setboolopt "unused") "list payees declared but not used"+ ,flagNone ["find"] (setboolopt "find") "list the first payee matched by the first argument (a case-insensitive infix regexp)"+ ,flagNone ["directives"] (setboolopt "directives") "show as payee directives, for use in journals"+ ]+ cligeneralflagsgroups1+ hiddenflags+ ([], Just $ argsFlag "[QUERY..]")++-- | The payees command.+payees :: CliOpts -> Journal -> IO ()+payees opts@CliOpts{rawopts_=rawopts, reportspec_=ReportSpec{_rsQuery=query}} j = do+ let+ matchedused = dbg5 "matchedused" $ nubSort $ map transactionPayee $ filter (matchesTransaction query) $ jtxns j+ matcheddeclared = dbg5 "matcheddeclared" $ nubSort $ filter (matchesPayee query) $ journalPayeesDeclared j+ -- unused/undeclared subtract the full used/declared sets, not the query-filtered ones,+ -- so that eg a date: query can't make a declared payee look undeclared.+ matchedunused = dbg5 "matchedunused" $ nubSort $ matcheddeclared \\ allused+ matchedundeclared = dbg5 "matchedundeclared" $ nubSort $ matchedused \\ alldeclared+ matchedall = dbg5 "matchedall" $ nubSort $ matcheddeclared ++ matchedused+ found = dbg5 "found" $ findMatchedByArgument rawopts "payee" $ nubSort $ allused <> alldeclared+ allused = map transactionPayee $ jtxns j+ alldeclared = journalPayeesDeclared j+ -- With --directives, show as payee directives; a name containing a semicolon is double-quoted.+ showp p+ | boolopt "directives" rawopts = "payee " <> if Text.any (==';') p then "\"" <> p <> "\"" else p+ | otherwise = p+ writeOutputWithTitle opts $ T.unlines $ map showp $ case declarablesSelectorFromOpts opts of+ Nothing -> matchedall+ Just Used -> matchedused+ Just Declared -> matcheddeclared+ Just Undeclared -> matchedundeclared+ Just Unused -> matchedunused+ Just FindFirst -> [found]+
+ Hledger/Cli/Commands/Payees.txt view
@@ -0,0 +1,35 @@+payees++List the payee/payer names used or declared in the journal.++Flags:+ --used list payees used+ --declared list payees declared+ --undeclared list payees used but not declared+ --unused list payees declared but not used+ --find list the first payee matched by the first+ argument (a case-insensitive infix regexp)+ --directives show as payee directives, for use in journals++This command lists unique payee/payer names - all of them by default, or+just the ones which have been used in transaction descriptions, or+declared with payee directives, or used but not declared, or declared+but not used, or just the first one matched by a pattern (with --find,+returning a non-zero exit code if it fails).++The payee/payer name is the part of the transaction description before a+| character (or if there is no |, the whole description).++With --directives, it shows valid payee directives, which could be+pasted into a journal file.++You can add query arguments to select a subset of transactions or+payees. Note that transaction-specific query terms like date: will+exclude declared-but-unused payees, which don't have that field.++Example:++$ hledger payees+Store Name+Gas Station+Person A
+ Hledger/Cli/Commands/Prices.hs view
@@ -0,0 +1,257 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE NamedFieldPuns #-}++module Hledger.Cli.Commands.Prices (+ pricesmode+ ,prices+)+where++import Data.List+import Data.Set qualified as S+import Data.Text qualified as T+import Data.Time.Calendar (Day, DayOfWeek(..), dayOfWeek)+import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils (writeOutputWithTitle)+import System.Console.CmdArgs.Explicit+import Data.Maybe (mapMaybe)+import Data.Function ((&))+import Text.Printf (printf)++pricesmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Prices.txt")+ [flagNone ["show-reverse"] (setboolopt "show-reverse") "also show the prices inferred by reversing known prices"+ ,flagNone ["show-aliases"] (setboolopt "show-aliases") "also show the exchange rates provided by commodity aliases"+ ,flagNone ["summary"] (setboolopt "summary") "summarise declared prices per commodity instead of listing them"+ ,flagNone ["locations"] (setboolopt "locations") "also show where prices where declared"+ ]+ cligeneralflagsgroups1+ (hiddenflags +++ [flagNone ["costs"] (setboolopt "infer-market-prices") "deprecated, use --infer-market-prices instead"+ ,flagNone ["inverted-costs"] (setboolopt "show-reverse") "deprecated, use --show-reverse instead"+ ,flagNone ["infer-reverse-prices"] (setboolopt "show-reverse") "deprecated, use --show-reverse instead"+ ])+ ([], Just $ argsFlag "[QUERY]")++instance HasAmounts PriceDirective where+ styleAmounts styles pd = pd{pdamount=styleAmounts styles $ pdamount pd}++-- List market prices.+prices opts j = do+ let+ q = _rsQuery $ reportspec_ opts+ showloc = boolopt "locations" (rawopts_ opts)+ styles = journalCommodityStyles j+ render pd =+ showPriceDirective (styleAmounts styles pd)+ <> comment (["commodity alias" | isAliasRate pd] <> [loc | showloc, Just loc <- [locationTag pd]])++ -- XXX duplicates logic in Hledger.Data.Valuation.makePriceGraph, keep synced++ declaredprices =+ -- dbg0 "declaredprices" $+ jpricedirectives j++ -- Use the location-preserving helper only when --locations is set,+ -- to avoid the per-directive record update otherwise.+ pricesfromcosts =+ -- dbg0 "pricesfromcosts" $+ concatMap (if showloc then postingPriceDirectivesWithLoc+ else postingPriceDirectivesFromCost) $+ journalPostings j++ marketprices =+ -- dbg0 "marketprices" $+ if boolopt "infer-market-prices" (rawopts_ opts)+ then declaredprices `mergePriceDirectives` pricesfromcosts+ else declaredprices++ -- Commodity alias rates, between commodities with no market prices between them+ -- (as in Hledger.Data.Valuation.buildPriceIndexes).+ aliasprices =+ if boolopt "show-aliases" (rawopts_ opts)+ then [ pd | pd <- journalAliasPriceDirectives j, let (f, t) = pricePair pd+ , not $ S.member (f, t) marketpairs, not $ S.member (t, f) marketpairs ]+ else []+ where marketpairs = S.fromList $ map pricePair marketprices+ aliaspairs = S.fromList $ map pricePair aliasprices+ pricePair pd = (pdcommodity pd, acommodity $ pdamount pd)+ -- An alias rate, or its reverse ?+ isAliasRate pd = let (f, t) = pricePair pd in S.member (f, t) aliaspairs || S.member (t, f) aliaspairs++ forwardprices = marketprices <> aliasprices++ reverseprices =+ -- dbg0 "reverseprices" $+ mapMaybe reversePriceDirective forwardprices++ allprices =+ -- dbg0 "allprices" $+ if boolopt "show-reverse" (rawopts_ opts)+ then forwardprices `mergePriceDirectives` reverseprices+ else forwardprices++ filteredprices =+ -- dbg0 "filtered unsorted" $+ filter (matchesPriceDirective q) allprices++ writeOutputWithTitle opts $+ if boolopt "summary" (rawopts_ opts)+ then pricesSummary j q (filter (matchesPriceDirective q) declaredprices)+ else T.unlines $ map render $ sortOn pddate filteredprices++-- | Like 'postingPriceDirectivesFromCost', but tags each inferred+-- price directive with the source position of the parent transaction+-- (if known) so it can be reported by --locations.+postingPriceDirectivesWithLoc :: Posting -> [PriceDirective]+postingPriceDirectivesWithLoc p =+ [ pd{pdsourcepos = pos} | pd <- postingPriceDirectivesFromCost p ]+ where+ pos = maybe nullsourcepos (fst . tsourcepos) (ptransaction p)++-- | A trailing journal comment containing these items, if any.+comment :: [T.Text] -> T.Text+comment [] = ""+comment xs = " ; " <> T.intercalate ", " xs++-- | A location tag showing the file and line where a price directive was declared or inferred+-- (or for a commodity alias rate, the commodity directive declaring it).+-- Reversed prices inherit the source position of the directive they were derived from.+-- Nothing only when no source position is available.+locationTag :: PriceDirective -> Maybe T.Text+locationTag PriceDirective{pdsourcepos=SourcePos fp l _}+ | null fp = Nothing+ | otherwise = Just $ "location: " <> T.pack fp <> ":" <> T.pack (show (unPos l))++-- | Per-commodity stats from the journal's declared price directives.+data PriceStats = PriceStats+ { psCommodity :: CommoditySymbol+ , psCount :: Int+ , psEarliest :: Maybe Day+ , psLatest :: Maybe Day+ , psDays :: S.Set Day -- distinct price dates+ }++-- | Stats for one ISO commodity code, gathered from raw P directives.+-- Symbol variants (eg "$" / "USD") are grouped together via 'toCurrencyCode'.+priceStatsFor :: [PriceDirective] -> CurrencyCode -> PriceStats+priceStatsFor pds c =+ let xs = filter ((== c) . toCurrencyCode . pdcommodity) pds+ dset = S.fromList (map pddate xs)+ in PriceStats c (length xs)+ (fst <$> S.minView dset)+ (fst <$> S.maxView dset)+ dset++isWeekday :: Day -> Bool+isWeekday d = case dayOfWeek d of+ Saturday -> False+ Sunday -> False+ _ -> True++-- | Compact human duration: "45d", "11mo", "1y 3mo".+-- Approximates with 365-day years and 30-day months — display only.+compactDuration :: Int -> T.Text+compactDuration n+ | n < 60 = T.pack (show n) <> "d"+ | n < 365 = T.pack (show (n `div` 30)) <> "mo"+ | otherwise =+ let (y, r) = n `divMod` 365+ mo = r `div` 30+ in T.pack (show y) <> "y" <>+ (if mo == 0 then "" else " " <> T.pack (show mo) <> "mo")++-- | The text for the period and coverage columns of a stats row.+-- Both are blank when the commodity has fewer than two prices.+-- Coverage is computed on a weekdays-only basis (Mon–Fri), so+-- weekday-only sources (eg FX) approach 100% rather than ~71%.+periodAndCoverage :: PriceStats -> (T.Text, T.Text)+periodAndCoverage ps@PriceStats{psEarliest=Just s, psLatest=Just e}+ | psCount ps < 2 = ("", "")+ | otherwise = (compactDuration nDays, T.pack (printf "%.f%%" pct))+ where+ days = [s..e]+ nDays = length days+ weekdays = filter isWeekday days+ nWeekdays = length weekdays+ nCovered = length (filter (`S.member` psDays ps) weekdays)+ pct | nWeekdays == 0 = 0+ | otherwise =+ fromIntegral nCovered / fromIntegral nWeekdays * 100 :: Double+periodAndCoverage _ = ("", "")++-- | Render the per-commodity summary table.+-- Lists every commodity used in the journal except the base currency,+-- normalised to ISO codes and deduplicated. The 'cur:' portion of the+-- query (if any) narrows the listed commodities. The supplied price+-- directives (already query-filtered by the caller) drive the counts.+pricesSummary :: Journal -> Query -> [PriceDirective] -> T.Text+pricesSummary j q pds =+ let+ base = journalBaseCurrencyCode j+ -- Just the cur: terms of the query; non-cur terms become Any so+ -- they don't reject every commodity.+ symq = filterQuery queryIsCur q+ codes = sort . nub . filter (/= base) . filter (matchesCommodity symq)+ . map toCurrencyCode+ $ journalCommoditiesUsed j+ rows = map (statsRow . priceStatsFor pds) codes+ header = ["Commodity", "Prices", "Earliest", "Latest", "Period", "Coverage"]+ aligns = [AlignL, AlignR, AlignL, AlignL, AlignR, AlignR]+ in renderColumns aligns (header : rows)++statsRow :: PriceStats -> [T.Text]+statsRow ps =+ let (perTxt, covTxt) = periodAndCoverage ps+ in [ psCommodity ps+ , T.pack (show (psCount ps))+ , maybe "-" (T.pack . show) (psEarliest ps)+ , maybe "-" (T.pack . show) (psLatest ps)+ , perTxt+ , covTxt+ ]++data ColAlign = AlignL | AlignR++-- | Render a list of equal-length rows as a column-aligned plain-text+-- table, two spaces between columns, one row per line.+renderColumns :: [ColAlign] -> [[T.Text]] -> T.Text+renderColumns aligns rs =+ let widths = map (maximum . map T.length) (transpose rs)+ pad a w t = case a of AlignL -> T.justifyLeft w ' ' t+ AlignR -> T.justifyRight w ' ' t+ renderRow r = T.stripEnd (T.intercalate " " (zipWith3 pad aligns widths r))+ in T.unlines (map renderRow rs)++-- XXX performance+-- | Append any new price directives (with different from commodity,+-- to commodity, or date) from the second list to the first.+-- (Does not remove redundant prices from the first; just avoids adding more.)+mergePriceDirectives :: [PriceDirective] -> [PriceDirective] -> [PriceDirective]+mergePriceDirectives pds1 pds2 =+ pds1 ++ [ pd | pd <- pds2 , pdid pd `notElem` pds1ids ]+ where+ pds1ids = map pdid pds1+ pdid PriceDirective{pddate,pdcommodity,pdamount} = (pddate, pdcommodity, acommodity pdamount)++-- | Convert a market price directive to a corresponding one in the+-- opposite direction, if possible. (A price directive with a zero+-- price can't be reversed.)+--+-- The price's display precision will be set to show all significant+-- decimal digits (or if they appear infinite, a smaller default precision (8).+-- This is visible eg in the prices command's output.+--+reversePriceDirective :: PriceDirective -> Maybe PriceDirective+reversePriceDirective pd@PriceDirective{pdcommodity=c, pdamount=a}+ | amountIsZero a = Nothing+ | otherwise = Just pd{pdcommodity=acommodity a, pdamount=a'}+ where+ lbl = lbl_ "reversePriceDirective"+ a' =+ amountSetFullPrecisionUpTo (Just defaultMaxDisplayPrecision) $+ invertAmount a{acommodity=c}+ & dbg9With (lbl "calculated reverse price".showAmount)+ -- & dbg9With (lbl "precision of reverse price".show.amountDisplayPrecision)
+ Hledger/Cli/Commands/Prices.txt view
@@ -0,0 +1,73 @@+prices++Print the market prices declared with P directives. With+--infer-market-prices, also show any additional prices inferred from+costs. With --show-reverse, also show additional prices inferred by+reversing known prices. With --show-aliases, also show the exchange+rates provided by commodity aliases.++Flags:+ --show-reverse also show the prices inferred by reversing known+ prices+ --show-aliases also show the exchange rates provided by+ commodity aliases+ --summary summarise declared prices per commodity instead+ of listing them+ --locations also show where prices where declared++With --locations, each price line gets a trailing ; location: FILE:LINE+comment showing where it came from. Declared prices point at their P+directive; prices inferred from costs point at the parent transaction's+first line. Reversed prices keep the source position of the directive+they were derived from.++With --show-aliases, each commodity alias which provides an exchange+rate (between a commodity and its alias, when there are no market prices+between them) is shown as a price dated 0000-01-01 with a+; commodity alias comment. Its location is the commodity directive which+declared the alias. These are used only when market prices can't provide+a conversion, see Finding market price.++Price amounts are always displayed with their full precision, except for+reverse prices which are limited to 8 decimal digits.++Prices can be filtered by a date:, cur:, amt: or find: query.++Generally if you run this command with --infer-market-prices+--show-reverse --show-aliases, it will show the same prices used+internally to calculate value reports. But if in doubt, you can inspect+those directly by running the value report with --debug=2.++Examples:++$ hledger prices+P 2024-01-01 AAPL $150+P 2024-02-01 AAPL $160+P 2024-02-01 EUR $1.08++$ hledger prices --infer-market-prices+P 2024-01-01 AAPL $150+P 2024-01-05 AAPL $150+P 2024-02-01 AAPL $160+P 2024-02-01 EUR $1.08++prices summary++With --summary, instead of listing individual prices, prices prints one+row per commodity used in the journal (other than the base currency),+with the following columns:++- Commodity — the commodity, as an ISO 4217 code if possible.+- Prices — the number of market price declarations for that commodity.+- Earliest / Latest — the date range of those prices.+- Period — the duration between earliest and latest.+- Coverage — the percentage of weekdays in that period that have a price+ declared (or blank when fewer than two prices).++Summary mode is a quick way to spot gaps in your price data, and pairs+naturally with getprices. Only prices declared with P directives are+counted; prices inferred with --show-reverse or --infer-market-prices+are ignored.++Queries (cur:, date:, amt:, find:) can be used to narrow the prices that+are summarised.
+ Hledger/Cli/Commands/Print.hs view
@@ -0,0 +1,427 @@+{-|++A ledger-compatible @print@ command.++-}++{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Print (+ printmode+ ,print'+ ,journalApplyMatchOpt+ ,entriesReportAsTextHelper+ ,roundFlag+ ,roundFromRawOpts+ ,amountStylesSetRoundingFromRawOpts+ ,layoutFlag+ ,layoutFromRawOpts+ ,transactionWithMostlyOriginalPostings+)+where+++import Data.Function ((&))+import Data.List (intersperse, intercalate)+import Data.Text (Text)+import Data.Map (Map)+import Data.Map qualified as Map+import Data.Text qualified as T+import Data.Text.Lazy qualified as TL+import Data.Text.Lazy.Builder qualified as TB+import Lens.Micro ((^.), _Just, has)+import Safe (lastMay, readMay)+import System.Console.CmdArgs.Explicit++import Hledger+import Hledger.Write.Beancount (showTransactionBeancount, beancountTransactions, beancountRenameAccounts, beancountDirectives, beancountItemRenderer)+import Hledger.Write.Ledger (showTransactionLedger, ledgerItemRenderer)+import Hledger.Write.Journal (ItemRenderer(..), journalItemRenderer, journalItemsAsText)+import Hledger.Write.Csv (CSV, printCSV, printTSV)+import Hledger.Write.Ods (printFods)+import Hledger.Write.Html (styledTableHtml, htmlAsLazyText, toHtml)+import Hledger.Write.Spreadsheet qualified as Spr+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils+import Hledger.Cli.Anchor (setAccountAnchor)+import System.IO qualified as IO+import Data.Maybe (isJust, isNothing)++printmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Print.txt")+ ([+ flagNone ["all","a"] (setboolopt "explicit" . setboolopt "lots" . setboolopt "verbose-tags")+ "show all details (--explicit --lots --verbose-tags)"+ ,flagNone ["explicit","x"] (setboolopt "explicit") "show all inferred info explicitly"+ ,flagNone ["verbose-tags"] (setboolopt "verbose-tags") "add tags indicating generated/modified data"+ ,flagNone ["invert"] (setboolopt "invert") "display all amounts with reversed sign"+ ,flagNone ["locations"] (setboolopt "locations") "add tags showing file paths and line numbers"+ ,flagNone ["export"] (setboolopt "export") "reproduce the whole journal, with directives and comments preserved and included files inlined"+ ,let arg = "DESC" in+ flagReq ["match","m"] (\s opts -> Right $ setopt "match" s opts) arg+ ("fuzzy search for one recent transaction with description closest to "++arg)+ ,flagNone ["new"] (setboolopt "new") "show only newer-dated transactions added in each file since last run"+ ,roundFlag+ ,layoutFlag+ ,flagReq ["base-url"] (\s opts -> Right $ setopt "base-url" s opts) "URLPREFIX"+ "in html output, generate links to hledger-web, with this prefix. (Usually the base url shown by hledger-web; can also be relative.)"+ ,outputFormatFlag ["journal","ledger","beancount","csv","tsv","html","fods","json","sql"]+ ,outputFileFlag+ ,outputViewFlag+ ])+ cligeneralflagsgroups1+ hiddenflags+ ([], Just $ argsFlag "[QUERY]")++roundFlag = flagReq ["round"] (\s opts -> Right $ setopt "round" s opts) "TYPE" $+ intercalate "\n"+ ["how much rounding or padding should be done when displaying amounts ?"+ ,"none - show original decimal digits,"+ ," as in journal (default)"+ ,"soft - just add or remove decimal zeros"+ ," to match precision"+ ,"hard - round posting amounts to precision"+ ," (can unbalance transactions)"+ ,"all - also round cost amounts to precision"+ ," (can unbalance transactions)"+ ]++-- | Get the --round option's value, if any. Can fail with a parse error.+roundFromRawOpts :: RawOpts -> Maybe Rounding+roundFromRawOpts = lastMay . collectopts roundfromrawopt+ where+ roundfromrawopt (n,v)+ | n=="round", v=="none" = Just NoRounding+ | n=="round", v=="soft" = Just SoftRounding+ | n=="round", v=="hard" = Just HardRounding+ | n=="round", v=="all" = Just AllRounding+ | n=="round" = error' $ "--round's value should be none, soft, hard or all; got: "++v+ | otherwise = Nothing++-- | Set these amount styles' rounding strategy when they are being applied to amounts,+-- according to the value of the --round option, if any.+amountStylesSetRoundingFromRawOpts :: RawOpts -> Map CommoditySymbol AmountStyle -> Map CommoditySymbol AmountStyle+amountStylesSetRoundingFromRawOpts rawopts styles =+ case roundFromRawOpts rawopts of+ Just r -> amountStylesSetRounding r styles+ Nothing -> styles++-- | The --layout flag for the print command, selecting how posting lines are aligned.+layoutFlag :: Flag RawOpts+layoutFlag = flagReq ["layout"] (\s opts -> Right $ setopt "layout" s opts) "hledger1|COL" $+ intercalate "\n"+ ["how should posting amounts be aligned ?"+ ,"hledger1 - right-align amounts, as in hledger 1"+ ,"COL - align decimal marks at column COL (default: 53)"+ ]++-- | Parse the --layout option. Defaults to 'defaultPostingLayout' if absent.+-- Errors with a clear message if the value is neither \"hledger1\" nor a positive integer.+layoutFromRawOpts :: RawOpts -> PostingLayout+layoutFromRawOpts rawopts = case maybestringopt "layout" rawopts of+ Nothing -> defaultPostingLayout+ Just "hledger1" -> LayoutHledger1+ Just s -> case readMay s of+ Just n | n >= 0 -> LayoutDecimal n+ _ -> error' $ "--layout's value should be 'hledger1' or a positive integer column number; got: " ++ s++-- | Print journal transactions in standard format.+print' :: CliOpts -> Journal -> IO ()+print' opts@CliOpts{rawopts_=rawopts} j = do+ -- The print command should show all amounts with their original decimal places,+ -- but as part of journal reading the posting amounts have already been normalised+ -- according to commodity display styles, and currently it's not easy to avoid+ -- that. For now we try to reverse it by increasing all amounts' decimal places+ -- sufficiently to show the amount exactly. The displayed amounts may have minor+ -- differences from the originals, such as trailing zeroes added.+ -- An amount with a repeating decimal (from division, rounded at the 255th decimal place)+ -- is shown with 8 decimal places, not all 255.+ -- But, we skip this for inferred postings.+ -- This avoids eg showing too many decimals by default for inferred gain amounts.+ let+ -- lbl = lbl_ "print'"+ hasPtype t p = ("_ptype", t) `elem` ptags p+ isGeneratedGainPosting p = hasPtype "gain" p+ setFullPrecisionExceptGain p+ | isGeneratedGainPosting p = p+ | otherwise = postingTransformAmount mixedAmountSetFullPrecisionCapped p+ j' = j+ -- & dbg9With (lbl "amounts before setting full precision".showJournalPostingAmountsDebug)+ & journalMapPostings setFullPrecisionExceptGain+ -- & dbg9With (lbl "amounts after setting full precision: ".showJournalPostingAmountsDebug)+ & if boolopt "locations" rawopts then journalMapTransactions addLocationTag else id++ printEntries opts $ journalApplyMatchOpt opts j'++-- | With --match DESC, keep only the one recent transaction whose description+-- is most similar to DESC, erroring if there is none. Otherwise, return the journal unchanged.+-- XXX should match similarly to register --match+journalApplyMatchOpt :: CliOpts -> Journal -> Journal+journalApplyMatchOpt opts j =+ case maybestringopt "match" $ rawopts_ opts of+ Nothing -> j+ Just desc ->+ case journalSimilarTransaction opts j (dbg1 "finding best match for description" $ T.pack desc) of+ Just t -> j{jtxns=[t]}+ Nothing -> error' $ "no transactions found with descriptions like " <> show desc++printEntries :: CliOpts -> Journal -> IO ()+printEntries opts@CliOpts{rawopts_=rawopts, reportspec_=rspec} j =+ writeOutputLazyText opts $+ if boolopt "export" rawopts+ then renderExport $ entriesReportUnsorted rspec j+ else render $ entriesReport rspec j+ where+ -- print does user-specified rounding or (by default) no rounding, in all output formats+ styles = amountStylesSetRoundingFromRawOpts rawopts $ journalCommodityStyles j+ styledPrices = map (\pd -> pd{pdamount = styleAmounts styles $ pdamount pd}) $ jpricedirectives j++ -- txt is an unlisted alias for journal, the default (outputFormatFromOpts calls it txt)+ fmt = case outputFormatFromOpts opts of+ "txt" -> "journal"+ f -> f+ baseUrl = balance_base_url_ $ _rsReportOpts rspec+ query = querystring_ $ _rsReportOpts rspec+ postinglayout = layoutFromRawOpts rawopts++ -- With --export, reproduce the journal file(s): directives and comments verbatim,+ -- the (filtered, processed) transactions in their original positions, and blank lines normalised.+ -- Transactions and postings generated by --forecast, --auto etc. are included when those flags+ -- are used, and then the periodic transaction rules / auto posting rules which generated them are dropped.+ renderExport+ | fmt=="journal" = exportWith (journalItemRenderer $ showTransactionWithLayout postinglayout)+ | fmt=="ledger" = exportWith ledgerItemRenderer+ | fmt=="beancount" = \ts ->+ let (j', ts') = beancountRenameAccounts j{jpricedirectives=styledPrices} $ beancountTransactions $ styleAmounts styles $ map fillBalanceAssignments ts+ -- (beancountItemRenderer drops all directives, including rules; anything generated is exported)+ in beancountDirectives j' ts' <> "\n" <> journalItemsAsText beancountItemRenderer (jitems j') ts'+ | otherwise = error' "print --export supports only the journal, ledger and beancount output formats" -- PARTIAL:+ where+ exportWith renderer = journalItemsAsText (withoutAppliedRules renderer) (jitems j) . styleAmounts styles . map (maybeoriginalamountsWith False)+ withoutAppliedRules renderer = renderer{irDirective = \txt -> if isAppliedRule txt then Nothing else irDirective renderer txt}+ isAppliedRule txt = (forecasting && "~" `T.isPrefixOf` txt) || (autoposting && "=" `T.isPrefixOf` txt)+ forecasting = isJust $ forecast_ $ inputopts_ opts+ autoposting = auto_ $ inputopts_ opts++ render | fmt=="journal" = withTitle (_rsReportOpts rspec) . entriesReportAsTextHelper (showTransactionWithLayout postinglayout) . styleAmounts styles . map maybeoriginalamounts+ | fmt=="ledger" = withTitle (_rsReportOpts rspec) . entriesReportAsTextHelper showTransactionLedger . styleAmounts styles . map maybeoriginalamounts+ | fmt=="beancount" = entriesReportAsTextHelper showTransactionBeancount . snd . beancountRenameAccounts j . beancountTransactions . styleAmounts styles . map fillBalanceAssignments+ | fmt=="csv" = printCSV . entriesReportAsCsv . styleAmounts styles+ | fmt=="tsv" = printTSV . entriesReportAsCsv . styleAmounts styles+ | fmt=="json" = toJsonText . styleAmounts styles+ | fmt=="sql" = entriesReportAsSql . styleAmounts styles+ | fmt=="html" =+ (<>"\n") . htmlAsLazyText . styledTableHtml .+ map (map (fmap toHtml)) .+ entriesReportAsSpreadsheet oneLineNoCostFmt baseUrl query .+ styleAmounts styles+ | fmt=="fods" =+ printFods IO.localeEncoding . Map.singleton "Print" .+ (,) (1,0) .+ entriesReportAsSpreadsheet oneLineNoCostFmt baseUrl query .+ styleAmounts styles+ | otherwise = error' $ unsupportedOutputFormatError fmt -- PARTIAL:++ -- For plain print, lot postings also get the cost basis annotation inferred+ -- by lot processing, making the output self-describing; not for --export,+ -- which reproduces the journal's directives instead and keeps entries as written.+ maybeoriginalamounts = maybeoriginalamountsWith True+ maybeoriginalamountsWith showinferredbasis+ -- Use the fully inferred and amount-styled/rounded transaction in the following situations:+ -- with -x/--explicit:+ | boolopt "explicit" (rawopts_ opts) = id+ -- with --infer-costs+ | opts ^. infer_costs = id+ -- with -B/-V/-X/--value ("because of #551, and because of print -V valuing only one posting when there's an implicit txn price.")+ | has (value . _Just) opts = id+ | isJust (conversionop_ $ _rsReportOpts rspec) = id+ -- For transactions containing priced auto-split postings (from lot transfer+ -- auto-split), keep the explicit form: reverting to the original would drop+ -- the priced dispose fragment while keeping its generated gain postings,+ -- leaving an unbalanced entry. (Priceless fee fragments generate no gain+ -- postings, so those transactions can safely revert to the user's original+ -- entry - except with --lots, where fragments must be kept to round-trip.)+ -- Otherwise, keep the transaction's amounts close to how they were written in the journal.+ | otherwise = \t ->+ if any keptFeesplit (tpostings t)+ then t+ else transactionWithMostlyOriginalPostings showinferredbasis t+ where+ hasTag name p = name `elem` map fst (ptags p)+ keptFeesplit p = hasTag feesplitPostingTagName p+ && (boolopt "lots" (rawopts_ opts) || any (isJust . acost) (amountsRaw (pamount p)))++ -- Like maybeoriginalamounts, but also keeps the inferred amount for+ -- balance assignment postings (which had no explicit amount).+ -- Beancount requires all amounts to be explicit.+ fillBalanceAssignments t = (maybeoriginalamountsWith False t)+ { tpostings = zipWith fillIfBalAssign (tpostings t) (tpostings $ maybeoriginalamountsWith False t) }+ where+ fillIfBalAssign inferred reverted+ | isJust (pbalanceassertion orig) && isMissingMixedAmount (pamount orig) = reverted { pamount = pamount inferred }+ | otherwise = reverted+ where orig = originalPosting inferred++-- | Replace this transaction's postings with the original postings if any, but keep the+-- current possibly rewritten account names, and the inferred values of any auto postings.+-- Drops postings tagged 'feesplitPostingTagName' (synthetic fragments carved off other+-- postings, eg by lot transfer auto-split), so the user sees their original entry.+-- Postings tagged 'lotsplitPostingTagName' (per-lot dispose/transfer split fragments)+-- are retained, keeping their fragment 'pamount' rather than reverting to 'poriginal' —+-- so 'print --lots' shows the per-lot detail, while 'journalCollapseLotDetail' has+-- already merged them down to one posting when --lots is off.+-- With a true first argument, lot postings whose original amount had no cost basis+-- annotation get the one inferred by lot processing (see withInferredBasis below).+-- This is mainly for showing transactions with the amounts in their original journal format.+transactionWithMostlyOriginalPostings :: Bool -> Transaction -> Transaction+transactionWithMostlyOriginalPostings showinferredbasis t =+ transactionMapPostings postingMostlyOriginal+ t{tpostings = filter (not . hasTag feesplitPostingTagName) (tpostings t)}+ where+ postingMostlyOriginal p = orig+ { paccount = paccount p+ , pamount = newAmt+ -- Keep the current comment and tags: journal processing only appends+ -- to these (eg visible ptype tags added by lot classification, which+ -- runs after the original was snapshotted), never rewrites the+ -- user's text.+ , pcomment = pcomment p+ , ptags = ptags p+ -- When paccount equals the original (no collapse), trust the+ -- original's assertion. When paccount has been changed (eg a lot+ -- subaccount was collapsed away), use the current state's+ -- assertion — which 'journalCollapseLotDetail' has already cleared+ -- if the assertion targeted the now-hidden lot subaccount.+ , pbalanceassertion =+ if paccount orig == paccount p+ then pbalanceassertion orig+ else pbalanceassertion p }+ where+ orig = originalPosting p+ newAmt+ | hasTag generatedPostingTagName p = pamount p+ -- For per-lot dispose/transfer fragments, use the user's original+ -- amount but with the fragment's quantity (so 'print --lots' shows+ -- e.g. "-1 A {} @ $60" rather than the full inferred form).+ -- When the original was elided or a balance assignment (no amount),+ -- show the fragment's current amount: several sibling fragments+ -- can't re-infer their amounts on re-reading (#2692).+ | hasTag lotsplitPostingTagName p =+ withInferredBasis $ if hasAmount orig then scaleToFragment (pamount orig) (pamount p) else pamount p+ | otherwise = withInferredBasis (pamount orig)+ -- Show the cost basis annotation inferred by lot processing, when the+ -- user didn't write one, so lot entries are self-describing (they can+ -- be re-read without the commodity's lots: declaration, under the+ -- default method). Not needed with --lots, where the lot subaccount+ -- name already carries it.+ withInferredBasis ma+ | not showinferredbasis = ma+ | isJust (lotSubaccountName (paccount p)) = ma+ | otherwise = case (amountsRaw ma, amountsRaw (pamount p)) of+ ([oa], [ca]) | isNothing (acostbasis oa), Just cb <- acostbasis ca -> mixedAmount oa{acostbasis = Just cb}+ _ -> ma+ scaleToFragment origAmt curAmt = case (amountsRaw origAmt, amountsRaw curAmt) of+ ([oa], [ca]) -> mixedAmount oa{aquantity = aquantity ca}+ _ -> curAmt+ hasTag name p = name `elem` map fst (ptags p)++entriesReportAsTextHelper :: (Transaction -> T.Text) -> EntriesReport -> TL.Text+entriesReportAsTextHelper showtxn = TB.toLazyText . foldMap (TB.fromText . showtxn)++entriesReportAsSql :: EntriesReport -> TL.Text+entriesReportAsSql txns = TB.toLazyText $ mconcat+ [ TB.fromText "create table if not exists postings(id serial,txnidx int,date1 date,date2 date,status text,code text,description text,comment text,account text,amount numeric,commodity text,debit numeric,credit numeric,posting_status text,posting_comment text);\n"+ , TB.fromText "insert into postings(txnidx,date1,date2,status,code,description,comment,account,amount,commodity,debit,credit,posting_status,posting_comment) values\n"+ , mconcat . intersperse (TB.fromText ",") $ map values csv+ , TB.fromText ";\n"+ ]+ where+ values vs = TB.fromText "(" <> mconcat (intersperse (TB.fromText ",") $ map toSql vs) <> TB.fromText ")\n"+ toSql "" = TB.fromText "NULL"+ toSql s = TB.fromText "'" <> TB.fromText (T.replace "'" "''" s) <> TB.fromText "'"+ csv =+ Spr.rawTableContent . transactionToSpreadsheet machineFmt Nothing [] .+ transactionMapPostingAmounts (mapMixedAmount setDecimalPoint)+ =<< txns+ where+ setDecimalPoint a = a{astyle=(astyle a){asdecimalmark=Just '.'}}++entriesReportAsCsv :: EntriesReport -> CSV+entriesReportAsCsv =+ Spr.rawTableContent . entriesReportAsSpreadsheet machineFmt Nothing []++entriesReportAsSpreadsheet ::+ AmountFormat -> Maybe Text -> [Text] ->+ EntriesReport -> [[Spr.Cell Spr.NumLines Text]]+entriesReportAsSpreadsheet fmt baseUrl query txns =+ Spr.addHeaderBorders+ (map Spr.headerCell+ ["txnidx","date","date2","status","code","description","comment",+ "account","amount","commodity","debit","credit",+ "posting-status","posting-comment"])+ :+ concatMap (transactionToSpreadsheet fmt baseUrl query) txns++-- | Generate one record per posting, duplicating the common transaction fields.+-- The txnidx field (transaction index) allows postings to be grouped back into transactions.+transactionToSpreadsheet ::+ AmountFormat -> Maybe Text -> [Text] ->+ Transaction -> [[Spr.Cell Spr.NumLines Text]]+transactionToSpreadsheet fmt baseUrl query t =+ addRowSpanHeader (idx:d:d2:status:code:description:comment:[])+ (postingToSpreadsheet fmt baseUrl query =<< tpostings t)+ where+ cell = Spr.defaultCell+ idx = Spr.integerCell $ tindex t+ description = cell $ tdescription t+ dateCell date =+ (Spr.defaultCell $ showDate date) {Spr.cellType = Spr.TypeDate}+ d = dateCell $ tdate t+ d2 = maybe Spr.emptyCell dateCell $ tdate2 t+ status = cell $ T.pack . show $ tstatus t+ code = cell $ tcode t+ comment = cell $ T.strip $ tcomment t++addRowSpanHeader ::+ [Spr.Cell border text] ->+ [[Spr.Cell border text]] -> [[Spr.Cell border text]]+addRowSpanHeader common rows =+ case rows of+ [] -> []+ [row] -> [common++row]+ _ ->+ let setSpan spn cell = cell{Spr.cellSpan = spn} in+ zipWith (++)+ (map (setSpan $ Spr.SpanVertical $ length rows) common :+ repeat (map (setSpan Spr.Covered) common))+ rows++postingToSpreadsheet ::+ (Spr.Lines border) =>+ AmountFormat -> Maybe Text -> [Text] ->+ Posting -> [[Spr.Cell border Text]]+postingToSpreadsheet fmt baseUrl query p =+ map (\(a@(Amount {aquantity=q,acommodity=c})) ->+ -- commodity goes into separate column, so we suppress it, along with digit group+ -- separators and prices+ let a_ = amountStripCost a{acommodity=""} in+ let credit = if q < 0 then amountCell $ negate a_ else Spr.emptyCell in+ let debit = if q >= 0 then amountCell a_ else Spr.emptyCell in+ [setAccountAnchor baseUrl query (paccount p) $ cell account,+ amountCell a_, cell c,+ debit, credit, cell status, cell comment])+ . amounts $ pamount p+ where+ cell = Spr.defaultCell+ amountCell amt =+ Spr.cellFromAmount fmt+ (Spr.Class "amount", (wbToText $ showAmountB machineFmt amt, amt))+ status = T.pack . show $ pstatus p+ account = showAccountName Nothing (preal p) (paccount p)+ comment = T.strip $ pcomment p++addLocationTag :: Transaction -> Transaction+addLocationTag t = t{tcomment = tcomment t `commentAddTagNextLine` loctag}+ where+ loctag = ("location", T.pack . sourcePosPairPretty $ tsourcepos t)
+ Hledger/Cli/Commands/Print.txt view
@@ -0,0 +1,326 @@+print++Show transactions' journal entries, or export journal data to another+format.++Flags:+ -a --all show all details (--explicit --lots+ --verbose-tags)+ -x --explicit show all inferred info explicitly+ --verbose-tags add tags indicating generated/modified data+ --invert display all amounts with reversed sign+ --locations add tags showing file paths and line numbers+ --export reproduce the whole journal, with directives and+ comments preserved and included files inlined+ -m --match=DESC fuzzy search for one recent transaction with+ description closest to DESC+ --new show only newer-dated transactions added in each+ file since last run+ --round=TYPE how much rounding or padding should be done when+ displaying amounts ?+ none - show original decimal digits,+ as in journal (default)+ soft - just add or remove decimal zeros+ to match precision+ hard - round posting amounts to precision+ (can unbalance transactions)+ all - also round cost amounts to precision+ (can unbalance transactions)+ --layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 - right-align amounts, as in hledger 1+ COL - align decimal marks at column COL+ (default: 53)+ --base-url=URLPREFIX in html output, generate links to hledger-web,+ with this prefix. (Usually the base url shown by+ hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ journal, ledger, beancount, csv, tsv, html, fods,+ json, sql.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ --view write output to FILE, or to view.FMT in hledger's+ cache directory, and open it in the system's+ default viewer for its format (eg a web browser for+ html). The default format is html.++The print command displays full journal entries (transactions) from the+journal file, sorted by date (or with --date2, by secondary date). (For+a compact one-line-per-transaction overview, see the transactions+command.)++By default, directives and inter-transaction comments are not shown+(except for comment lines immediately preceding a transaction, which are+shown with it), and entries are sorted by date. So the default print+output is somewhat lossy. To reproduce the whole journal, including+directives and comments, use --export (see below).++Eg:++$ hledger print -f examples/sample.journal date:200806+2008/06/01 gift+ assets:bank:checking $1+ income:gifts $-1++2008/06/02 save+ assets:bank:saving $1+ assets:bank:checking $-1++2008/06/03 * eat & shop+ expenses:food $1+ expenses:supplies $1+ assets:cash $-2++print explicitness++Normally, whether posting amounts are implicit or explicit is preserved.+For example, when an amount is omitted in the journal, it will not+appear in the output. Similarly, if a conversion cost is implied but not+written, it will not appear in the output.++You can use the -x/--explicit flag to force explicit display of all+amounts and costs. This can be useful for troubleshooting or for making+your journal more readable and robust against data entry errors. -x is+also implied by using any of -B,-V,-X,--value.++The -x/--explicit flag will cause any postings with a multi-commodity+amount (which can arise when a multi-commodity transaction has an+implicit amount) to be split into multiple single-commodity postings,+keeping the output parseable.++To see more details — not just inferred amounts and costs, but also lot+subaccounts and postings, and the hidden tags that hledger adds to+classify things — use -a/--all, which is equivalent to+--explicit --lots --verbose-tags.++print layout++By default, print aligns posting amounts so that their decimal mark is+at column 53 (or would be if they had a decimal mark). If needed, it+will shift a transaction's amounts further to the right to ensure at+least 2 spaces between account names and amounts. Also, any balance+assertion/assignment operators (=, =* etc.) are aligned to the right of+the posting amounts; and the assertion/assignment amounts will be+aligned by their decimal marks.++You can customise this with --layout:++- --layout=COL — sets a different target column for posting amounts'+ decimal mark+- --layout=hledger1 — use hledger 1 layout (right-aligned posting+ amounts in each transaction).++If you want to change the default, put something like this in+~/.hledger.conf:++[print]+--layout=hledger1++Other print-like commands (close, import, rewrite, add) also accept+--layout.++print amount style++Amounts will be displayed mostly in their commodity's display style,+with standardised symbol placement, decimal mark, and digit group marks.+This does not apply to their decimal digits; print normally shows the+same decimal digits that are recorded in each journal entry. (Calculated+amounts with a repeating decimal, eg from converting 10 min to hours,+are shown with 8 decimal places.)++You can override the decimal precisions with print's special --round+option. --round tries to show amounts with their commodities' standard+decimal precisions, increasingly strongly:++- --round=none show amounts with original precisions (default)+- --round=soft add/remove decimal zeros in amounts (except costs)+- --round=hard round amounts (except costs), possibly hiding significant+ digits+- --round=all round all amounts and costs++soft is good for non-lossy cleanup, displaying more consistent decimals+where possible, without making entries unbalanced.++hard or all can be good for stronger cleanup, when decimal rounding is+wanted. Note rounding can produce unbalanced journal entries, perhaps+requiring manual fixup.++print parseability++Usually, print's output is a valid hledger journal, which you can pipe+into a second hledger command for further processing. This is sometimes+convenient for rewriting journal entries:++# Make today's shopping entry explicit. (-f - means read from standard input.)+$ hledger print date:today desc:shop | hledger -f- print -x++or for achieving certain kinds of query:++# Show running total of food expenses paid from cash.+$ hledger print assets:cash | hledger -f- reg expenses:food++But here are some things which can cause print's output to become+unparseable:++- --round (see above) can disrupt transaction balancing.+- Account aliases or pivoting can disrupt account names, balance+ assertions, or balance assignments.+- Value reporting also can disrupt balance assertions or balance+ assignments.+- Auto postings can generate too many amountless postings.+- --infer-costs or --infer-equity can generate too-complex redundant+ costs.+- Because print always shows transactions in date order, balance+ assertions involving non-date-ordered transactions (and same-day+ postings) could be disrupted.++Also, printing a subset of journal entries can disrupt validation of+balance assertions or lot entries. And print does not reproduce+directives (unless --export is used). Lot entries are printed with their+inferred cost basis annotations, so they can still be read without the+commodity's lots: declaration when the default cost basis method is+used; but with other methods, or lots: NONE accounts, the missing+declarations will change how they are read. (--export output keeps lot+entries as written, since it reproduces the declarations.) To suppress+errors from these, we often use the -I flag (short for+--ignore-assertions --ignore-lots). So any time you are reading from+standard input with -f-, consider adding -I also.++print export mode++With --export, print reproduces the whole journal in its original order,+with directives, top-level comment lines and comment blocks preserved+verbatim, and with each transaction shown as print normally shows it (so+-x, --round, --layout etc. still apply). Blank lines are normalised:+there is one blank line between transactions, and between groups of+directive or comment lines. The output can be read by hledger as an+equivalent journal, so this is the mode to use when reformatting or+regenerating a journal file. Some details:++- Included files are inlined at the position of their include directive,+ and the include line itself is dropped. If you want to preserve a+ multi-file structure rather than flattening it, currently the best way+ is: comment out the include directives (they will be preserved as+ comments), export each file individually, then uncomment the include+ directives in the exported main file. (A file which depends on+ directives in its parent file, such as Y or decimal-mark, might need+ those added temporarily while it is exported.)+- apply account, alias and their end directives are dropped, since their+ effect is already applied to the account names shown. (An account+ declaration inside an apply account block is reproduced as written,+ without the parent account prefix.)+- Directives which hledger ignores (for compatibility with Ledger) are+ not exported.+- By default, periodic transaction rules (~) and auto posting rules (=)+ are exported as directives. With --forecast and/or --auto, the+ generated transactions (at the end of the output) and postings are+ exported instead, and the rules are not. In other words, these flags+ materialise the rules. Postings generated by --infer-equity are+ exported too. (In Beancount output, these rules are never exported,+ only whatever has been generated.)+- A query still selects which transactions are shown, but all directives+ and comments are kept.+- Transactions from non-journal files (eg an included CSV file) are+ added at the end.+- The journal (default), ledger and beancount output formats are+ supported. With -O ledger, transactions use Ledger's lot syntax, and+ directives which hledger accepts but Ledger does not (decimal-mark, a+ one-line commodity directive with an amount, a periodic transaction+ rule with a description, an auto posting rule with *N amount+ multipliers) are commented out, with an explanatory comment. Other+ hledger-specific syntax may remain; see Ledger output. With+ -O beancount, Beancount option, commodity, open and price directives+ are generated from the journal's declarations and data, other+ directives (which have no Beancount equivalent) are dropped, and+ comments are converted to Beancount comments; see Beancount output.+ Note for both Ledger and Beancount, manual fixups may still be+ required in some cases; but the export will be a good start.++print, other features++With -B/--cost, amounts with costs are shown converted to cost.++With --invert, posting amounts are shown with their sign flipped. It+could be useful if you have accidentally recorded some transactions with+the wrong signs.++With --new, print shows only transactions it has not seen on a previous+run. This uses the same deduplication system as the import command. (See+import's docs for details.)++With -m DESC/--match=DESC, print shows one recent transaction whose+description is most similar to DESC. DESC should contain at least two+characters. If there is no similar-enough match, no transaction will be+shown and the program exit code will be non-zero.++With --locations, print adds the source file and line number to every+transaction, as a tag.++print output format++This command also supports the output destination and output format+options The output formats supported are journal (the default; txt is+also accepted), ledger, beancount, csv, tsv, html, fods, json and sql.++The ledger format is currently the same as journal except it renders+amounts' cost basis using Ledger's lot syntax ([DATE] (LABEL) {COST})+instead of hledger's ({DATE, "LABEL", COST}).++The beancount format tries to produce Beancount-compatible output, as+follows:++- Transaction and postings with unmarked status are converted to cleared+ (*) status.+- Transactions' payee and note are backslash-escaped and+ double-quote-escaped and wrapped in double quotes.+- Transaction and posting tags are converted to Beancount metadata+ lines.+- Commodity symbols are converted to upper case, and a small number of+ currency symbols like $ are converted to the corresponding currency+ names.+- Account name parts are capitalised and unsupported characters are+ replaced with -. The first part must be one of Assets, Liabilities,+ Equity, Income or Expenses; if it is not, but the account's type is+ known (declared or inferred), the corresponding one of those is+ prepended; otherwise an error is raised. (Or, use --alias options to+ bring your accounts into compliance.)+- Balance assignments are converted to explicit amounts.+- Virtual and balanced virtual postings are dropped.++By default only transactions are shown. With --export, the directives+Beancount needs are also generated: options (a commented-out tolerance+option, and operating_currency for the currencies used in costs), a+commodity directive for each declared commodity, an open directive for+each declared or used account (on the account's earliest posting date,+or the earliest transaction date), and price directives. Account and+commodity tags become metadata on those directives, and an account's+lots: tag becomes the Beancount booking method. Other hledger directives+are dropped, and top-level comments are converted to Beancount comments.++Here's an example of print's CSV output:++$ hledger print -Ocsv+"txnidx","date","date2","status","code","description","comment","account","amount","commodity","debit","credit","posting-status","posting-comment"+"1","2008/01/01","","","","income","","assets:bank:checking","1","$","1","","",""+"1","2008/01/01","","","","income","","income:salary","-1","$","","1","",""+"2","2008/06/01","","","","gift","","assets:bank:checking","1","$","1","","",""+"2","2008/06/01","","","","gift","","income:gifts","-1","$","","1","",""+"3","2008/06/02","","","","save","","assets:bank:saving","1","$","1","","",""+"3","2008/06/02","","","","save","","assets:bank:checking","-1","$","","1","",""+"4","2008/06/03","","*","","eat & shop","","expenses:food","1","$","1","","",""+"4","2008/06/03","","*","","eat & shop","","expenses:supplies","1","$","1","","",""+"4","2008/06/03","","*","","eat & shop","","assets:cash","-2","$","","2","",""+"5","2008/12/31","","*","","pay off","","liabilities:debts","1","$","1","","",""+"5","2008/12/31","","*","","pay off","","assets:bank:checking","-1","$","","1","",""++- There is one CSV record per posting, with the parent transaction's+ fields repeated.+- The "txnidx" (transaction index) field shows which postings belong to+ the same transaction. (This number might change if transactions are+ reordered within the file, files are parsed/included in a different+ order, etc.)+- The amount is separated into "commodity" (the symbol) and "amount"+ (numeric quantity) fields.+- The numeric amount is repeated in either the "debit" or "credit"+ column, for convenience. (Those names are not accurate in the+ accounting sense; it just puts zero or greater amounts under debit and+ negative amounts under credit.)
+ Hledger/Cli/Commands/Quickref.hs view
@@ -0,0 +1,67 @@+{-|++The quick reference card: a compact overview of hledger's most useful+commands, flags, and concepts, shown by @hledger help quickref@.++-}++{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Quickref (+ showQuickref+) where++import Data.List (isPrefixOf, isSuffixOf)+import System.Console.ANSI (setSGRCode, SGR(..), Underlining(..))++import Hledger+import Hledger.Cli.CliOptions (prognameandversionnoarch)++-- | The quick reference card, from quickref.txt in the hledger package directory.+quickrefcontent :: String+quickrefcontent = $(embedFileRelative "quickref.txt")++-- | Print the quick reference card, styling it a little when color is enabled.+showQuickref :: IO ()+showQuickref = do+ usecolor <- useColorOnStdout+ runPager $ styleQuickref usecolor quickrefcontent++-- | Render the card. The program name and version are added right-aligned on+-- the title line. When color is enabled: the title line gets hledger's usual+-- bold colour gradient (and the version a faint gradient), labels in the margin+-- (the first 18 columns) are faint, top-level headings are also underlined (up to+-- their first : or ,), a heading followed by just a parenthesised note is all faint,+-- and the commands, flags etc. beyond the margin are left normal, except parentheses,+-- which are faint.+styleQuickref :: Bool -> String -> String+styleQuickref usecolor s = unlines $ case lines s of+ [] -> []+ title:rest -> titleline title : map styleline rest+ where+ version = prognameandversionnoarch+ -- align the version's right edge with the widest line of the card+ cardwidth = maximum $ map length $ lines s+ titleline t = titleAndVersionLine cardwidth t version+ labelwidth = 18+ styleheading = faint'+ styleline l+ | not usecolor = l+ | all (==' ') label = label <> dimparens content+ | isnoteheading = stylelabel l+ | otherwise = stylelabel label <> dimparens content+ where+ -- eg "Common flags: (hledger -h ... to see all)"+ isnoteheading = case break (==':') l of+ (_:_, _:rest) -> let note = dropWhile (==' ') rest in "(" `isPrefixOf` note && ")" `isSuffixOf` note+ _ -> False+ (label, content) = splitAt labelwidth l+ -- an indented sub-label is just faint; a top-level heading's name is also underlined+ stylelabel t@(' ':_) = styleheading t+ stylelabel t = underline' (styleheading name) <> styleheading rest+ where (name, rest) = break (`elem` (",:" :: String)) t+ dimparens = concatMap (\c -> if c `elem` "()" then styleheading [c] else [c])++-- | Wrap a string in ANSI codes to switch single underlining on and off.+underline' :: String -> String+underline' s = setSGRCode [SetUnderlining SingleUnderline] <> s <> setSGRCode [SetUnderlining NoUnderline]
+ Hledger/Cli/Commands/Register.hs view
@@ -0,0 +1,352 @@+{-|++A ledger-compatible @register@ command.++-}++{-# LANGUAGE CPP #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Register (+ registermode+ ,register+ ,postingsReportAsText+ ,postingsReportItemAsText+ -- ,showPostingWithBalanceForVty+ ,tests_Register+) where++import Data.Default (def)+import Data.Maybe (fromMaybe, isJust)+import Data.Text (Text)+import Data.Map qualified as Map+import Data.Text qualified as T+import Data.Text.Lazy qualified as TL+import Data.Text.Lazy.Builder qualified as TB+import Safe (readMay)+import System.Console.CmdArgs.Explicit (flagNone, flagReq)++import Hledger.Utils.I18n qualified as I18n+import Hledger hiding (per)+import Hledger.Write.Csv (CSV, printCSV, printTSV)+import Hledger.Write.Ods (printFods)+import Hledger.Write.Html (titledTableHtml, htmlAsLazyText, toHtml)+import Hledger.Write.Spreadsheet qualified as Spr+import Hledger.Cli.Chart (chartFlag, chartRequested, postingsReportAsChart, writeChart)+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils+import Hledger.Cli.Anchor (setAccountAnchor, dateCell)+import Text.Tabular.AsciiWide (Cell(..), Align(..), Properties(..), Header(Header, Group), renderRowB, textCell, tableBorders, borderSpaces)+import Data.List (sortBy)+import Data.Char (toUpper)+import Data.List.Extra (intersect)+import System.IO qualified as IO++registermode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Register.txt")+ ([flagNone ["cumulative"] (setboolopt "cumulative")+ (accumprefix ++ "show running total from report start date (default)")+ ,flagNone ["historical","H"] (setboolopt "historical")+ (accumprefix ++ "show historical running total/balance (includes postings before report start date)")+ ,flagNone ["average","A"] (setboolopt "average")+ "show running average of posting amounts instead of total (implies --empty)"+ ,let arg = "DESC" in+ flagReq ["match","m"] (\s opts -> Right $ setopt "match" s opts) arg+ ("fuzzy search for one recent posting with description closest to "++arg)+ ,flagNone ["related","r"] (setboolopt "related") "show postings' siblings instead"+ ,flagNone ["invert"] (setboolopt "invert") "display all amounts with reversed sign"+ ,flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "omit N leading account name parts"+ ,flagReq ["sort"] (\s opts -> Right $ setopt "sort" s opts) "FIELDS" + ("sort by: " <> sortKeysDescription+ <> ", or a comma-separated combination of these. For a descending sort, prefix with -. (Default: date)")+ ,flagReq ["width","w"] (\s opts -> Right $ setopt "width" s opts) "N"+ ("set output width (default: " +++#ifdef mingw32_HOST_OS+ show defaultWidth+#else+ "terminal width"+#endif+ ++ "). -wN,M sets description width as well."+ )+ ,flagNone ["align-all"] (setboolopt "align-all") "guarantee alignment across all lines (slower)"+ ,flagReq ["base-url"] (\s opts -> Right $ setopt "base-url" s opts) "URLPREFIX" "in html output, generate links to hledger-web, with this prefix. (Usually the base url shown by hledger-web; can also be relative.)"+ ,outputFormatFlag ["txt","csv","tsv","html","fods","json","svg"]+ ,outputFileFlag+ ,outputViewFlag+ ,chartFlag+ ])+ cligeneralflagsgroups1+ hiddenflags+ ([], Just $ argsFlag "[QUERY]")+ where+ accumprefix = "accumulation mode: "++-- | Print a (posting) register report.+register :: CliOpts -> Journal -> IO ()+register opts@CliOpts{rawopts_=rawopts, reportspec_=rspec} j+ -- match mode, print one recent posting most similar to given description, if any+ -- XXX should match similarly to print --match+ | Just desc <- maybestringopt "match" rawopts = do+ let ps = [p | (_,_,_,p,_) <- rpt]+ case similarPosting ps desc of+ Nothing -> error' $ "no postings found with description like " <> show desc+ Just p -> writeOutputLazyText opts $ postingsReportAsText opts [pri]+ where pri = (Just (postingDate p)+ ,Nothing+ ,tdescription <$> ptransaction p+ ,styleAmounts styles p+ ,styleAmounts styles nullmixedamt)+ -- chart+ | chartRequested opts = writeChart opts (Just $ render $ styleAmounts styles rpt) $+ postingsReportAsChart (journalAccountType j) (postingsReportStartBalances rspec j) (_rsReportOpts rspec) (effectiveTitle (_rsReportOpts rspec) "") $ styleAmounts styles rpt+ -- normal register report, list postings+ | otherwise = writeOutputLazyText opts $ render $ styleAmounts styles rpt+ where+ styles = journalCommodityStylesWith HardRounding j+ rpt = postingsReport rspec j+ render | fmt=="txt" = withTitle (_rsReportOpts rspec) . postingsReportAsText opts+ | fmt=="json" = toJsonText+ | fmt=="csv" = printCSV . postingsReportAsCsv opts+ | fmt=="tsv" = printTSV . postingsReportAsCsv opts+ | fmt=="html" =+ (<>"\n") . htmlAsLazyText .+ titledTableHtml (effectiveTitle (_rsReportOpts rspec) "") .+ map (map (fmap toHtml)) .+ postingsReportAsSpreadsheet opts oneLineNoCostFmt baseUrl query+ | fmt=="fods" =+ printFods IO.localeEncoding . Map.singleton (I18n.tr (translations_ (_rsReportOpts rspec)) "Register") .+ (,) (1,0) .+ postingsReportAsSpreadsheet opts oneLineNoCostFmt baseUrl query+ | otherwise = error' $ unsupportedOutputFormatError fmt -- PARTIAL:+ where fmt = outputFormatFromOpts opts+ baseUrl = balance_base_url_ $ _rsReportOpts rspec+ query = querystring_ $ _rsReportOpts rspec++postingsReportAsCsv :: CliOpts -> PostingsReport -> CSV+postingsReportAsCsv opts pr =+ case postingsReportAsSpreadsheet opts machineFmt Nothing [] pr of+ [] -> []+ rows@(headerrow : _) -> Spr.rawTableContent $ titleRows headerrow ++ rows+ where+ titleText = effectiveTitle (_rsReportOpts $ reportspec_ opts) ""+ titleRows headerrow+ | T.null titleText = []+ | otherwise = [Spr.horizontalSpan headerrow (Spr.headerCell titleText)]++-- ToDo: --layout=bare etc.+-- ToDo: Text output does not show headers, but Spreadsheet does+postingsReportAsSpreadsheet ::+ CliOpts -> AmountFormat -> Maybe Text -> [Text] ->+ PostingsReport -> [[Spr.Cell Spr.NumLines Text]]+postingsReportAsSpreadsheet opts fmt baseUrl query is =+ Spr.addHeaderBorders+ (map Spr.headerCell+ ["txnidx","date","code","description","account","amount","total"])+ :+ map (postingsReportItemAsRecord opts fmt baseUrl query) is++{- ToDo:+link txnidx to journal URL,+ however, requires Web.Widget.Common.transactionFragment+-}+postingsReportItemAsRecord ::+ (Spr.Lines border) =>+ CliOpts -> AmountFormat -> Maybe Text -> [Text] ->+ PostingsReportItem -> [Spr.Cell border Text]+postingsReportItemAsRecord opts@CliOpts{reportspec_=rspec} fmt baseUrl query (_, mperiod, _, p, b) =+ [idx,+ dateSpanCellOrDate,+ cell code, cell desc,+ setAccountAnchor baseUrl query (paccount p) $ cell acct,+ amountCell (pamount p),+ amountCell b]+ where+ cell = Spr.defaultCell+ idx = Spr.integerCell . maybe 0 tindex $ ptransaction p+ date = postingDate p -- XXX csv should show date2 with --date2+ -- With --period-titles=dates and a report interval, render the period as+ -- a full ISO date range string instead of the period start date.+ dateSpanCellOrDate = case (mperiod, period_titles_ $ _rsReportOpts rspec) of+ (Just per, PTDates) ->+ cell (showDateSpanFull (periodAsDateSpan per))+ _ ->+ (dateCell baseUrl query (paccount p) date) {Spr.cellType = Spr.TypeDate}+ code = maybe "" tcode $ ptransaction p+ desc = maybe "" tdescription $ ptransaction p+ -- (account names have already been clipped to the depth limit by postingsReport)+ acct = bracket . dropAcct $ paccount p+ where+ dropAcct = accountNameDrop (fromMaybe 0 $ readMay =<< maybestringopt "drop" (rawopts_ opts))+ bracket = case preal p of+ BalancedVirtualPosting -> wrap "[" "]"+ VirtualPosting -> wrap "(" ")"+ _ -> id+ -- Since postingsReport strips prices from all Amounts when not used, we can display prices.+ amountCell amt =+ wbToText <$> Spr.cellFromMixedAmount fmt (Spr.Class "amount", amt)++-- | Render a register report as plain text suitable for console output.+postingsReportAsText :: CliOpts -> PostingsReport -> TL.Text+postingsReportAsText opts = TB.toLazyText .+ postingsOrTransactionsReportAsText alignAll opts (postingsReportItemAsText opts) itemamt itembal+ where+ alignAll = boolopt "align-all" $ rawopts_ opts+ itemamt (_,_,_,Posting{pamount=a},_) = a+ itembal (_,_,_,_,a) = a++-- | Render one register report line item as plain text. Layout is like so:+-- @+-- <---------------- width (specified, terminal width, or 80) -------------------->+-- date (10) description account amount (12) balance (12)+-- DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA+-- @+-- If description's width is specified, account will use the remaining space.+-- Otherwise, description and account divide up the space equally.+--+-- With a report interval, the layout is like so:+-- @+-- <---------------- width (specified, terminal width, or 80) -------------------->+-- date (21) account amount (12) balance (12)+-- DDDDDDDDDDDDDDDDDDDDD aaaaaaaaaaaaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA+-- @+--+-- date and description are shown for the first posting of a transaction only.+--+-- Returns a string which can be multi-line, eg if the running balance+-- has multiple commodities. Does not yet support formatting control+-- like balance reports.+--+-- Also returns the natural width (without padding) of the amount and balance+-- fields.+postingsReportItemAsText :: CliOpts -> Int -> Int+ -> (PostingsReportItem, [WideBuilder], [WideBuilder])+ -> TB.Builder+postingsReportItemAsText opts@CliOpts{reportspec_=rspec} preferredamtwidth preferredbalwidth ((mdate, mperiod, mdesc, p, _), amt, bal) =+ table <> TB.singleton '\n'+ where+ table = renderRowB def{tableBorders=False, borderSpaces=False} . Group NoLine $ map Header+ [ textCell TopLeft $ fitText (Just datewidth) (Just datewidth) True True date+ , spacerCell+ , textCell TopLeft $ fitText (Just descwidth) (Just descwidth) True True desc+ , spacerCell2+ , textCell TopLeft $ fitText (Just acctwidth) (Just acctwidth) True True acct+ , spacerCell2+ , Cell TopRight $ map (pad amtwidth) amt+ , spacerCell2+ , Cell BottomRight $ map (pad balwidth) bal+ ]+ spacerCell = Cell BottomLeft [WideBuilder (TB.singleton ' ') 1]+ spacerCell2 = Cell BottomLeft [WideBuilder (TB.fromString " ") 2]+ pad fullwidth amt' = WideBuilder (TB.fromText $ T.replicate w " ") w <> amt'+ where w = fullwidth - wbWidth amt'+ -- calculate widths+ (totalwidth,mdescwidth) = registerWidthsFromOpts opts+ ph = period_titles_ $ _rsReportOpts rspec+ datewidth = case mperiod of+ Nothing -> 10+ Just per -> case ph of+ PTDates -> 22 -- YYYY-MM-DD..YYYY-MM-DD+ PTCompact -> periodTextWidth per+ date = case mperiod of+ Just per -> if isJust mdate+ then case ph of+ PTDates -> showDateSpanFull (periodAsDateSpan per)+ PTCompact -> showPeriod per+ else ""+ Nothing -> maybe "" showDate mdate+ (amtwidth, balwidth)+ | shortfall <= 0 = (preferredamtwidth, preferredbalwidth)+ | otherwise = (adjustedamtwidth, adjustedbalwidth)+ where+ mincolwidth = 2 -- columns always show at least an ellipsis+ maxamtswidth = max 0 (totalwidth - (datewidth + 1 + mincolwidth + 2 + mincolwidth + 2 + 2))+ shortfall = (preferredamtwidth + preferredbalwidth) - maxamtswidth+ amtwidthproportion = fromIntegral preferredamtwidth / fromIntegral (preferredamtwidth + preferredbalwidth)+ adjustedamtwidth = round $ amtwidthproportion * fromIntegral maxamtswidth+ adjustedbalwidth = maxamtswidth - adjustedamtwidth++ remaining = totalwidth - (datewidth + 1 + 2 + amtwidth + 2 + balwidth)+ (descwidth, acctwidth)+ | isJust mperiod = (0, remaining - 2)+ | otherwise = (w, remaining - 2 - w)+ where+ w = fromMaybe ((remaining - 2) `div` 2) mdescwidth++ -- gather content+ desc = fromMaybe "" mdesc+ -- (account names have already been clipped to the depth limit by postingsReport)+ acct = parenthesise . elideAccountName awidth . dropAcct $ paccount p+ where+ dropAcct = accountNameDrop (fromMaybe 0 $ readMay =<< maybestringopt "drop" (rawopts_ opts))+ (parenthesise, awidth) = case preal p of+ BalancedVirtualPosting -> (wrap "[" "]", acctwidth-2)+ VirtualPosting -> (wrap "(" ")", acctwidth-2)+ _ -> (id,acctwidth)++-- for register --match:++-- Identify the closest recent match for this description in the given date-sorted postings.+similarPosting :: [Posting] -> String -> Maybe Posting+similarPosting ps desc =+ let matches =+ sortBy compareRelevanceAndRecency+ $ filter ((> threshold).fst)+ [(maybe 0 (\t -> compareDescriptions desc (T.unpack $ tdescription t)) (ptransaction p), p) | p <- ps]+ where+ compareRelevanceAndRecency (n1,p1) (n2,p2) = compare (n2,postingDate p2) (n1,postingDate p1)+ threshold = 0+ in case matches of [] -> Nothing+ m:_ -> Just $ snd m++-- -- Identify the closest recent match for this description in past transactions.+-- similarTransaction :: Journal -> Query -> String -> Maybe Transaction+-- similarTransaction j q desc =+-- case historymatches = transactionsSimilarTo j q desc of+-- ((,t):_) = Just t+-- [] = Nothing++compareDescriptions :: String -> String -> Double+compareDescriptions s t = compareStrings s' t'+ where s' = simplify s+ t' = simplify t+ simplify = filter (not . (`elem` ("0123456789"::String)))++-- | Return a similarity measure, from 0 to 1, for two strings.+-- This is Simon White's letter pairs algorithm from+-- http://www.catalysoft.com/articles/StrikeAMatch.html+-- with a modification for short strings.+compareStrings :: String -> String -> Double+compareStrings "" "" = 1+compareStrings [_] "" = 0+compareStrings "" [_] = 0+compareStrings [a] [b] = if toUpper a == toUpper b then 1 else 0+compareStrings s1 s2 = 2.0 * fromIntegral i / fromIntegral u+ where+ i = length $ intersect pairs1 pairs2+ u = length pairs1 + length pairs2+ pairs1 = wordLetterPairs $ uppercase s1+ pairs2 = wordLetterPairs $ uppercase s2++wordLetterPairs = concatMap letterPairs . words++letterPairs (a:b:rest) = [a,b] : letterPairs (b:rest)+letterPairs _ = []++-- tests++tests_Register = testGroup "Register" [++ testGroup "postingsReportAsText" [+ testCase "unicode in register layout" $ do+ j <- readJournal'' "2009/01/01 * медвежья шкура\n расходы:покупки 100\n актив:наличные\n"+ let rspec = defreportspec+ (TL.unpack . postingsReportAsText defcliopts $ postingsReport rspec j)+ @?=+ unlines+ ["2009-01-01 медвежья шкура расходы:покупки 100 100"+ ," актив:наличные -100 0"]+ ]++ ]
+ Hledger/Cli/Commands/Register.txt view
@@ -0,0 +1,195 @@+register++(reg)++Show postings & running total across accounts.++Flags:+ --cumulative accumulation mode: show running total from report+ start date (default)+ -H --historical accumulation mode: show historical running+ total/balance (includes postings before report+ start date)+ -A --average show running average of posting amounts instead+ of total (implies --empty)+ -m --match=DESC fuzzy search for one recent posting with+ description closest to DESC+ -r --related show postings' siblings instead+ --invert display all amounts with reversed sign+ --drop=N omit N leading account name parts+ --sort=FIELDS sort by: date, desc, account, amount, absamount,+ or a comma-separated combination of these. For a+ descending sort, prefix with -. (Default: date)+ -w --width=N set output width (default: terminal width). -wN,M+ sets description width as well.+ --align-all guarantee alignment across all lines (slower)+ --base-url=URLPREFIX in html output, generate links to hledger-web,+ with this prefix. (Usually the base url shown by+ hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ txt, csv, tsv, html, fods, json, svg.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ --view write output to FILE, or to view.FMT in hledger's+ cache directory, and open it in the system's+ default viewer for its format (eg a web browser for+ html). The default format is html.+ --chart[=net,SCALE] show a chart: instead of the table (txt), above+ it (html), or as data (csv, tsv, json). net: also+ draw the net total (a line, or marks in text+ charts). SCALE: the amount that fills the chart (eg+ 1000 or 1000 USD; one per commodity), for+ comparable charts.++The register command displays matched postings, across all accounts, in+date order, with their running total or running historical balance. (See+also the aregister command, which shows matched transactions in a+specific account.)++register normally shows line per posting, but note that multi-commodity+amounts will occupy multiple lines (one line per commodity).++It is typically used with a query selecting a particular account, to see+that account's activity:++$ hledger register checking+2008/01/01 income assets:bank:checking $1 $1+2008/06/01 gift assets:bank:checking $1 $2+2008/06/02 save assets:bank:checking $-1 $1+2008/12/31 pay off assets:bank:checking $-1 0++With --date2, it shows and sorts by secondary date instead.++Postings with a zero amount (including amounts inferred from a balance+assignment) are not shown by default; use the --empty/-E flag to see+them.++For performance reasons, column widths are chosen based on the first+1000 lines; this means unusually wide values in later lines can cause+visual discontinuities as column widths are adjusted. If you want to+ensure perfect alignment, at the cost of more time and memory, use the+--align-all flag.++The --historical/-H flag adds the balance from any undisplayed prior+postings to the running total. This is useful when you want to see only+recent activity, with a historically accurate running balance:++$ hledger register checking -b 2008/6 --historical+2008/06/01 gift assets:bank:checking $1 $2+2008/06/02 save assets:bank:checking $-1 $1+2008/12/31 pay off assets:bank:checking $-1 0++The --depth option limits the amount of sub-account detail displayed.++The --drop option will trim leading segments from account names.++The --average/-A flag shows the running average posting amount instead+of the running total (so, the final number displayed is the average for+the whole report period). This flag implies --empty (see below). It is+affected by --historical. It works best when showing just one account+and one commodity.++The --related/-r flag shows the other postings in the transactions of+the postings which would normally be shown.++The --invert flag negates all amounts. For example, it can be used on an+income account where amounts are normally displayed as negative numbers.+It's also useful to show postings on the checking account together with+the related account:++The --sort=FIELDS flag sorts by the fields given, which can be any of+account, amount, absamount, date, or desc/description, optionally+separated by commas. For example, --sort account,amount will group all+transactions in each account, sorted by transaction amount. Each field+can be negated by a preceding -, so --sort -amount will show+transactions ordered from smallest amount to largest amount.++$ hledger register --related --invert assets:checking++With a reporting interval, register shows summary postings, one per+interval, aggregating the postings to each account:++$ hledger register --monthly income+2008/01 income:salary $-1 $-1+2008/06 income:gifts $-1 $-2++Here too, periods with no activity, and summary postings with a zero+amount, are not shown by default; use the --empty/-E flag to see them:++$ hledger register --monthly income -E+2008/01 income:salary $-1 $-1+2008/02 0 $-1+2008/03 0 $-1+2008/04 0 $-1+2008/05 0 $-1+2008/06 income:gifts $-1 $-2+2008/07 0 $-2+2008/08 0 $-2+2008/09 0 $-2+2008/10 0 $-2+2008/11 0 $-2+2008/12 0 $-2++Often, you'll want to see just one line per interval. The --depth option+helps with this, causing subaccounts to be aggregated:++$ hledger register --monthly assets --depth 1+2008/01 assets $1 $1+2008/06 assets $-1 0+2008/12 assets $-1 $-1++Note when using report intervals, if you specify start/end dates these+will be adjusted outward if necessary to contain a whole number of+intervals. This ensures that the first and last intervals are full+length and comparable to the others in the report.++If you have a deeply nested account tree some reports might benefit from+trimming leading segments from the account names using --drop.++$ hledger register --monthly income --drop 1+2008/01 salary $-1 $-1+2008/06 gifts $-1 $-2++With -m DESC/--match=DESC, register does a fuzzy search for one recent+posting whose description is most similar to DESC. DESC should contain+at least two characters. If there is no similar-enough match, no posting+will be shown and the program exit code will be non-zero.++Custom register output++register normally uses the full terminal width (or 80 columns if it+can't detect that). You can override this with the --width/-w option.++The description and account columns normally share the space equally+(about half of (width - 40) each). You can adjust this by adding a+description width as part of --width's argument, comma-separated:+--width W,D . Here's a diagram (won't display correctly in --help):++<--------------------------------- width (W) ---------------------------------->+date (10) description (D) account (W-41-D) amount (12) balance (12)+DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA++and some examples:++$ hledger reg # use terminal width (or 80 on windows)+$ hledger reg -w 100 # use width 100+$ hledger reg -w 100,40 # set overall width 100, description width 40++This command also supports the output destination and output format+options The output formats supported are txt, csv, tsv, html, fods,+json, and svg.++Register charts++With --chart, or with svg output (-o FILE.svg), it shows a chart+instead. Without a report interval, this is the running total (or+average) after each posting, as a line over time; with postings to+several accounts, each account's own running total is shown too, in its+account type's colour (starting from its balance before the report+period, with -H), at most eight of them, the smallest combined into+"other". A text chart has a row per posting, with the accounts' running+totals stacked. With a report interval, it is each account's amount in+each period, as stacked bars, with the period's total. Charts draw the+overall running total (with several accounts) or the periods' totals+only with --chart=net. With --chart -O csv (or tsv or json) it shows the+chart's data. See also Balance charts.
+ Hledger/Cli/Commands/Repl.txt view
@@ -0,0 +1,91 @@+repl++Start an interactive prompt for running hledger commands. Input files+are reloaded only when they change, so commands run faster.++Flags:+ --no-watch disable automatic reloading of changed input+ files, config aliases and addon commands++hledger repl starts a read-eval-print loop (REPL) where you can enter+commands interactively. As with the run command, each input file (or+each input file/input options combination) is parsed just once, so+commands will run more quickly than if you ran them individually at the+command line.++The input file(s) specified for the repl command will be used throughout+the session; but you can override this temporarily by specifying new -f+options for a command.++Before running a command, any input files which have changed on disk are+automatically reloaded (including CSV rules files). Also command aliases+are reloaded if the config file has changed, and addon commands are+re-detected if PATH's contents have changed. The --no-watch flag+disables all of this reloading, so as to work with a stable snapshot of+the data, or to avoid file/directory polling on a slow network drive.++Any other general flags given to repl - input, reporting, or display+flags such as -I, --strict, --alias, -b/-e, --depth, --cost, --value,+--color - are also applied to every command you run. A command can still+override them by specifying its own flags.++The command syntax is the same as with run:++- enter one hledger command at a time, without the usual hledger first+ word+- empty lines and comment text from # to end of line are ignored+- enclose arguments in quotes if they contain spaces.++Use help (or h) to show the quick reference, or help commands to list+commands. Addons in PATH and command aliases defined in a config file+can also be used. Generally repl should feel much like using hledger at+the command line. But repl requires full command names or official+abbreviations (it does not recognise ad hoc abbreviations).++To run a single shell command, type ! SHELLCMD (eg ! ls or+! git status).++While it is running, the REPL remembers your command history, and you+can navigate in the usual ways:++- Keypad or Emacs navigation keys to edit the current command line+- UP/DOWN or control-P/control-N to step back/forward through history+- control-R to search for a past command+- TAB to complete file paths.++You can type control-C to cancel a long-running command (but only once;+typing it a second time will exit the REPL).++In most shells you can type control-Z to temporarily exit to the shell+(and then fg to return to the REPL).++To exit the REPL, use control-D or q or quit or exit.++Examples++Start the REPL and enter some commands:++$ hledger repl +hledger 1.52+Enter hledger commands. To exit, enter 'quit' or 'exit', or send EOF / control-d.+2025> stats+Main file : .../2025.journal+...+2025> stats -f 2024/2024.journal +Main file : .../2024.journal+...+2025> stats+Main file : .../2025.journal+...++or:++$ hledger repl -f some.journal+hledger 1.52+Enter hledger commands. To exit, enter 'quit' or 'exit', or send EOF / control-d.+some> bs+...+some> print -b 'last week'+...+some> bs -f other.journal+...
+ Hledger/Cli/Commands/Rewrite.hs view
@@ -0,0 +1,149 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE ViewPatterns #-}++module Hledger.Cli.Commands.Rewrite (+ rewritemode+ ,rewrite+)+where++import Control.Monad (unless)+import Data.Either (partitionEithers)+import Data.Functor.Identity+import Data.List (dropWhileEnd, find, sortOn)+import Data.Map qualified as M+import Data.Maybe (isJust)+import Data.Text (Text)+import Data.Text qualified as T+import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils (writeOutput)+import Hledger.Cli.Commands.Print+import System.Console.CmdArgs.Explicit+import System.IO (hPutStr, stderr)+import Text.Megaparsec hiding (pos1)+import Text.Printf (printf)+import Data.Algorithm.DiffContext qualified as D+import Text.PrettyPrint (render, text)++rewritemode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Rewrite.txt")+ [flagReq ["add-posting"] (\s opts -> Right $ setopt "add-posting" s opts) "'ACCT AMTEXPR'"+ "add a posting to ACCT, which may be parenthesised. AMTEXPR is either a literal amount, or *N which means the transaction's first matched amount multiplied by N (a decimal number). Two spaces separate ACCT and AMTEXPR."+ ,flagNone ["diff"] (setboolopt "diff") "generate diff suitable as an input for patch tool"+ ,flagNone ["verbose-tags"] (setboolopt "verbose-tags") "add tags indicating generated/modified data"+ ,layoutFlag+ ]+ cligeneralflagsgroups1+ hiddenflags+ ([], Just $ argsFlag "[QUERY] --add-posting \"ACCT AMTEXPR\" ...")++-- TODO regex matching and interpolating matched name in replacement+-- TODO interpolating match groups in replacement+-- TODO allow using this on unbalanced entries, eg to rewrite while editing++rewrite opts@CliOpts{rawopts_=rawopts,reportspec_=rspec} j@Journal{jtxns=ts} = do+ -- rewrite matched transactions+ let+ today = _rsDay rspec+ verbosetags = boolopt "verbose-tags" rawopts+ modifiers = transactionModifierFromOpts opts : jtxnmodifiers j+ let j' = j{jtxns=either error' id $ modifyTransactions (journalAccountType j) (journalInheritedAccountTags j) mempty today verbosetags modifiers ts} -- PARTIAL:+ -- run the print command, showing all transactions, or show diffs+ printOrDiff rawopts opts{reportspec_=rspec{_rsQuery=Any}} j j'++-- | Build a 'TransactionModifier' from any query arguments and --add-posting flags+-- provided on the command line, or throw a parse error.+transactionModifierFromOpts :: CliOpts -> TransactionModifier+transactionModifierFromOpts CliOpts{rawopts_=rawopts} =+ TransactionModifier{tmquerytxt=q, tmpostingrules=ps}+ where+ q = T.pack . unwords . map quoteIfNeeded $ listofstringopt "args" rawopts+ ps = map (parseposting . T.pack) $ listofstringopt "add-posting" rawopts+ parseposting t = either (error' . errorBundlePretty) id ep -- PARTIAL:+ where+ ep = runIdentity (runJournalParser (tmpostingrulep Nothing <* eof) t')+ t' = " " <> t <> "\n" -- inject space and newline for proper parsing++printOrDiff :: RawOpts -> (CliOpts -> Journal -> Journal -> IO ())+printOrDiff opts+ | boolopt "diff" opts = diffOutput (layoutFromRawOpts opts)+ | otherwise = flip (const print')++-- | How many lines of unchanged context to show around each change,+-- as with diff -U3. patch and similar tools need some context to be+-- able to apply a patch.+diffContextLines :: Int+diffContextLines = 3++-- | A replacement of a source file's lines [start..end) with new lines.+type Edit = (Int, Int, [Text])++-- | Show the changes between two journals as a unified diff, suitable+-- for piping to patch.+--+-- Only transactions which exist as journal entries in a file can be+-- patched. Changed transactions which don't - ones generated from CSV+-- or timeclock data, or by a periodic transaction rule - are left out+-- of the diff, and reported on stderr.+diffOutput :: PostingLayout -> CliOpts -> Journal -> Journal -> IO ()+diffOutput postinglayout opts j j' = do+ unless (null unpatchable) . hPutStr stderr $ unpatchableWarning unpatchable+ writeOutput opts . T.unpack . foldMap fileDiff $ M.toAscList editsbyfile+ where+ changed = [(transactionWithMostlyOriginalPostings False t, transactionWithMostlyOriginalPostings False t')+ | (t, t') <- zip (jtxns j) (jtxns j'), t /= t']+ -- collected per file, in no particular order; fileDiff sorts them+ (edits, unpatchable) = partitionEithers $ map txnEdit changed+ editsbyfile = M.fromListWith (++) edits++ -- The rewriting of a changed transaction, as a replacement of its lines in+ -- its source file; or, if it has no journal entry to replace, why not.+ txnEdit (t, t')+ -- A transaction generated by a periodic rule occupies no lines of its own;+ -- its source position is the rule's, which we must not overwrite.+ | isJust . lookup generatedTransactionTagName $ ttags t =+ Right "generated by a periodic transaction rule"+ -- Transactions read from CSV or timeclock data have a source line but no line range.+ | (SourcePos fp line _, SourcePos _ line' _) <- tsourcepos t, line' > line =+ Left (fp, [(unPos line, unPos line', newlines)])+ | otherwise = Right . T.pack $ "read from " <> sourceName (fst $ tsourcepos t)+ where+ -- showTransaction* adds a trailing blank line; the source lines don't include one.+ newlines = dropWhileEnd T.null . T.lines $ showTransactionWithLayout postinglayout t'++ fileDiff (fp, es) = case jftext <$> find ((== fp) . jfpath) (jfiles j) of+ Nothing -> ""+ Just contents -> unifiedDiff fp oldlines $ applyEdits (sortOn first3 es) oldlines+ where oldlines = T.lines contents++-- | Explain which changed transactions were left out of the diff, and why.+unpatchableWarning :: [Text] -> String+unpatchableWarning reasons = unlines $+ printf "warning: %d changed transaction%s not shown in the diff, having no journal entry to patch:"+ n (if n == (1::Int) then " is" else "s are" :: String)+ : [printf " %d %s" howmany reason | (reason, howmany) <- M.toAscList reasoncounts]+ where+ n = length reasons+ reasoncounts = M.fromListWith (+) [(T.unpack r, 1::Int) | r <- reasons]++-- | Replace line ranges in a list of lines. Edits are expected to be+-- sorted by start line and non-overlapping; any that aren't are skipped.+applyEdits :: [Edit] -> [Text] -> [Text]+applyEdits = go 1+ where+ go _ [] ls = ls+ go lineno ((start, end, new):es) ls+ | start < lineno || end < start = go lineno es ls+ | otherwise = before <> new <> go end es (drop (end-start) rest)+ where (before, rest) = splitAt (start-lineno) ls++-- | Render the differences between two versions of a file's lines as a+-- unified diff, with the standard amount of context. Returns the empty+-- text if there are no differences.+unifiedDiff :: FilePath -> [Text] -> [Text] -> Text+unifiedDiff fp old new+ | null hunks = ""+ | otherwise = T.pack . render $ D.prettyContextDiff (text fp) (text fp) (text . T.unpack . D.unnumber) hunks+ where hunks = D.getContextDiff (Just diffContextLines) old new
+ Hledger/Cli/Commands/Rewrite.txt view
@@ -0,0 +1,185 @@+rewrite++Print all transactions, adding auto postings to some of them. For now+the only rewrite available is adding new postings, like print --auto.++Flags:+ --add-posting='ACCT AMTEXPR' add a posting to ACCT, which may be+ parenthesised. AMTEXPR is either a literal+ amount, or *N which means the transaction's+ first matched amount multiplied by N (a+ decimal number). Two spaces separate ACCT+ and AMTEXPR.+ --diff generate diff suitable as an input for+ patch tool+ --verbose-tags add tags indicating generated/modified+ data+ --layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 - right-align amounts, as in+ hledger 1+ COL - align decimal marks at column+ COL (default: 53)++This is a start at a generic rewriter of transaction entries. It reads+the default journal and prints the transactions, like print, but adds+one or more specified postings to any transactions matching QUERY. The+posting amounts can be fixed, or a multiplier of the existing+transaction's first posting amount.++Examples:++$ hledger-rewrite.hs ^income --add-posting '(liabilities:tax) *.33 ; income tax' --add-posting '(reserve:gifts) $100'+$ hledger-rewrite.hs expenses:gifts --add-posting '(reserve:gifts) *-1"'+$ hledger-rewrite.hs -f rewrites.hledger++rewrites.hledger may consist of entries like:++= ^income amt:<0 date:2017+ (liabilities:tax) *0.33 ; tax on income+ (reserve:grocery) *0.25 ; reserve 25% for grocery+ (reserve:) *0.25 ; reserve 25% for grocery++Note the single quotes to protect the dollar sign from bash, and the two+spaces between account and amount.++More:++$ hledger rewrite [QUERY] --add-posting "ACCT AMTEXPR" ...+$ hledger rewrite ^income --add-posting '(liabilities:tax) *.33'+$ hledger rewrite expenses:gifts --add-posting '(budget:gifts) *-1"'+$ hledger rewrite ^income --add-posting '(budget:foreign currency) *0.25 JPY; diversify'++Argument for --add-posting option is a usual posting of transaction with+an exception for amount specification. More precisely, you can use '*'+(star symbol) before the amount to indicate that that this is a factor+for an amount of original matched posting. If the amount includes a+commodity name, the new posting amount will be in the new commodity;+otherwise, it will be in the matched posting amount's commodity.++Re-write rules in a file++During the run this tool will execute so called "Automated Transactions"+found in any journal it process. I.e instead of specifying this+operations in command line you can put them in a journal file.++$ rewrite-rules.journal++Make contents look like this:++= ^income+ (liabilities:tax) *.33++= expenses:gifts+ budget:gifts *-1+ assets:budget *1++Note that '=' (equality symbol) that is used instead of date in+transactions you usually write. It indicates the query by which you want+to match the posting to add new ones.++$ hledger rewrite -f input.journal -f rewrite-rules.journal > rewritten-tidy-output.journal++This is something similar to the commands pipeline:++$ hledger rewrite -f input.journal '^income' --add-posting '(liabilities:tax) *.33' \+ | hledger rewrite -f - expenses:gifts --add-posting 'budget:gifts *-1' \+ --add-posting 'assets:budget *1' \+ > rewritten-tidy-output.journal++It is important to understand that relative order of such entries in+journal is important. You can re-use result of previously added+postings.++Diff output format++To use this tool for batch modification of your journal files you may+find useful output in form of unified diff.++$ hledger rewrite --diff -f examples/sample.journal '^income' --add-posting '(liabilities:tax) *.33'++Output might look like:++--- /tmp/examples/sample.journal++++ /tmp/examples/sample.journal+@@ -28,13 +28,15 @@+ ; declare commodities:+ ; commodity $+ +-2008/01/01 income+- assets:bank:checking $1++2008-01-01 income++ assets:bank:checking $1+ income:salary++ (liabilities:tax) $0+ +-2008/06/01 gift+- assets:bank:checking $1++2008-06-01 gift++ assets:bank:checking $1+ income:gifts++ (liabilities:tax) $0+ + 2008/06/02 save+ assets:bank:saving $1++If you'll pass this through patch tool you'll get transactions+containing the posting that matches your query be updated. Note that+multiple files might be update according to list of input files+specified via --file options and include directives inside of these+files.++Changed transactions are re-rendered in print's standard format, so the+diff shows any reformatting as well as the postings you added: amounts+are realigned, and dates are written with - separators. Transactions you+didn't change are left exactly as they are. --layout selects the amount+alignment, so choosing one which matches your journal will keep the diff+small. Here is the example above again, with --layout=26 to match this+journal's own alignment:++@@ -28,13 +28,15 @@+ ; declare commodities:+ ; commodity $+ +-2008/01/01 income++2008-01-01 income+ assets:bank:checking $1+ income:salary++ (liabilities:tax) $0+ +-2008/06/01 gift++2008-06-01 gift+ assets:bank:checking $1+ income:gifts++ (liabilities:tax) $0+ + 2008/06/02 save+ assets:bank:saving $1++Only transactions which exist as journal entries in a file can be+patched this way. Transactions read from other data formats, such as CSV+or timeclock, and transactions generated by a periodic transaction rule,+have no journal entry of their own; these are left out of the diff, and+reported on stderr. To rewrite those, convert them to journal entries+first, eg with hledger print or hledger import.++Be careful. Whole transaction being re-formatted in a style of output+from hledger print.++See also:++https://github.com/hledgerorg/hledger/issues/99++rewrite vs. print --auto++This command predates print --auto, and currently does much the same+thing, but with these differences:++- with multiple files, rewrite lets rules in any file affect all other+ files. print --auto uses standard directive scoping; rules affect only+ child files.++- rewrite's query limits which transactions can be rewritten; all are+ printed. print --auto's query limits which transactions are printed.++- rewrite applies rules specified on command line or in the journal.+ print --auto applies rules specified in the journal.
+ Hledger/Cli/Commands/Roi.hs view
@@ -0,0 +1,456 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ParallelListComp #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE TupleSections #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ViewPatterns #-}+{-|++The @roi@ command prints internal rate of return and time-weighted rate of return for an investment.++-}++module Hledger.Cli.Commands.Roi (+ roimode+ , roi+) where++import Control.Monad+import Data.Time.Calendar+import Text.Printf+import Data.Bifunctor (second)+import Data.List+import Data.Maybe (fromMaybe)+import Data.Decimal+import Data.Map qualified as M+import Data.Set qualified as S+import Data.Text qualified as T+import Data.Text.Lazy qualified as TL+import System.Console.CmdArgs.Explicit as CmdArgs+import System.IO (hFlush, stdout)++import Text.Tabular.AsciiWide as Tab++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils (warnIfLargeMultiPeriodReport, withTitle, writeOutput)+import Hledger.Cli.Xirr+++roimode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Roi.txt")+ [flagNone ["cashflow"] (setboolopt "cashflow") "show all amounts that were used to compute returns"+ ,flagReq ["investment"] (\s opts -> Right $ setopt "investment" s opts) "QUERY"+ "query to select your investment transactions"+ ,flagReq ["profit-loss","pnl"] (\s opts -> Right $ setopt "pnl" s opts) "QUERY"+ "query to select profit-and-loss or appreciation/valuation transactions (optional)"+ ]+ cligeneralflagsgroups1+ hiddenflags+ ([], Just $ argsFlag "[QUERY]")++-- One reporting span,+data OneSpan = OneSpan+ Day -- start date, inclusive+ Day -- end date, exclusive+ MixedAmount -- value of investment at the beginning of day on spanBegin_+ MixedAmount -- value of investment at the end of day on spanEnd_+ [(Day,MixedAmount)] -- all deposits and withdrawals (but not changes of value) in the DateSpan [spanBegin_,spanEnd_)+ [(Day,MixedAmount)] -- all PnL changes of the value of investment in the DateSpan [spanBegin_,spanEnd_)+ deriving (Show)++roi :: CliOpts -> Journal -> IO ()+roi opts@CliOpts{rawopts_=rawopts, reportspec_=rspec@ReportSpec{_rsReportOpts=ropts@ReportOpts{..}}} j = do+ warnIfLargeMultiPeriodReport rspec j+ -- We may be converting posting amounts to value, per hledger_options.m4.md "Effect of --value on reports".+ let+ -- lbl = lbl_ "roi"+ today = _rsDay rspec+ priceOracle = journalPriceOracle infer_prices_ j+ styles = journalCommodityStylesWith HardRounding j+ mixedAmountValue periodlast date =+ -- These calculations can generate very precise decimals. To avoid showing too many digits:+ -- If we have no style for the valuation commodity, generate one that will limit the precision ?+ -- But it's not easy to find out the valuation commodity (or commodities) here if it's implicit,+ -- as that information is buried in the price graph.+ -- Instead, do what we don't like to do: hard code a max precision, overriding commodity styles.+ mixedAmountSetPrecisionMax defaultMaxDisplayPrecision+ . maybe id (mixedAmountApplyValuation priceOracle styles periodlast today date) value_+ . maybe id (mixedAmountToCost styles) conversionop_++ let+ wd = whichDate ropts+ showCashFlow = boolopt "cashflow" rawopts+ prettyTables = pretty_+ makeQuery flag = do+ q <- either usageError (return . fst) . parseQuery today . T.pack $ stringopt flag rawopts+ return . simplifyQuery $ And [queryFromFlags ropts{period_=PeriodAll}, q]+ cantCompute msg = error' $ msg ++ " - will be unable to compute the rates of return"++ investmentsQuery <- makeQuery "investment"+ pnlQuery <- case maybestringopt "pnl" rawopts of+ Nothing -> return None+ Just _ -> makeQuery "pnl"++ when (pnlQuery == Any) $+ cantCompute "Need some transactions classed as investment and not pnl, but the pnl query matches any transaction"++ let+ filteredj = filterJournalTransactions investmentsQuery j+ trans = dbg3 "investments" $ jtxns filteredj++ postingDay = postingDateOrDate2 wd+ isInvestment = matchesPosting investmentsQuery+ isPnl p = not (isInvestment p) && matchesPosting pnlQuery p++ -- The investment's holdings at the end of each day which changes them, accumulated once.+ -- With -B, each posting is converted to cost before summing, since summing can merge+ -- amounts with different cost bases (eg lots), losing them.+ holdingsByDay = M.fromAscList . drop 1 . scanl (\(_, acc) (d, a) -> (d, acc `maPlus` a)) (nulldate, nullmixedamt) . M.toAscList $+ M.fromListWith maPlus [ (postingDay p, maybe id (mixedAmountToCost styles) conversionop_ $ pamount p)+ | t <- trans, p <- realPostings t, isInvestment p ]+ -- the investment's holdings at the end of this day+ holdingsAt d = maybe nullmixedamt snd $ M.lookupLE d holdingsByDay++ -- The unit prices of the investment's own purchases and sales, by commodity and date (the last one recorded on a+ -- date wins, as with --infer-market-prices), for valuing holdings which have no market price.+ -- (fromListWith passes the later entry first, and union keeps its first argument's entries.)+ tradePrices = M.fromListWith M.union+ [ (pdcommodity pd, M.singleton (postingDay p) (pdamount pd))+ | t <- trans, p <- realPostings t, isInvestment p, a <- amounts (pamount p)+ , Just pd <- [amountPriceDirectiveFromCost (postingDay p) a] ]+ -- the price of the investment's latest purchase or sale of this commodity, on or before this date+ latestTradePrice c d = M.lookup c tradePrices >>= fmap snd . M.lookupLE d++ -- The investment's cash flows from b to lastDay, measured from its own side: for each transaction and each date of+ -- its investment postings, the cost of those postings, less the transaction's profit and loss (counted on the first+ -- of those dates), valued with valueOn. So other postings in the same transaction (eg fees, or gains and losses on+ -- other holdings) don't count, and flows are dated like the changes they make to the investment.+ -- Deposits are negative and withdrawals positive, like the postings of the money that pays for them.+ investmentCashFlows valueOn b lastDay =+ [ InvestmentFlow d (tdescription t) cost gain (maNegate $ cost `maMinus` gain)+ | t <- trans+ , let ps = realPostings t+ byDay = M.fromListWith (flip (++)) [ (postingDay p, [p]) | p <- ps, isInvestment p ]+ pnlAmt = sumPostings (filter isPnl ps)+ , (i, (d, invps)) <- zip [0 :: Int ..] (M.toAscList byDay)+ , d >= b, d <= lastDay+ , let cost = valueOn d $ mixedAmountToCost styles ToCost $ sumPostings invps+ gain = if i == 0 then maNegate (valueOn d pnlAmt) else nullmixedamt+ , maIsNonZero (cost `maMinus` gain) ]++ when (null trans) $+ error' "No relevant transactions found. Check your investments query"++ let (fullPeriodDateSpan, mspans) = reportSpan filteredj rspec++ let err = cantCompute "Undefined start or end of the period"+ spans = maybe err (map (second (addDays 1)) . dayPartitionToList) mspans+ fullPeriod = case fullPeriodDateSpan of+ DateSpan (Just b) (Just e) -> (fromEFDay b, fromEFDay e)+ _ -> err++ let processSpan (b, e) = do+ -- Spans are [begin,end), and end is 1 day after the actual end date we are interested in+ let+ -- the last day of the span, which --value=end and the value at the end of the span are valued on+ lastDay = addDays (-1) e++ cashFlowApplyCostValue = map (\(d,amt) -> (d,mixedAmountValue lastDay d amt))++ -- With valuation, the investment's value should end up in the same commodity as the cash flows and PnL, which+ -- are valued the same way (that need not be the one given to --value, if nothing converts to it).+ -- Without cash flows or PnL, it should be in the one given to --value.+ expectedCommodity = case value_ of+ Nothing -> Nothing+ Just vt -> case S.toList (S.unions $ map (maCommodities . snd) (otherFlows ++ pnl)) of+ [c] -> Just c+ [] -> valuationTypeValuationCommodity vt+ _ -> Nothing+ -- Value an amount of the investment on a date. Positions fully closed by then are dropped first. A commodity+ -- with no market price known on or before that date is valued at the price of the investment's latest purchase+ -- or sale of it (as --infer-market-prices would, but only from the investment's own transactions, and only when+ -- no market price is known). Its net cost would be wrong after a sale at a different price, and could even be+ -- negative.+ valueOn date amt0 =+ let amt = dropClosedPositions amt0+ valued = mixedAmountValue lastDay date amt+ unpriced = S.fromList [ acommodity a | Just c <- [expectedCommodity], a <- amounts valued+ , acommodity a /= c, not (amountIsZero a) ]+ isUnpriced = (`S.member` unpriced) . acommodity+ valued'+ | S.null unpriced = valued+ | otherwise = mixedAmountValue lastDay date $ mixed+ [ if isUnpriced a then maybe a (\pr -> pr{aquantity = aquantity pr * aquantity a}) (latestTradePrice (acommodity a) date) else a+ | a <- amounts amt ]+ in checkValued (value_ >>= valuationTypeValuationCommodity) expectedCommodity date valued'++ -- the value at the start of the span is the value at the end of the previous day, so that it equals the value+ -- at the end of the previous span (except with --value=end, which values each span at its own end)+ valueBefore = dbg3 "valueBefore" $ valueOn (addDays (-1) b) $ holdingsAt (addDays (-1) b)++ valueAfter = dbg3 "valueAfter" $ valueOn lastDay $ holdingsAt lastDay++ flowDetails = investmentCashFlows valueOn b lastDay+ cashFlow = dbg3 "cashFlow" $ [ (ifDate f, ifFlow f) | f <- flowDetails ]++ -- The other postings of the investment transactions, which are where the money comes from or goes to.+ -- Only used to tell which commodity the money is in, after valuation.+ otherFlows = dbg3 "otherFlows" $+ cashFlowApplyCostValue $ inSpan $+ calculateCashFlow wd trans (And [Not investmentsQuery, Not pnlQuery])++ pnl = dbg3 "pnl" $+ cashFlowApplyCostValue $ inSpan $+ calculateCashFlow wd trans (And [Not investmentsQuery, pnlQuery])++ -- postings dated (like the cash flows and holdings) within the span+ inSpan = filter (\(d, _) -> d >= b && d <= lastDay)++ spanCommodities = dbg3 "spanCommodities" $+ S.unions $ (maCommodities valueBefore) : (maCommodities valueAfter) : map (maCommodities.snd) (cashFlow ++ pnl)++ thisSpan = dbg3 "processing span" $+ OneSpan b e valueBefore valueAfter cashFlow pnl++ when (S.size spanCommodities > 1) $+ multiCommodityError $ "Period " ++ show (b,e) ++ " has multiple commodities: " ++ (T.unpack $ T.intercalate ", " $ map showCommoditySymbol (S.toList spanCommodities))++ let -- show a quantity of the span's (single) commodity, styled+ showAmt q = T.pack $ showMixedAmountOneLineWithoutCost False $ styleAmounts styles $+ mixedAmount nullamt{acommodity = fromMaybe "" (S.lookupMin spanCommodities), aquantity = q}+ (irrdetails, eirr) <- internalRateOfReturn styles showCashFlow prettyTables flowDetails thisSpan+ (twrdetails, etwr) <- timeWeightedReturn showCashFlow prettyTables showAmt holdingsAt valueOn thisSpan+ let cashFlowAmt = maNegate . maSum $ map snd cashFlow+ let smallIsZero x = if abs x < 0.01 then 0.0 else x+ let showPct = either (const "error") (T.pack . printf "%0.2f%%" . smallIsZero)+ let spanLabel = T.unpack $ showDate b <> " - " <> showDate lastDay+ let errors = [ spanLabel ++ ", " ++ what ++ ":\n" ++ intercalate "\n" (map (" " ++) (lines msg))+ | (what, Left msg) <- [("IRR", () <$ eirr), ("TWR", () <$ etwr)] ]+ let spanrow = [ showDate b+ , showDate (addDays (-1) e)+ , T.pack $ showMixedAmountOneLineWithoutCost False $ styleAmounts styles $ valueBefore+ , T.pack $ showMixedAmountOneLineWithoutCost False $ styleAmounts styles $ cashFlowAmt+ -- , T.pack $ showMixedAmount $+ -- -- dbg0With (lbl "cashflow after styling".showMixedAmountOneLine) $+ -- mapMixedAmount (amountSetFullPrecisionUpTo (Just defaultMaxDisplayPrecision)) $+ -- styleAmounts (styles+ -- -- & dbg0With (lbl "styles".show))+ -- cashFlowAmt+ -- -- & dbg0With (lbl "cashflow before styling".showMixedAmountOneLine)+ , T.pack $ showMixedAmountOneLineWithoutCost False $ styleAmounts styles $ valueAfter+ , T.pack $ showMixedAmountOneLineWithoutCost False $ styleAmounts styles $ (valueAfter `maMinus` (valueBefore `maPlus` cashFlowAmt))+ , showPct eirr+ , showPct (fst <$> etwr)+ , showPct (snd <$> etwr) ]+ return (irrdetails <> twrdetails, spanrow, errors)++ (perioddetails, periodRows, periodErrors) <- unzip3 <$> forM spans processSpan+ (totaldetails, totalRow, totalErrors) <- case periodRows of+ [singleRow] -> return ("", singleRow, [])+ _ -> processSpan fullPeriod++ let rowTitles = Tab.Group Tab.NoLine (map (Header . T.pack . show) (take (length periodRows) [1..]))++ let isSingleSpan = length spans == 1+ details = mconcat perioddetails <> totaldetails++ rows = if isSingleSpan then periodRows else periodRows ++ [totalRow]+ -- a rate of return that can't be computed shows as "error" in its cell; the reasons are given after the report+ errors = concat periodErrors ++ totalErrors++ let table = Table+ (if isSingleSpan+ then rowTitles+ else Tab.Group Tab.SingleLine [ rowTitles, Tab.Group Tab.NoLine [ Header "Total" ]]+ )+ (Tab.Group Tab.DoubleLine+ [ Tab.Group Tab.SingleLine [Header "Begin", Header "End"]+ , Tab.Group Tab.SingleLine [Header "Value (begin)", Header "Cashflow", Header "Value (end)", Header "PnL"]+ , Tab.Group Tab.SingleLine [Header "IRR"]+ , Tab.Group Tab.SingleLine [Header "TWR/period", Header "TWR/year"]])+ rows++ writeOutput opts $ TL.unpack $ withTitle ropts $+ details <> Tab.render prettyTables id id id table <> "\n"++ -- The report did complete, and a rate with no answer is a permanent fact about the journal, so this is a warning.+ unless (null errors) $ do+ hFlush stdout+ warnIO $ intercalate "\n" $ "Some rates of return could not be computed (they are shown as error):" : errors++-- | Time-weighted rate of return, computed from the investment's value at the end of each day.+--+-- Only end-of-day values are used, which are always well defined: the day's closing balance, valued with the prices in+-- effect that day, whatever the order of transactions and prices within the day. Between days with cash flows, the+-- return is the ratio of values. A day with cash flows is split in two: first the day's price changes, applied to the+-- holdings carried over from the previous day; then the flows, as if made at the day's closing prices, with deposits+-- counted at the start and withdrawals at the end of that part (any difference between the trade prices and the+-- closing prices is part of its return). A stretch with nothing invested earns nothing, and contributes a factor of 1.+-- All returns are chained.+--+-- Cash flows are measured from the investment's side (see investmentCashFlows), so that they always agree with the+-- changes in its value.+timeWeightedReturn showCashFlow prettyTables showAmt holdingsAt valueOn (OneSpan begin end _valueBeforeAmt _valueAfterAmt cashflows _pnls) = do+ let+ lastDay = addDays (-1) end+ valueAt d = unMix $ valueOn d $ holdingsAt d++ -- deposits and withdrawals on each day of the period (each transaction's flows are netted, deposits are positive)+ flowsByDay = M.fromListWith (\(i1, o1) (i2, o2) -> (i1 + i2, o1 + o2))+ [ (d, (max 0 f, min 0 f)) | (d, ma) <- cashflows, let f = negate (unMix ma) ]++ -- Each row is a part of the period: (begin, end, what it is, value at begin, deposits, withdrawals, value at end).+ -- Every row's return is (value at end - withdrawals) / (value at begin + deposits) - 1 (withdrawals are negative),+ -- or 0 when nothing was invested at the start; the time-weighted return chains them.+ -- Stretches without cash flows get one row. A day with cash flows gets a row for its price changes (when there are+ -- any), from the previous day's closing value to the holdings carried over at this day's prices, and a row for its+ -- cash flows, from there to its closing value.+ go (prevDay, prevValue) [] =+ [ (addDays 1 prevDay, lastDay, "no cash flows", prevValue, 0, 0, valueAt lastDay) | prevDay < lastDay ]+ go (prevDay, prevValue) ((d, (deposits, withdrawals)) : rest) =+ let startValue = valueAt (addDays (-1) d)+ movedValue = unMix $ valueOn d $ holdingsAt (addDays (-1) d)+ endValue = valueAt d+ in [ (addDays 1 prevDay, addDays (-1) d, "no cash flows", prevValue, 0, 0, startValue) | addDays 1 prevDay <= addDays (-1) d ]+ ++ [ (d, d, "prices", startValue, 0, 0, movedValue) | movedValue /= startValue ]+ ++ (d, d, "cash flows", movedValue, deposits, withdrawals, endValue)+ : go (d, endValue) rest++ rowReturn (b, e, part, v0, dep, wdr, v1)+ | base == 0 = Right 0 -- nothing invested at the start+ | base < 0 = Left $ "Cannot compute the time-weighted return for "+ ++ T.unpack (if b == e then showDate b else showDate b <> " to " <> showDate e) ++ " (" ++ T.unpack part ++ "): "+ ++ "the investment's value at the start (" ++ T.unpack (showAmt v0) ++ ") plus deposits ("+ ++ T.unpack (showAmt dep) ++ ") is negative."+ | otherwise = Right (realToFrac final / realToFrac base - 1 :: Double)+ where base = v0 + dep; final = v1 - wdr++ rows = dbg3 "twr rows" $ go (addDays (-1) begin, valueAt (addDays (-1) begin)) (M.toAscList flowsByDay)+ returns = map rowReturn rows+ -- once a row's return can't be computed, neither can the cumulative returns from there on+ cumulative = drop 1 $ scanl (\acc r -> (\a x -> (1 + a) * (1 + x) - 1) <$> acc <*> r) (Right 0) returns+ etwr = dbg3 "twr" $ if null cumulative then Right 0 else last cumulative++ years = fromIntegral (diffDays end begin) / 365.25 :: Double+ result = flip fmap etwr $ \twr ->+ let periodTWR = roundTo 2 (100 * realToFrac twr :: Decimal)+ annualizedTWR = 100 * ((1 + twr) ** (1 / years) - 1) :: Double+ in (realToFrac periodTWR :: Double, annualizedTWR)++ showPercent = either (const "error") $ \r -> T.pack (showDecimal (roundTo 2 (realToFrac r * 100 :: Decimal)))+ details = if not showCashFlow then "" else+ TL.pack (printf "\nTWR returns for period %s - %s\n" (showDate begin) (showDate lastDay))+ <> Tab.render prettyTables T.pack id id+ (Table+ (Tab.Group Tab.NoLine [Header (show n) | n <- [1..length rows]])+ (Tab.Group DoubleLine+ [ Tab.Group Tab.SingleLine [Tab.Header "Begin", Tab.Header "End", Tab.Header "Part"]+ , Tab.Group Tab.SingleLine [Tab.Header "Value (begin)", Tab.Header "Deposits", Tab.Header "Withdrawals", Tab.Header "Value (end)"]+ , Tab.Group Tab.SingleLine [Tab.Header "Return, %", Tab.Header "Cumulative, %"]])+ [ [ showDate b, showDate e, part+ , showAmt v0, showAmt dep, showAmt wdr, showAmt v1+ , showPercent r, showPercent c ]+ | ((b, e, part, v0, dep, wdr, v1), r, c) <- zip3 rows returns cumulative ])+ <> "Each row's return is (Value (end) - Withdrawals) / (Value (begin) + Deposits) - 1; they are chained.\n"+ <> case result of+ Right (periodTWR, annualizedTWR) ->+ TL.pack (printf "Total period TWR: %.2f%%.\nPeriod: %.2f years.\nAnnualized TWR: %.2f%%\n\n"+ periodTWR years annualizedTWR)+ Left _ -> "\n"++ return (details, result)++internalRateOfReturn styles showCashFlow prettyTables flowDetails (OneSpan begin end valueBefore valueAfter cashFlow _pnl) = do+ let prefix = (begin, maNegate valueBefore)++ postfix = (end, valueAfter)++ totalCF = filter (maIsNonZero . snd) $ prefix : (sortOn fst cashFlow) ++ [postfix]++ showMA = T.pack . showMixedAmountOneLineWithoutCost False . styleAmounts styles+ -- one row per cash flow, with the transaction it comes from, between the values at the start and the end+ -- (dated like the IRR uses them: the value at the end of the last day, on the day after it)+ rows =+ [ (begin, "value at the start", "", "", maNegate valueBefore) | maIsNonZero valueBefore ]+ ++ [ (ifDate f, ifDescription f, showMA (ifCost f), showMA (ifPnl f), ifFlow f) | f <- sortOn ifDate flowDetails ]+ ++ [ (end, "value at the end of " <> showDate (addDays (-1) end), "", "", valueAfter) | maIsNonZero valueAfter ]+ details = if not showCashFlow then "" else+ TL.pack (printf "\nIRR cash flows for %s - %s\n" (showDate begin) (showDate (addDays (-1) end)))+ <> Tab.render prettyTables id id id+ (Table+ (Tab.Group Tab.NoLine [ Header (showDate d) | (d, _, _, _, _) <- rows ])+ (Tab.Group Tab.SingleLine [Header "Description", Header "Investment, at cost", Header "Profit/loss", Header "Amount"])+ [ [desc, cost, pnl, showMA amt] | (_, desc, cost, pnl, amt) <- rows ])+ <> "Amounts are from your point of view: what you put in is negative, what you take out (or still have) positive.\n\n"++ return (details, either (Left . irrErrorMessage) Right $ xirr end [ (d, unMix a) | (d, a) <- totalCF ])++irrErrorMessage :: IrrError -> String+irrErrorMessage e = "Equation for Internal Rate of Return (IRR) can not be solved.\n" ++ case e of+ IrrNothingPutIn ->+ " Money only came out of the investment in this period (or is still in it at the end), and none was put in\n\+ \ (counting its value at the start as put in), so the IRR is infinite."+ IrrAllOnOneDay d ->+ " All of this period's cash flows (including the values at its start and end) fall on " ++ T.unpack (showDate d) ++ ",\n\+ \ so no time passes for the gain or loss to happen in."+ IrrNotBracketed ->+ " Possible causes: IRR is huge (>1000000%), balance of investment becomes negative at some point in time."+ IrrSearchFailed ->+ " Either search does not converge to a solution, or converges too slowly."++type CashFlow = [(Day, MixedAmount)]++calculateCashFlow :: WhichDate -> [Transaction] -> Query -> CashFlow+calculateCashFlow wd trans query =+ [ (postingDateOrDate2 wd p, pamount p) | p <- concatMap (filter (matchesPosting query) . realPostings) trans, maIsNonZero (pamount p) ]++unMix :: MixedAmount -> Quantity+unMix a =+ case (unifyMixedAmount a) of+ Just a' -> aquantity a'+ Nothing -> multiCommodityError $ "Amounts could not be converted to a single commodity: " ++ show (map showAmount $ amounts a)++-- | One cash flow of the investment, with the parts it is computed from (shown by --cashflow).+data InvestmentFlow = InvestmentFlow+ { ifDate :: Day+ , ifDescription :: T.Text+ , ifCost :: MixedAmount -- ^ the cost of the transaction's investment postings on that date+ , ifPnl :: MixedAmount -- ^ the transaction's profit and loss (gains positive)+ , ifFlow :: MixedAmount -- ^ the cash flow: deposits negative, withdrawals positive+ }++-- | Drop the amounts of commodities whose quantities add up to zero (positions fully closed). Summing postings can keep+-- these as separate amounts with different costs, which don't cancel out when valued at cost.+dropClosedPositions :: MixedAmount -> MixedAmount+dropClosedPositions ma = filterMixedAmount ((`S.notMember` closed) . acommodity) ma+ where closed = M.keysSet . M.filter (== 0) $ M.fromListWith (+) [ (acommodity a, aquantity a) | a <- amounts ma ]++-- | After valuation, an amount of the investment should be in the expected commodity, if we know it. If some of it is+-- still in another commodity, there was no market price for that commodity on that date. Say so, rather than mistake+-- its quantity for a value or report a confusing mix of commodities later.+-- The expected commodity can differ from the one requested with --value, when nothing converts to that; mention it then.+checkValued :: Maybe CommoditySymbol -> Maybe CommoditySymbol -> Day -> MixedAmount -> MixedAmount+checkValued _ Nothing _ amt = amt+checkValued requested (Just c) date amt =+ case nub [ acommodity a | a <- amounts amt, acommodity a /= c, not (amountIsZero a) ] of+ [] -> amt+ unpriced -> error' $ "Could not value the investment on " ++ T.unpack (showDate date) ++ ": "+ ++ "no market price in " ++ showc c ++ " is known for "+ ++ intercalate ", " (map showc unpriced) ++ " on or before that date."+ ++ (case requested of+ Just r | r /= c -> "\n" ++ showc r ++ " was requested with --value, but the cash flows and PnL"+ ++ " are in " ++ showc c ++ ", as no market price converts them to " ++ showc r ++ "."+ _ -> "")+ ++ "\nAdd a P directive, or use --infer-market-prices to also use the prices recorded in transactions."+ where showc = T.unpack . showCommoditySymbol++multiCommodityError msg = error' $ msg +++ "\nConsider using --value to force all costs to be in a single commodity." +++ "\nFor example, \"--value=end,<commodity> --infer-market-prices\", where commodity is the one that you want to value the investment in."++-- Show Decimal rounded to two decimal places, unless it has less places already. This ensures that "2" won't be shown as "2.00"+showDecimal :: Decimal -> String+showDecimal d = if d == rounded then show d else show rounded+ where+ rounded = roundTo 2 d
+ Hledger/Cli/Commands/Roi.txt view
@@ -0,0 +1,337 @@+roi++Show the money-weighted (IRR) and time-weighted (TWR) rate of return on+your investments.++Flags:+ --cashflow show all amounts that were used to compute+ returns+ --investment=QUERY query to select your investment transactions+ --profit-loss=QUERY --pnl query to select profit-and-loss or+ appreciation/valuation transactions (optional)++At a minimum, you need to supply a query (which could be just an account+name) to select your investment(s) with --inv.++An optional second query to identify your profit and loss transactions+could be given with --pnl. If your investment's value changes are+captured solely through price directives (rather than manual P&L journal+entries), or if you do not need TWR, you can simply omit --pnl, and no+transactions will be classed as profit and loss in this case.++This command will compute and display the internal rate of return (IRR,+also known as money-weighted rate of return) and time-weighted rate of+return (TWR) for your investments for the time period requested. IRR is+always annualized due to the way it is computed, but TWR is reported+both as a rate over the chosen reporting period and as an annual rate.++Price directives will be taken into account if you supply appropriate+--cost or --value flags (see Value reporting).++Some special cases of IRR have no solution in the usual sense, and are+reported as:++- 0%, when there are no cash flows, or when they all fall on the same+ day and add up to zero (nothing is gained or lost, and no time passes)+- -100%, when money is put in, but nothing comes out of the investment+ or is left in it (all of it is lost). A total loss is -100% however+ long the money was invested, even for a day. (But a partial loss+ within one day is an error, below, since its annual rate depends on+ how much time passes.)++In some cases a rate of return can't be computed. Then its cell in the+report shows error, the rest of the report is still shown, and the+reasons (each with its period) are printed after it as a warning. The+reasons can be:++- No solution for Internal Rate of Return (IRR). Possible causes: IRR is+ huge (>1000000%), balance of investment becomes negative at some point+ in time.+- No solution for Internal Rate of Return (IRR), because money only came+ out of the investment in that period (or is still in it at the end),+ and none was put in (counting its value at the start as put in), so+ the IRR is infinite.+- No solution for Internal Rate of Return (IRR), because all of a+ period's cash flows (including the values at its start and end) fall+ on the same day, so no time passes for the gain or loss to happen in.+- Failed to find solution for Internal Rate of Return (IRR). Either+ search does not converge to a solution, or converges too slowly.+- Cannot compute the time-weighted return for DATES (PART): the+ investment's value at the start (...) plus deposits (...) is negative.+ Possible cause: the balance of the investment becomes negative, eg+ more is sold than is held (a short position).++And in some cases the whole report can't be produced:++- Error: Could not value the investment on DATE: no market price ... is+ known for COMMODITY on or before that date. A holding has no market+ price, and none of the investment's transactions on or before that+ date records a price for buying or selling it. Add a P directive for+ it, or record the price of its purchase.+- Error: Period ... has multiple commodities: ... The investment, its+ cash flows or its profit and loss are in more than one commodity. Use+ --value to convert them to one (eg+ --value=end,$ --infer-market-prices).++Examples:++- Using roi to compute total return of investment in stocks:+ https://github.com/hledgerorg/hledger/blob/main/examples/investing/roi-unrealised.ledger++- Cookbook > Return on Investment: https://hledger.org/roi.html++Spaces and special characters in --inv and --pnl++Note that --inv and --pnl's argument is a query, and queries could have+several space-separated terms (see QUERIES).++To indicate that all search terms form single command-line argument, you+will need to put them in quotes (see Special characters):++$ hledger roi --inv 'term1 term2 term3 ...'++If any query terms contain spaces themselves, you will need an extra+level of nested quoting, eg:++$ hledger roi --inv="'Assets:Test 1' cur:USD" --pnl="'Equity:Unrealized Profit and Loss'"++Semantics of --inv and --pnl++Query supplied to --inv has to match all transactions that are related+to your investment. Transactions not matching --inv will be ignored.++In these transactions, ROI will consider postings that match --inv to be+"investment postings" and other postings (not matching --inv) will be+sorted into two categories: "cash flow" and "profit and loss", as ROI+needs to know which part of the investment value is your contributions+and which is due to the return on investment.++- "Cash flow" is depositing or withdrawing money, buying or selling+ assets, or otherwise converting between your investment commodity and+ any other commodity. Example:++ 2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++ 2020-01-01 Selling my Snake Oil+ assets:cash $10+ investment:snake oil = 0++- "Profit and loss" is change in the value of your investment:++ 2019-06-01 Snake Oil falls in value+ investment:snake oil = $57+ equity:unrealized profit or loss++All non-investment postings are assumed to be "cash flow", unless they+match --pnl query. Changes in value of your investment due to "profit+and loss" postings will be considered as part of your investment return.++The amount of each cash flow is measured from the investment's+perspective: it is the cost of the transaction's investment postings,+minus any profit and loss in that transaction. Its date is the date of+those investment postings, even if the money's posting has a different+date (eg a settlement date). This means that other postings in the same+transaction, such as fees, don't change the amount of the cash flow.++In this example, the investment receives $100, so without --pnl the cash+flow is a $100 deposit, and the $1 fee is not part of the investment at+all. With --pnl expenses, the fee counts as part of the investment's+return instead: the cash flow is a $101 deposit, of which $1 is+immediately lost (shown as profit/loss of -$1):++2019-01-01 Buying Snake Oil, with a fee+ assets:cash -$101+ expenses:fees $1+ investment:snake oil $100++Example: if you use --inv snake --pnl equity:unrealized, then postings+in the example below would be classifed as:++2019-01-01 Snake Oil #1+ assets:cash -$100 ; cash flow posting+ investment:snake oil ; investment posting++2019-03-01 Snake Oil #2+ equity:unrealized pnl -$100 ; profit and loss posting+ snake oil ; investment posting++2019-07-01 Snake Oil #3+ equity:unrealized pnl ; profit and loss posting+ cash -$100 ; cash flow posting+ snake oil $50 ; investment posting++Using roi with lots++If your journal records lots, each disposal transaction has a realised+gain posting, by default to revenues:gain. Make sure --pnl matches that+account, eg --pnl revenues:gain, so realised gains are counted as+profit. Cash flows are measured at the investment postings' cost, which+for lots is their cost basis, so without --pnl a sale is a withdrawal of+its cost basis only, and its gain is not counted at all: IRR and TWR+will understate the return (eg showing 0% for a buy and a sale at a+profit).++IRR and TWR explained++"ROI" stands for "return on investment". Traditionally this was computed+as a difference between current value of investment and its initial+value, expressed in percentage of the initial value.++However, this approach is only practical in simple cases, where the+investment receives no in-flows or out-flows of money and the rate of+growth is fixed over time. For more complex scenarios you need different+ways to compute rate of return, and this command implements two of them:+IRR and TWR.++Internal rate of return (IRR), also called money-weighted rate of+return, answers the question: what single constant annual interest rate,+applied to your actual sequence of deposits and withdrawals, would+produce exactly the ending balance you have?++IRR is inherently personal. If you deposited a large sum right before a+bad period, your IRR is dragged down - not because the investment was+poorly managed, but because your timing was bad. Conversely, investing+heavily just before a rally makes your IRR look great. This is what+makes IRR "money-weighted": periods when more of your money is at stake+contribute more to the result.++In technical terms, IRR uses the same approach as computation of net+present value, and tries to find a discount rate that makes the net+present value of all the cash flows of your investment add up to zero.+The implementation in hledger produces results that match the =XIRR+formula in Excel.++Time-weighted rate of return (TWR) strips out the effect of your deposit+and withdrawal timing, measuring the investment's own performance rather+than your experience of it.++hledger computes TWR from the value of your investment at the end of+each day: its balance at the end of the day, valued (with --value) using+the prices in effect on that day. The order of transactions and prices+within a day doesn't matter.++- The days between two days with cash flows form one stretch, which+ starts at the end of the earlier cash flow day and ends at the end of+ the day before the later one. Its return is the ratio of the+ investment's values at those two moments. For example, with cash flows+ on March 1 and March 10, the stretch is March 2 to 9, and its return+ is (value at the end of March 9) / (value at the end of March+ 1) - 1. (March 10 itself is a day with cash flows, handled as+ below.)+- A day with cash flows is split in two parts:+ 1. The day's price changes: the return of the holdings carried over+ from the previous day, from their value at the previous day's+ prices to their value at this day's prices. (This part is skipped+ if no prices changed.)+ 2. The cash flows, as if all of the day's trades were made at the+ day's closing prices. Its return is (value at the end of the day -+ withdrawals) / (value after part 1 + deposits) - 1, with+ withdrawals negative. That is, the day's deposits count as+ invested during this part, as if made at its start, and its+ withdrawals count as still invested during it, as if made at its+ end. So any difference between the prices you traded at and the+ closing prices shows up in this part's return.+- Times when nothing is invested earn nothing. That includes a day on+ which something arrives in an empty investment only as profit and loss+ (eg a stock grant, booked to an account matched by --pnl): there is+ nothing to compute a return on, so that day's return is 0%.+- A holding which has no market price is valued at the price of the+ investment's latest purchase or sale of it, on or before that day (as+ --infer-market-prices would do, but only from the investment's own+ transactions, and only while no market price is known). If there are+ several on a day, the last one recorded is used. Like any price, it+ applies to the whole holding on that day, including what was held+ before the trade, so a trade at a new price can show up in --cashflow+ output as a "prices" row, before its cash flows. And a trade recorded+ at zero cost (eg a gift, recorded with @ $0) gives a price of 0, so+ such a holding is worth nothing until a market price is known; add a P+ directive for it.++All these returns are then multiplied together (geometrically chained)+to give the TWR for the full period. In multi-period reports, each+period begins with the value the previous one ended with, so the+periods' returns chain to the total.++Use --value=then for TWR, so that each day is valued with the prices of+that day. With --value=end, --value=now or --value=DATE, all the values+in a period use the same prices, so its TWR only reflects recorded+profit and loss and the differences between the prices you traded at and+those prices. With --value=end, each period is also valued with its own+end's prices, so the periods' returns don't chain to the total.++TWR can only be as good as the values your journal gives for each day.+If you record changes in value only occasionally (with --pnl+transactions, or with sparse price directives), the growth since the+previous record is attributed to the day you record it, and so is+counted on whatever was invested on that day. If you made a large+deposit or withdrawal in between, that can make TWR quite different from+what it would be if the growth had been spread out. So record a+valuation around large deposits and withdrawals (professional+performance standards require this too), or use price directives, or+--infer-market-prices if your transactions record their prices.++In short: TWR tells you how good the investment was; IRR tells you how+good your experience of the investment was.++Checking the results++--cashflow shows everything that IRR and TWR are computed from, so that+you can check them against your journal, against other hledger reports,+or in a spreadsheet:++- IRR cash flows: one row per cash flow, with the transaction's+ description, the cost of its investment postings, and its profit or+ loss, between the investment's value at the start and its value at the+ end (dated the day after the period's last day, since it is the value+ at the end of that day). Amounts are from your point of view: what you+ put in is negative, what you take out or still have is positive. The+ dates and amounts can be given to Excel's =XIRR as they are.++- TWR returns: one row for each stretch without cash flows, and for each+ day with cash flows, a row for its price changes (if any) and a row+ for its cash flows. Each row's Value (begin) is the previous row's+ Value (end), and each row's return is++ (Value (end) - Withdrawals) / (Value (begin) + Deposits) - 1++ where withdrawals are negative. The Cumulative column chains the+ returns by multiplication: each row's (1 + Cumulative) is the previous+ row's (1 + Cumulative) times (1 + Return). Its last row is the+ period's TWR.++The values can be checked with hledger balance: the value at the end of+a day D is the investment's historical balance at the end of that day,+valued then. For example, if you ran roi --value=then,$, check the value+at the end of day D with:++$ hledger balance --historical --value=end,$ -e D+1 INVESTMENTQUERY++(where D+1 is the day after D; --value=end values at the end of the+report period, which is day D). Holdings which have no market price are+the exception, as roi values them at the price of their latest purchase+or sale.++When each matters++Use IRR when you want to know your actual personal return - what you+earned on your money, accounting for when you chose to move it. It is+the right measure when evaluating your own deposit and withdrawal timing+decisions.++Use TWR when you want to evaluate the investment vehicle itself,+independent of your deposit timing. It is the right measure when+comparing two funds or strategies, or when asking whether you would have+been better off elsewhere. TWR is the standard that professional+investment managers use to report fund performance, precisely because it+removes the distortion caused by investor cash flows.++References:++- Explanation of rate of return+- Explanation of IRR+- Explanation of TWR+- IRR vs TWR+- Examples of computing IRR and TWR and discussion of the limitations of+ both metrics
+ Hledger/Cli/Commands/Run.hs view
@@ -0,0 +1,621 @@+{-|++The @run@ command allows you to run multiple commands via REPL or from the supplied file(s).++-}++{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Run (+ runmode+ ,run+ ,replmode+ ,repl+ ,runOrReplStub+) where++import Data.List (isInfixOf)+import Data.List.NonEmpty qualified as NE+import Data.Map.Strict qualified as Map+import Data.Semigroup (sconcat)+import Data.Text qualified as T+import Data.Text.IO qualified as T+import Data.Text.Lazy qualified as TL+import System.Console.CmdArgs.Explicit as C ( Mode )+import Hledger+import Hledger.Cli.CliOptions+import Hledger.Utils.I18n qualified as I18n+import Hledger.Cli.Conf (CommandAlias, CommandLine, ResolvedCommand(..), expandCommandAlias, getConf, confAliases)++import Control.Exception+import Control.Concurrent.MVar+import Control.Monad (forM_, void, when, zipWithM_)+import Control.Monad.IO.Class (liftIO)+import Control.Monad.Extra (concatMapM, anyM)+import Data.IORef (IORef, modifyIORef, newIORef, readIORef, writeIORef)+import Data.Time.Clock.POSIX (POSIXTime, utcTimeToPOSIXSeconds)++import System.Exit (ExitCode(..), exitWith)+import System.Console.CmdArgs.Explicit (expandArgsAt, flagHelp, flagNames, flagNone, modeFlags, modeNames)+import System.IO (stdin, stderr, stdout, hClose, hIsTerminalDevice, hIsOpen, hPutStrLn, hFlush, openTempFile)+import System.IO.Unsafe (unsafePerformIO)+import System.Console.Haskeline++import Data.Maybe (isJust, fromMaybe, catMaybes)+import Safe (headMay)+import Hledger.Cli.DocFiles (runTldrForPage, runInfoForTopic, runManForTopic)+import Hledger.Cli.Utils (journalTransform, journalFileIsNewer, maybeFileModificationTime, writeOutputLazyText)+import Text.Printf (printf)+import System.FilePath (takeBaseName, getSearchPath)+import System.Directory (XdgDirectory(..), createDirectoryIfMissing, doesDirectoryExist, getModificationTime, getXdgDirectory, removeFile)+import System.Process (system)+import Hledger.Cli.Version (packageversion)+import Hledger.Write.Html (htmlAsLazyText, nl)+import Text.Blaze.Html5 ((!), (!?))+import Text.Blaze.Html5 qualified as H+import Text.Blaze.Html5.Attributes qualified as A++-- | Command line options for this command.+runmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Run.txt")+ (+ [outputFormatFlag ["html"]+ ,outputFileFlag+ ,outputViewFlag+ ])+ cligeneralflagsgroups1+ -- A hidden marker flag, inserted before run's first -- (see argsMarkRunCommands), letting run+ -- detect it was given inline commands rather than command files. Not for direct use.+ (flagNone [runCommandsMarker] (setboolopt runCommandsMarker) "" : hiddenflags)+ ([], Just $ argsFlag "[COMMANDS_FILE1 COMMANDS_FILE2 ...] OR [-- command1 args... -- command2 args... -- command3 args...]")++replmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Repl.txt")+ (+ [flagNone ["no-watch"] (setboolopt "no-watch") "disable automatic reloading of changed input files, config aliases and addon commands"]+ )+ cligeneralflagsgroups1+ hiddenflags+ ([], Nothing)++-- | The fake run/repl command introduced to break circular dependency.+-- This module needs access to `findBuiltinCommand`, which is defined in Hledger.Cli.Commands+-- However, Hledger.Cli.Commands imports this module, which creates circular dependency.+-- We expose this do-nothing function so that it could be included in the list of all commands inside+-- Hledger.Cli.Commands and ensure that "run" is recognized as a valid command by the Hledger.Cli top-level+-- command line parser. That parser, however, would not call run'. It has a special case for "run", and+-- will call "run" (see below), passing it `findBuiltinCommand`, thus breaking circular dependency.+runOrReplStub :: CliOpts -> Journal -> IO ()+runOrReplStub _opts _j = return ()++-- | Default input files that would be used by commands if+-- there is no explicit alternative given+newtype DefaultRunJournal = DefaultRunJournal (NE.NonEmpty String) deriving (Show)++-- | The actual run command.+run :: Maybe DefaultRunJournal -> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())) -> [String] -> [(CommandAlias,CommandLine)] -> Bool -> CliOpts -> IO ()+run defaultJournalOverride findBuiltinCommand addons cmdaliases shellaliasesallowed cliopts@CliOpts{rawopts_=rawopts} = do+ jpaths <- DefaultRunJournal <$> journalFilePathFromOptsOrDefault defaultJournalOverride cliopts+ let+ args = dbg1 "args" $ listofstringopt "args" rawopts+ rungeneralopts = generalRawOpts rawopts -- general flags we will propagate to each command+ addonfileargs = concatMap (\f -> ["-f", f]) $ file_ cliopts -- the session's explicit -f files, to pass through to addons+ isTerminal <- isStdinTerminal+ -- With html output (-O html, -o FILE.html or --view), the commands' outputs are collected into one html page.+ let+ outputrequested = isJust (output_file_ cliopts) || isJust (output_format_ cliopts) || viewRequested cliopts+ collecting = outputrequested && outputFormatFromOpts cliopts == "html"+ when (outputrequested && not collecting) $ error' "run can write only html output; use -O html, -o FILE.html or --view" -- PARTIAL:+ mcollect <- if collecting then Just <$> newIORef [] else return Nothing+ if+ -- Inline commands (a -- was present, flagged by the marker): split and run them.+ | boolopt runCommandsMarker rawopts ->+ runFromArgs jpaths rungeneralopts addonfileargs findBuiltinCommand addons cmdaliases shellaliasesallowed mcollect args+ -- No arguments and stdin is not a terminal: read commands from stdin.+ | args == [] && not isTerminal -> do+ inputFiles <- journalFilePathFromOpts cliopts+ let journalFromStdin = any (== "-") $ map (snd . splitReaderPrefix) $ NE.toList inputFiles+ if journalFromStdin+ then error' "'run' can't read commands from stdin, as one of the input files was stdin as well"+ -- watch is False: run never reloads changed files, in any of its modes+ -- (unlike repl). Its other modes don't, since they don't go through runREPL.+ else runREPL jpaths rungeneralopts addonfileargs findBuiltinCommand addons cmdaliases shellaliasesallowed mcollect Nothing Nothing False+ -- Otherwise the arguments are files to read commands from.+ | otherwise ->+ runFromFiles jpaths rungeneralopts addonfileargs findBuiltinCommand addons cmdaliases shellaliasesallowed mcollect args+ forM_ mcollect $ \ref -> do+ sections <- reverse <$> readIORef ref+ let tr = I18n.tr (translations_ $ _rsReportOpts $ reportspec_ cliopts)+ writeOutputLazyText cliopts $ runPageHtml (tr "Show:", tr "Titles", tr "Charts", tr "All") sections++-- | The actual repl command. mconfinfo is the active config file and the raw options+-- needed to re-read it, used to auto-reload command aliases when the config file changes.+-- mrescanAddons is an action that re-scans PATH for addon commands, used to auto-reload the+-- addon command list when PATH's contents change.+repl :: (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())) -> [String] -> [(CommandAlias,CommandLine)] -> Bool -> Maybe (FilePath, RawOpts) -> Maybe (IO [String]) -> CliOpts -> IO ()+repl findBuiltinCommand addons cmdaliases shellaliasesallowed mconfinfo mrescanAddons cliopts = do+ jpaths <- DefaultRunJournal <$> journalFilePathFromOptsOrDefault Nothing cliopts+ let watch = not $ boolopt "no-watch" $ rawopts_ cliopts -- reload changed files/aliases/addons unless --no-watch+ addonfileargs = concatMap (\f -> ["-f", f]) $ file_ cliopts -- the session's explicit -f files, to pass through to addons+ runREPL jpaths (generalRawOpts $ rawopts_ cliopts) addonfileargs findBuiltinCommand addons cmdaliases shellaliasesallowed Nothing mconfinfo mrescanAddons watch++-- | Run commands from files given to "run".+runFromFiles :: DefaultRunJournal -> [(String,String)] -> [String] -> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())) -> [String] -> [(CommandAlias,CommandLine)] -> Bool -> Maybe RunSections -> [String] -> IO ()+runFromFiles defaultJournalOverride rungeneralopts addonfileargs findBuiltinCommand addons cmdaliases shellaliasesallowed mcollect inputfiles = do+ dbg1IO "inputfiles" inputfiles+ -- read commands from all the inputfiles+ commands <- (flip concatMapM) inputfiles $ \f -> do+ dbg1IO "reading commands" f+ lines . T.unpack <$> T.readFile f++ forM_ commands (runCommand defaultJournalOverride rungeneralopts addonfileargs findBuiltinCommand addons cmdaliases shellaliasesallowed mcollect . parseCommand)++-- | Run commands from command line arguments given to "run".+runFromArgs :: DefaultRunJournal -> [(String,String)] -> [String] -> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())) -> [String] -> [(CommandAlias,CommandLine)] -> Bool -> Maybe RunSections -> [String] -> IO ()+runFromArgs defaultJournalOverride rungeneralopts addonfileargs findBuiltinCommand addons cmdaliases shellaliasesallowed mcollect args = do+ -- read commands from all the inputfiles+ let commands = dbg1 "commands from args" $ splitAtElement "--" args+ forM_ commands (runCommand defaultJournalOverride rungeneralopts addonfileargs findBuiltinCommand addons cmdaliases shellaliasesallowed mcollect)++-- When commands are passed on the command line, shell will parse them for us+-- When commands are read from file, we need to split the line into command and arguments+parseCommand :: String -> [String]+parseCommand line =+ case wordsEither line' of+ -- # begins a comment, ignore everything after #+ Right ws -> takeWhile (not. ((Just '#')==) . headMay) ws+ Left err -> error' $ "could not parse this command line:\n" <> err+ where line' = strip line++-- | Interpret the common backslash escape sequences \n, \t, \r and \\ in a string,+-- so the run/repl echo command can print newlines, tabs etc. An unrecognised escape+-- is left as written (its backslash is kept).+unescape :: String -> String+unescape ('\\':c:cs) = case c of+ 'n' -> '\n' : unescape cs+ 't' -> '\t' : unescape cs+ 'r' -> '\r' : unescape cs+ '\\' -> '\\' : unescape cs+ _ -> '\\' : c : unescape cs+unescape (c:cs) = c : unescape cs+unescape [] = []++-- | Run an action that writes a file, with a temporary part file in hledger's cache directory+-- (created readable only by the user, and deleted afterwards), and return what it wrote.+withPartFile :: (FilePath -> IO ()) -> IO TL.Text+withPartFile act = do+ d <- getXdgDirectory XdgCache "hledger"+ createDirectoryIfMissing True d+ (part, h) <- openTempFile d "part"+ hClose h+ (act part >> TL.fromStrict <$> T.readFile part) `finally` removeFile part++-- | An html page showing run's collected sections: a heading for each echo,+-- and for each command, its command line and its output (html as is, text preformatted),+-- in a collapsible section (open). Each section's SVG ids get a suffix, so that charts+-- don't share eg a hatch pattern (which browsers won't draw from a hidden chart).+-- Links at the top, with the given labels, show more or less detail: just the sections' titles (all folded),+-- the charts (the sections open, as at first), or all (with the report details shown too).+runPageHtml :: (T.Text, T.Text, T.Text, T.Text) -> [(String, Maybe TL.Text)] -> TL.Text+runPageHtml (showlabel, titleslabel, chartslabel, alllabel) sections = htmlAsLazyText $ do+ H.docType+ H.html ! A.lang "en" $ do+ H.meta ! A.charset "utf-8"+ H.meta ! A.name "viewport" ! A.content "width=device-width,initial-scale=1"+ nl+ H.title "hledger run"+ nl+ H.style $ H.preEscapedText $ T.unlines $ "" :+ [ "body{margin:0 auto;max-width:980px;padding:24px 16px 48px;background:#f3f2ee;color:#0b0b0b;font:15px/1.5 system-ui,-apple-system,\"Segoe UI\",sans-serif}"+ , "h2{margin:24px 0 8px;font-size:18px;font-weight:650}"+ , ".hledger-run-show{margin:0 0 8px;text-align:right;font-size:13px;color:#898781}"+ , ".hledger-run-show a{margin-left:10px;color:#52514e}.hledger-run-show a.current{color:#0b0b0b;font-weight:600;text-decoration:none}"+ , "details.hledger-run{margin:0 0 8px;background:#fcfcfb;border:1px solid #e1e0d9;border-radius:8px}"+ , "details.hledger-run>summary{padding:10px 14px;cursor:pointer;color:#52514e;font:13px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}"+ , "details.hledger-run>div{padding:8px 14px 14px;border-top:1px solid #e1e0d9;overflow-x:auto}"+ , "details.hledger-run table{font-size:13px;font-variant-numeric:tabular-nums}"+ , "details.hledger-run svg{max-width:100%;height:auto}"+ ]+ nl+ H.p ! A.class_ "hledger-run-show" $ do+ H.toHtml showlabel+ forM_ (zip [0 :: Int ..] [titleslabel, chartslabel, alllabel]) $ \(n, l) ->+ H.a ! A.href "#" ! H.dataAttribute "level" (H.toValue n) !? (n == 1, A.class_ "current") $ H.toHtml l+ nl+ -- level 0: sections folded; 1: sections open (as at first); 2: report details open too.+ -- Report details are closed first, and the page laid out (by reading its height) before the sections are toggled+ -- (otherwise Safari leaves the space of report details closed along with their section, when it is reopened).+ H.script $ H.preEscapedText $ T.concat+ [ "document.querySelectorAll('.hledger-run-show a').forEach(a => a.onclick = e => { e.preventDefault();"+ , " const level = +a.dataset.level, details = document.querySelectorAll('details.hledger-details');"+ , " if (level < 2) details.forEach(d => d.open = false);"+ , " void document.body.offsetHeight;"+ , " document.querySelectorAll('details.hledger-run').forEach(d => d.open = level > 0);"+ , " if (level > 1) details.forEach(d => d.open = true);"+ , " document.querySelectorAll('.hledger-run-show a').forEach(b => b.classList.toggle('current', b === a)); });"+ ]+ nl+ zipWithM_ section [1 :: Int ..] sections+ nl+ where+ section _ (heading, Nothing) = H.h2 (H.toHtml heading) >> nl+ section n (cmd, Just out) = do+ H.details ! A.class_ "hledger-run" ! A.open "" $ do+ H.summary $ H.toHtml ("hledger " ++ cmd)+ H.div $ do+ nl+ if | TL.null (TL.strip out) -> H.p "(no output)"+ | "<" `TL.isPrefixOf` TL.stripStart out -> H.preEscapedLazyText $ uniqueIds out+ | otherwise -> H.pre $ H.lazyText out+ nl+ nl+ where+ uniqueIds = TL.replace "hledger-chart-hatch" ("hledger-chart-hatch-" <> suffix) . TL.replace "hledger-chart-clip-" ("hledger-chart-clip-" <> suffix <> "-")+ suffix = TL.pack (show n)++-- | Run a shell command, and if it fails, exit with its exit code; on success just return,+-- so a sequence of run/repl commands can continue. Flushes stdout first, so that our own+-- buffered output (eg echo's) appears before the subprocess's output.+runShellCommandOrExit :: String -> IO ()+runShellCommandOrExit shcmd = do+ hFlush stdout+ ec <- system shcmd+ when (ec /= ExitSuccess) $ exitWith ec++-- | The sections of an html page being collected by run: for each command, its command line and its output+-- (or for an echo, just its text), most recent first.+type RunSections = IORef [(String, Maybe TL.Text)]++-- | Take a single command line (from file, or REPL, or "--"-surrounded block of the args), and run it.+-- addonfileargs are -f options (the session's explicit input files) to pass through to addon commands.+-- With mcollect, a builtin command's output is collected as a section of an html page instead of being printed+-- (and so is an echo's text, as a heading).+runCommand :: DefaultRunJournal -> [(String,String)] -> [String] -> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())) -> [String] -> [(CommandAlias,CommandLine)] -> Bool -> Maybe RunSections -> [String] -> IO ()+runCommand defaultJournalOverride rungeneralopts addonfileargs findBuiltinCommand addons cmdaliases shellaliasesallowed mcollect cmdline = do+ dbg1IO "runCommand for" cmdline+ case cmdline of+ "echo":args | Just ref <- mcollect -> modifyIORef ref ((unescape $ unwords args, Nothing) :)+ | otherwise -> putStrLn $ unescape $ unwords args+ cmdname0:args0 ->+ -- The command may be a command alias defined in the config file; expand it.+ case expandCommandAlias (isJust . findBuiltinCommand) cmdaliases cmdname0 of+ -- A !-prefixed shell command alias: run it (if allowed), with any arguments appended.+ ShellCommand shcmd+ | shellaliasesallowed -> runShellCommandOrExit (unwords $ shcmd : map quoteForCommandLine args0)+ | otherwise -> error' $ "the command alias '" ++ cmdname0+ ++ "' runs a shell command, which is only allowed from your user config file or a --conf file"+ -- Otherwise an hledger command, with the alias's arguments preceding this line's own arguments.+ HledgerCommand cmdname defargs ->+ let+ -- Mark run's inline commands (see argsMarkRunCommands), after alias expansion, so it+ -- works whether "run ... -- ..." was typed directly or reached via a command alias+ -- (or a nested run in a commands file).+ args = (if cmdname == "run" then argsMarkRunCommands else id) $ defargs <> args0+ aliasnote = if cmdname /= cmdname0 then " (expanded from the " ++ cmdname0 ++ " command alias)" else ""+ in+ case findBuiltinCommand cmdname of+ Just (cmdmode,cmdaction) -> do+ -- Even though expandArgsAt is done by the Cli.hs, it stops at the first '--', so we need+ -- to do it here as well to make sure that each command can use @ARGFILEs+ args' <- replaceNumericFlags <$> expandArgsAt args+ dbg1IO "runCommand final args" (cmdname,args')+ -- Propagate run/repl's general flags to this command, letting its own flags take precedence+ opts0 <- insertRawOpts rungeneralopts =<< getHledgerCliOpts' cmdmode args'+ -- When collecting an html page, write this command's output to a part file, as html if it can produce that+ -- (otherwise its usual text, shown preformatted), and add it to the page.+ let+ collect act = case mcollect of+ Nothing -> act opts0+ Just ref -> do+ out <- withPartFile $ \part -> act opts0{output_file_ = Just part, output_format_ = if supportsHtml then Just "html" else Nothing}+ modifyIORef ref ((unwords $ map quoteForCommandLine cmdline, Just out) :)+ supportsHtml = any (\f -> "output-format" `elem` flagNames f && "html" `isInfixOf` flagHelp f) $ modeFlags cmdmode+ opts = opts0+ let+ rawopts = rawopts_ opts+ mmodecmdname = headMay $ modeNames cmdmode+ helpFlag = boolopt "help" rawopts+ examplesFlag = boolopt "examples" rawopts+ infoFlag = boolopt "info" rawopts+ manFlag = boolopt "man" rawopts+ if+ | helpFlag -> runPager $ showModeUsage cmdmode ++ "\n"+ | examplesFlag -> runTldrForPage $ maybe "hledger" (("hledger-"<>)) mmodecmdname+ | infoFlag -> runInfoForTopic "hledger" mmodecmdname+ | manFlag -> runManForTopic "hledger" mmodecmdname+ | cmdname `elem` journalIgnoringCommandNames ->+ -- help/setup never read the journal, as at the CLI+ cmdaction opts nulljournal+ | cmdname `elem` journalCreatingCommandNames ->+ -- add and import can create a nonexistent journal file, as they do at the CLI+ withPossibleRunJournal defaultJournalOverride opts (cmdaction opts)+ | otherwise -> do+ withJournalCached (Just defaultJournalOverride) opts $ \(j,jpaths) -> do+ if cmdname == "run" -- allow "run" to call "run"+ then run (Just jpaths) findBuiltinCommand addons cmdaliases shellaliasesallowed opts+ else collect $ \o -> cmdaction o j+ Nothing | cmdname `elem` addons ->+ -- Pass the session's explicit input files to the addon, so it uses the same journal+ -- (as the CLI does by forwarding its -f options to addons).+ runShellCommandOrExit (printf "%s-%s %s" progname cmdname (unwords $ map quoteForCommandLine $ addonfileargs <> args))+ Nothing ->+ error' $ "Unrecognized command" ++ aliasnote ++ ": " ++ unwords (cmdname:args)+ [] -> return ()++-- | Run an interactive REPL. mconfinfo is the active config file and the raw options+-- needed to re-read it, used to auto-reload command aliases when the config file changes.+-- mrescanAddons is an action that re-scans PATH for addon commands, used to auto-reload the+-- addon command list when PATH's contents change. Either being Nothing disables that reload+-- (eg for a non-interactive "run").+-- watch enables the automatic reloading of changed files/aliases/addons (disabled by --no-watch).+runREPL :: DefaultRunJournal -> [(String,String)] -> [String] -> (String -> Maybe (Mode RawOpts, CliOpts -> Journal -> IO ())) -> [String] -> [(CommandAlias,CommandLine)] -> Bool -> Maybe RunSections -> Maybe (FilePath, RawOpts) -> Maybe (IO [String]) -> Bool -> IO ()+runREPL defaultJournalOverride@(DefaultRunJournal jpaths) rungeneralopts addonfileargs findBuiltinCommand addons cmdaliases shellaliasesallowed mcollect mconfinfo mrescanAddons watch = do+ isTerminal <- isStdinTerminal+ -- Mutable alias and addon state, so these can be reloaded when their sources change on disk.+ confmtime0 <- maybe (return 0) (fmap (fromMaybe 0) . maybeFileModificationTime . fst) mconfinfo+ aliasesRef <- newIORef (confmtime0, cmdaliases)+ pathmtime0 <- maybe (return 0) (const maxSearchPathMtime) mrescanAddons+ addonsRef <- newIORef (pathmtime0, addons)+ if not isTerminal+ then runInputT defaultSettings (loop aliasesRef addonsRef False "")+ else do+ -- Show a startup banner: the program name and version and a usage hint,+ -- coloured with a gradient like the commands list when supported.+ -- w <- fromMaybe 80 <$> getTerminalWidth+ -- The interactive prompt is coloured only in terminals that fully emulate one.+ -- Emacs's M-x shell (comint) advertises xterm but mishandles the cursor movement+ -- haskeline uses to redraw a prompt containing escape codes, garbling the display;+ -- there we use a plain prompt (the banner above is fine, being plain putStrLn output).+ emacs <- insideEmacsNotVterm+ let+ grad intensity row s = gradientStr intensity 2 (length s) row 0 s+ fpath = snd $ splitReaderPrefix $ NE.head jpaths+ --------------------------------------80----------------------------------------+ title = progname <> " " <> packageversion+ hint = "Ready for hledger or !shell commands. For help: h or h -h. To exit: q or ctrl-d."+ promptbase = takeBaseName fpath ++ "> "+ prompt = if emacs then promptbase else stxMarkEscapes $ grad faint' 2 promptbase+ -- putStrLn $ grad faint' 0 $ replicate w '-'+ putStrLn $ grad bold' 1 title+ putStrLn $ faint' hint+ -- Then run the REPL loop.+ runInputT defaultSettings (loop aliasesRef addonsRef True prompt)++ where+ loop :: IORef (POSIXTime,[(CommandAlias,CommandLine)]) -> IORef (POSIXTime,[String]) -> Bool -> String -> InputT IO ()+ loop aliasesRef addonsRef interactive prompt = do+ minput <- getInputLine prompt+ case minput of+ Nothing -> return ()+ Just "q" -> return ()+ Just "quit" -> return ()+ Just "exit" -> return ()+ Just input -> do+ -- Reload any changed input files, config aliases or addon commands, then run the command.+ -- All are guarded by the handlers below (interactively), so a control-C during any of them+ -- returns to the prompt rather than exiting the REPL.+ let action = do+ when watch $ do+ refreshStaleJournals+ refreshStaleAliases mconfinfo aliasesRef+ refreshStaleAddons mrescanAddons addonsRef+ (_, cmdaliases') <- readIORef aliasesRef+ (_, addons') <- readIORef addonsRef+ case strip input of+ "!" -> return () -- a bare !, do nothing+ '!':shcmd -> hFlush stdout >> void (system shcmd) -- !SHELLCMD, run the rest as a shell command+ -- h is a short alias for the help command.+ _ -> runCommand defaultJournalOverride rungeneralopts addonfileargs findBuiltinCommand addons' cmdaliases' shellaliasesallowed mcollect $+ case parseCommand input of+ "h":rest -> "help":rest+ cmd -> cmd+ liftIO $ if interactive+ then action `catches`+ [Handler (\(e::ErrorCall) -> putStrLn $ rstrip $ show e)+ ,Handler (\(e::IOError) -> putStrLn $ rstrip $ show e)+ ,Handler (\(_::ExitCode) -> return ())+ ,Handler (\UserInterrupt -> hPutStrLn stderr "(interrupted)")+ ]+ else action+ loop aliasesRef addonsRef interactive prompt++isStdinTerminal = do+ op <- hIsOpen stdin+ if op then hIsTerminalDevice stdin else return False++-- | Mark any ANSI escape sequences (eg SGR colour/style codes) in a string as zero-width+-- for haskeline, by appending a \STX character to each. Haskeline treats text between+-- \ESC and \STX as zero-width; without this, escape codes in the prompt make it+-- miscalculate the prompt's width, garbling the display.+stxMarkEscapes :: String -> String+stxMarkEscapes ('\ESC':cs) =+ case break (=='m') cs of -- SGR escape sequences end with 'm'+ (code, 'm':rest) -> '\ESC' : code ++ "m\STX" ++ stxMarkEscapes rest+ _ -> '\ESC' : cs -- unterminated escape sequence, leave as is+stxMarkEscapes (c:cs) = c : stxMarkEscapes cs+stxMarkEscapes "" = ""++-- | Cache of all journals that have been read by commands given to "run",+-- keyed by the fully-expanded filename.+journalCache :: MVar (Map.Map (InputOpts,PrefixedFilePath) Journal)+journalCache = unsafePerformIO $ newMVar Map.empty+{-# NOINLINE journalCache #-}++-- | Cache of stdin contents, so that we can re-read it if InputOptions change+stdinCache :: MVar (Maybe T.Text)+stdinCache = unsafePerformIO $ newMVar Nothing+{-# NOINLINE stdinCache #-}++-- | A changed file F is being reloaded: print a "(reloading F)" notice, read the new value+-- with the given action (catching synchronous errors so an async exception such as a control-C+-- still propagates), then either apply it with onSuccess, or on failure print+-- "could not reload F, keeping previous THING" and run onKeepPrevious. Shared by the journal-data+-- and config-alias reloads to keep their notices and error handling identical.+reloadChanged :: FilePath -> String -> IO (Either String a) -> (a -> IO ()) -> IO () -> IO ()+reloadChanged fp thing readNew onSuccess onKeepPrevious = do+ hPutStrLn stderr $ "(reloading " ++ fp ++ ")"+ hFlush stderr+ enew <- readNew `catches`+ [Handler (\(e::IOError) -> return $ Left $ show e)+ ,Handler (\(e::ErrorCall) -> return $ Left $ show e)]+ case enew of+ Right new -> onSuccess new+ Left err -> do+ hPutStrLn stderr $ "could not reload " ++ fp ++ ", keeping previous " ++ thing ++ ":\n" ++ err+ onKeepPrevious++-- | Re-read any cached journals whose files (main or included) have changed on+-- disk since they were last read, updating the cache in place. Called at the top+-- of each REPL loop iteration so that commands see the latest file contents.+-- Prints a visible notice on stderr for each reload, and, if a changed file no+-- longer parses, keeps the previous version and prints the error.+refreshStaleJournals :: IO ()+refreshStaleJournals = do+ cache <- readMVar journalCache+ forM_ (Map.toList cache) $ \((iopts,fp), j) -> do+ changed <- anyM (journalFileIsNewer j) (journalAllFilePaths j)+ when changed $+ reloadChanged fp "version" (runExceptT $ readJournalFile iopts fp)+ (\j' -> modifyMVar_ journalCache $ return . Map.insert (iopts,fp) j')+ -- On failure advance the cached journal's read time past its current files, so we report+ -- the error once and stay quiet until a file changes again.+ (do newest <- maximum . (jlastreadtime j :) . catMaybes <$> mapM maybeFileModificationTime (journalAllFilePaths j)+ modifyMVar_ journalCache $ return . Map.adjust (journalSetLastReadTime newest) (iopts,fp))++-- | If the config file has changed on disk since its command aliases were last read,+-- re-read them into the given ref. Prints a "(reloading CONFFILE)" notice before reading and,+-- if the file no longer parses, keeps the previous aliases and prints the error - consistent+-- with the journal data reload.+refreshStaleAliases :: Maybe (FilePath, RawOpts) -> IORef (POSIXTime,[(CommandAlias,CommandLine)]) -> IO ()+refreshStaleAliases Nothing _ = return ()+refreshStaleAliases (Just (conffile, rawopts)) ref = do+ mmtime <- maybeFileModificationTime conffile+ case mmtime of+ Nothing -> return () -- config file no longer exists; keep current aliases+ Just mtime -> do+ (lastseen, oldaliases) <- readIORef ref+ when (mtime > lastseen) $+ reloadChanged conffile "aliases" readAliases+ (\as -> writeIORef ref (mtime, as))+ -- On failure advance the marker but keep the old aliases, so we report the error once+ -- and stay quiet until the file changes again.+ (writeIORef ref (mtime, oldaliases))+ where+ -- Re-read the config file's command aliases, forcing them so any error in a malformed+ -- [alias] line is raised here (and caught by reloadChanged) rather than later during expansion.+ readAliases = do+ econf <- getConf rawopts+ case econf of+ Left e -> return $ Left e+ Right (conf, _) -> do+ let as = reverse $ confAliases conf+ mapM_ evaluate as+ return $ Right as++-- | If a PATH directory has changed since the addon command list was last scanned,+-- re-scan for addon commands with the given action and update the ref. Prints a+-- "(reloaded addons)" notice only when the set of addon commands actually changed+-- (a PATH directory's mtime can change without affecting which hledger-* executables exist).+refreshStaleAddons :: Maybe (IO [String]) -> IORef (POSIXTime,[String]) -> IO ()+refreshStaleAddons Nothing _ = return ()+refreshStaleAddons (Just rescan) ref = do+ mtime <- maxSearchPathMtime+ (lastseen, oldaddons) <- readIORef ref+ when (mtime > lastseen) $ do+ newaddons <- rescan+ writeIORef ref (mtime, newaddons)+ when (newaddons /= oldaddons) $ hPutStrLn stderr "(reloaded addons)"++-- | The most recent modification time among the existing directories on the PATH.+-- A directory's mtime changes when entries are added or removed, so this detects when+-- the set of installed addon commands may have changed.+maxSearchPathMtime :: IO POSIXTime+maxSearchPathMtime = do+ dirs <- getSearchPath+ mtimes <- mapM maybeDirModificationTime dirs+ return $ maximum (0 : catMaybes mtimes)++-- | The last modified time of the specified directory, if it exists.+maybeDirModificationTime :: FilePath -> IO (Maybe POSIXTime)+maybeDirModificationTime d = do+ exists <- doesDirectoryExist d+ if exists then Just . utcTimeToPOSIXSeconds <$> getModificationTime d else return Nothing++-- | Get the journal(s) to read: the command's own -f files if any, else the run/repl session's+-- journal(s) (defaultJournalOverride), else the default journal path. The path need not exist -+-- like add/import at the CLI, we let commands create it or report the error, rather than requiring+-- it up front (which would stop run/repl starting when there is no journal yet).+journalFilePathFromOptsOrDefault :: Maybe DefaultRunJournal -> CliOpts -> IO (NE.NonEmpty PrefixedFilePath)+journalFilePathFromOptsOrDefault defaultJournalOverride cliopts = do+ mbjournalpaths <- journalFilePathFromOptsNoDefault cliopts+ case mbjournalpaths of+ Just journalpaths -> return journalpaths -- the command's own -f files+ Nothing -> case defaultJournalOverride of+ Just (DefaultRunJournal defaultFiles) -> return defaultFiles -- the journal(s) given to run/repl+ Nothing -> NE.fromList . pure <$> defaultJournalPath -- the default journal path (need not exist)++-- | Like withJournalCached, but tolerates a nonexistent first journal file (providing an empty+-- journal with that path set), so add and import can create it - as they do at the CLI. Does not+-- cache, since these commands write to the file.+withPossibleRunJournal :: DefaultRunJournal -> CliOpts -> (Journal -> IO ()) -> IO ()+withPossibleRunJournal defaultJournalOverride cliopts cmd = do+ journalpaths <- journalFilePathFromOptsOrDefault (Just defaultJournalOverride) cliopts+ ej <- runExceptT $ journalTransform cliopts <$> readPossibleJournalFiles (inputopts_ cliopts) (NE.toList journalpaths)+ either error' cmd ej++-- | Similar to `withJournal`, but caches all the journals it reads.+-- When reading from stdin, also caches the stdin contents so that we could reprocess+-- it if a read with different InputOptions is requested.+withJournalCached :: Maybe DefaultRunJournal -> CliOpts -> ((Journal, DefaultRunJournal) -> IO ()) -> IO ()+withJournalCached defaultJournalOverride cliopts cmd = do+ journalpaths <- journalFilePathFromOptsOrDefault defaultJournalOverride cliopts+ j <- readFiles journalpaths+ cmd (j,DefaultRunJournal journalpaths)+ where+ readFiles journalpaths =+ journalTransform cliopts . sconcat <$> mapM (readAndCacheJournalFile (inputopts_ cliopts)) journalpaths+ -- | Read a journal file, caching it (and InputOptions used to read it) if it has not been seen before.+ -- If the same file is requested with different InputOptions, we read it anew and cache+ -- it separately.+ readAndCacheJournalFile :: InputOpts -> PrefixedFilePath -> IO Journal+ readAndCacheJournalFile iopts fp = do+ modifyMVar journalCache $ \cache ->+ case Map.lookup (ioptsWithoutReportSpan,fp) cache of+ Just journal -> do+ dbg1IO ("readAndCacheJournalFile using cache for "++fp) iopts+ return (cache, journal)+ Nothing -> do+ dbg1IO ("readAndCacheJournalFile reading and caching "++fp) iopts+ journal <- runExceptT $ if isStdin fp then readStdin else readJournalFile iopts fp+ either error' (\j -> return (Map.insert (ioptsWithoutReportSpan,fp) j cache, j)) journal+ where+ -- InputOptions contain reportspan_ that is used to calculate forecast period,+ -- that is used by journalFinalise to insert forecast transactions.+ -- For the purposes of caching, we want to ignore it whenever+ -- --forecast is not used, or when explicit dates are requested.+ ioptsWithoutReportSpan = iopts{ reportspan_ = forecastreportspan }+ where+ forecastreportspan = case forecast_ iopts of+ Nothing -> emptydatespan+ -- This could be better if we had access to the journal (as we+ -- could use 'forecastPeriod') or to the journal end date (as+ -- forecast transactions are never generated before journal end+ -- unless specifically requested).+ Just forecastspan -> forecastspan `spanValidDefaultsFrom` reportspan_ iopts+ -- Read stdin, or if we read it already, use a cache+ -- readStdin :: InputOpts -> ExceptT String IO Journal+ readStdin = do+ stdinContent <- liftIO $ modifyMVar stdinCache $ \cache ->+ case cache of+ Just cached -> do+ dbg1IO "readStdin using cached stdin" "-"+ return (cache, cached)+ Nothing -> do+ dbg1IO "readStdin reading and caching stdin" "-"+ stdinContent <- readFileOrStdinPortably "-"+ return (Just stdinContent, stdinContent)+ hndl <- liftIO $ textToHandle stdinContent+ readJournal iopts Nothing hndl
+ Hledger/Cli/Commands/Run.txt view
@@ -0,0 +1,113 @@+run++Run a sequence of hledger commands, provided as files or command line+arguments. Input files are parsed just once, so the commands run faster.++Flags:+ -O --output-format=FMT select the output format. Supported formats:+ html.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ --view write output to FILE, or to view.FMT in hledger's+ cache directory, and open it in the system's+ default viewer for its format (eg a web browser for+ html). The default format is html.++You can use run in three ways:++- hledger run -- CMD1 -- CMD2 -- CMD3 - read commands from the command+ line, separated by --+- hledger run SCRIPTFILE1 SCRIPTFILE2 - read commands from one or more+ files+- cat SCRIPTFILE1 | hledger run - read commands from standard input.++run first loads the input file(s) specified by LEDGER_FILE or by -f+options, in the usual way. Then it runs each command in turn, each using+the same input data. But if you want a particular command to use+different input, you can specify an -f option within that command. This+will override (not add to) the default input, just for that command.++Any other general flags given to run - input, reporting, or display+flags such as -I, --strict, --alias, -b/-e, --depth, --cost, --value,+--color - are also applied to every command it runs. A command can still+override them by specifying its own flags.++Each input file (more precisely, each combination of input file and+input options) is parsed only once. This means that commands will not+see any changes made to these files, until the next run. But the+commands will run more quickly than if run individually (typically about+twice as fast).++Command scripts, whether in a file or written on the command line, have+a simple syntax:++- each line may contain a single hledger command and its arguments,+ without the usual hledger first word+- empty lines are ignored+- text from # to end of line is a comment, and ignored+- you can use single or double quotes to quote arguments when needed, as+ on the command line+- these extra commands are available: echo TEXT prints some text+ (interpreting the backslash escapes \n, \t, \r, \\), and exit or quit+ ends the run.++On unix systems you can use #!/usr/bin/env hledger run in the first line+of a command file to make it a runnable script. If that gives an error,+use #!/usr/bin/env -S hledger run.++It's ok to use the run command recursively within a command script.++With -O html, -o FILE.html or --view, run collects the commands' outputs+into one HTML page instead of printing them: a section for each command,+headed by its command line, which can be folded; and a heading for each+echo. Commands which can produce HTML (the balance commands, register,+aregister, print, holdings, activity) do so, charts included; others'+text output is shown as is. --view then opens the page in your web+browser (see Output destination), which is a convenient way to see+several reports, or charts, at once:++$ hledger run --view -- echo Overview -- is -M --chart -- bs -Q --chart -- reg expenses -p thismonth++Command aliases defined in a config file can also be used in command+scripts.++You may find some differences in behaviour between run command lines and+normal hledger command lines. run is a little stricter; eg it requires+full command names or official abbreviations (as seen in the commands+list), and command options must be written after the command name.++Examples++Run commands from the command line:++hledger -f some.journal run -- balance assets --depth 2 -- balance liabilities -f /some/other.journal --depth 3 --transpose -- stats++This would load some.journal, run balance assets --depth 2 on it, then+run balance liabilities --depth 3 --transpose on /some/other.journal,+and finally run stats on some.journal++Run commands from standard input:++(echo "files"; echo "stats") | hledger -f some.journal run++Run commands as a script:++$ cat report+#!/usr/bin/env -S hledger run -f some.journal++echo "List of accounts in some.journal"+accounts++echo "Assets of some.journal"+balance assets --depth 2++echo "Liabilities from /some/other.journal"+balance liabilities -f /some/other.journal --depth 3 --transpose++echo "Commands from another.script, applied to another.journal"+run -f another.journal another.script++$ chmod +x report+$ ./report+List of accounts in some.journal+...
+ Hledger/Cli/Commands/Setup.hs view
@@ -0,0 +1,702 @@+{-|++Check and show the status of the hledger installation.++-}+{-+Old design notes:++## Goals+- Make getting started with hledger and PTA easier and quicker, to+ (a) make this practical for more people (non techies, busy techies..)+ (b) free up more time and energy for learning and doing PTA and finance++Subgoals:+- Reduce the special knowledge and docs needed after install, to get a standard setup working (especially on windows)+- Help with discovery and setup of advanced quality of life terminal features+- Assist with setting up a first or new journal file+- Deliver relevant install/setup/config expertise more efficiently, freeing up dev and support time++## Design+Why a built in command and not a shell script, haskell script, or docs ?+So it is available and runs reliably anywhere a hledger executable runs, and so it can detect more context-specific advice.+(Optionally use shell or haskell scripts for prototyping, if that's helpful)++## Setup checks+Somewhat ordered.+These deal with the complexities of terminals, the shell, GHC, hledger, and the user's machine, locale, and data.+Initially just informational hints.+Later, add automated or interactive diagnosis and repair attempts,+and semi-persistent state (invalidated at suitable times).+These checks are a necessary evil/stopgap; long term, automate/replace/remove them whenever possible.++-}++-- {-# LANGUAGE DeriveGeneric #-}+{-# LANGUAGE OverloadedStrings #-}+-- {-# LANGUAGE NamedFieldPuns #-}+-- {-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TemplateHaskell #-}++{-# OPTIONS_GHC -Wno-name-shadowing #-}+{-# OPTIONS_GHC -Wno-unused-top-binds #-}+{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE RecordWildCards #-}+-- {-# OPTIONS_GHC -Wno-unused-matches #-}++module Hledger.Cli.Commands.Setup (+ setupmode+ ,setup+)+where++import Control.Concurrent (rtsSupportsBoundThreads)+import Control.Exception+import Control.Monad+-- import Data.ByteString qualified as B+import Data.Char+import Data.Default (def)+import Data.List+import Data.Map qualified as M+import Data.Maybe+import Data.Text qualified as T+import Data.Text.Encoding qualified as T+import Data.Version qualified (showVersion)+import Network.HTTP.Client+import Network.HTTP.Types (statusCode, hLocation)+import Network.HTTP.Req as R+import Safe+import System.Directory+import System.Environment (getEnvironment, lookupEnv)+import System.Exit+import System.FilePath+import System.Info+import System.Process+import Text.Printf (printf)++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Conf+import Hledger.Cli.Version+import System.Console.ANSI (hSupportsANSIColor)+import System.IO (localeEncoding, stdout, hFlush, hIsTerminalDevice)+++setupmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Setup.txt")+ []+ [generalflagsgroup3]+ []+ ([], Nothing)+++{- | Test and print the status of various aspects of the hledger installation.+May also show extra info and hints on how to fix problems.+The goal is to detect and show as much useful information as possible,+and to complete this task reliably regardless of what we find,+without premature termination or misformatting.++The tests are grouped into setup* routines, so named because they might do more+than just test in future.++This is the second version of setup. If it finds that the currently+running hledger is not the one installed in PATH (by comparing --version output),+it refuses to proceed further until that has been done.+This means it can rely on all the latest features and use the hledger API+within this process, simplifying things greatly.+-}+setup :: CliOpts -> Journal -> IO ()+setup _opts@CliOpts{rawopts_=_rawopts, reportspec_=_rspec} _ignoredj = do+ -- This command is not given a journal and should not use _ignoredj;+ -- instead read it ourselves when we are ready.+ putStrLn "Checking your setup (and contacting hledger.org to find out the current release):"+ -- color <- useColorOnStdout+ -- when color $ + -- putStrLn $ "Legend: " <> intercalate ", " [+ -- good "good"+ -- ,neutral "neutral"+ -- ,warning "unknown"+ -- ,bad "warning"+ -- ]+ elatestversionnumstr <- getLatestHledgerVersion+ meconf <- setupHledger elatestversionnumstr+ setupTerminal meconf+ setupJournal meconf+ -- putStr "\n"++------------------------------------------------------------------------------++-- Returns Nothing if no config file was found,+-- or Just the read error or config if it was found.+setupHledger :: Either String String -> IO (Maybe (Either String Conf))+setupHledger elatestversionnumstr = do+ pgroup "hledger"++ let+ os'+ | os=="darwin" = "macos"+ | os=="mingw32" = "windows"+ | otherwise = os+ mosversion <- getOSVersion+ let osdesc = os' <> maybe "" (" "<>) mosversion+ pdesc "is running on"+ putStrLn $ " " <> osdesc <> " on " <> arch++ pdesc "is built with a supported compiler/RTS"+ p (if rtsSupportsBoundThreads then Y else N) $ + compilerName <> " " <> Data.Version.showVersion fullCompilerVersion+ <> if rtsSupportsBoundThreads then ", using threaded RTS" else ", RTS does not have threads enabled"++ pdesc "is a native binary for this machine ?"+ case hbinArch binaryinfo of+ Nothing -> p U $ "couldn't detect this binary's architecture"+ Just a | a /= arch -> p N $ "binary is for " <> a <> ", system is " <> arch <> ", may run slowly"+ Just a -> p Y a++ pdesc "is a released version ?"+ if isReleaseVersion $ hbinPackageVersion binaryinfo+ then p Y prognameandversion+ else i N prognameandversion++ pdesc "is up to date ? checking latest..." >> hFlush stdout+ case elatestversionnumstr of+ Left e -> p U ("couldn't read " <> latestHledgerVersionUrlStr <> " " <> e)+ Right latestversionnumstr ->+ case toVersion latestversionnumstr of+ Nothing -> p U "couldn't parse latest version number"+ Just latestversion -> p+ (if hbinPackageVersion binaryinfo >= latestversion then Y else N)+ ("latest is " <> latestversionnumstr <> ", " <> showVersion (hbinPackageVersion binaryinfo) <> " is installed")++ pdesc "is installed in PATH (this version) ?"+ pathexes <- findExecutables progname+ let+ (failaction, failmsg) =+ -- (exitFailure , "Please install this hledger in PATH then run setup again.")+ (return () , " Some of this info may not apply to that hledger version. Continuing anyway..")+ case pathexes of+ [] -> p N failmsg >> failaction+ exe:_ -> do+ eerrout <- tryHledgerArgs [["--version", "--no-conf"], ["--version"]]+ case eerrout of+ Left err -> p U (progname <> " --version failed: " <> err) >> failaction+ Right out -> do+ case parseHledgerVersion out of+ Left _ -> p U ("couldn't parse " <> progname <> " --version: " <> rstrip out) >> exitFailure+ Right pathbin -> do+ let pathversion = hbinVersionOutput pathbin+ if pathversion /= prognameandversion+ then p N (chomp $ unlines [+ ""+ ," A different hledger version was found in PATH: " <> pathversion+ ," at: " <> exe+ ,failmsg+ ]) >> failaction+ else p Y exe++ pdesc "has a system text encoding configured ?"+ let encoding = localeEncoding -- the initial system encoding+ if map toLower (show encoding) == "ascii"+ then p N (show encoding <> ", please configure an encoding for non-ascii data")+ else p Y (show encoding <> ", data files must use this encoding")++ -- pdesc "can handle UTF-8 text ?"+ -- let+ -- eAcuteUtf8 = B.pack [0xC3, 0xA9]+ -- eAcuteLatin1 = B.pack [0xE9]+ -- case T.decodeUtf8' eAcuteUtf8 of+ -- Left _ -> p N "hledger's docs and examples use UTF-8"+ -- Right t -> p Y (T.unpack t)++ -- pdesc "can report text decoding failures ?"+ -- i U (T.unpack $ T.decodeUtf8 eAcuteLatin1)++ pdesc "has a user config file ?"+ muf <- activeUserConfFile+ mlf <- activeLocalConfFile+ let+ (ok, msg) = case muf of+ Just f -> (Y, f <> if isJust mlf then " (overridden)" else "")+ Nothing -> (N, "")+ i ok msg++ pdesc "has a local config file ?"+ let+ (ok, msg) = case mlf of+ Just f -> (Y, f)+ Nothing -> (N, "")+ i ok msg++ if (isJust muf || isJust mlf) then do+ pdesc "the config file is readable ?"+ econf <- getConf def+ case econf of+ Left e -> p N e >> return (Just $ Left e)+ Right (conf, _) -> do+ p Y ""++ -- pdesc "common general options are configured ?"+ -- --infer-costs"+ -- print --explicit --infer-costs"++ return $ Just $ Right conf+ else+ return Nothing++------------------------------------------------------------------------------++setupTerminal meconf = do+ pgroup "terminal"+ let+ -- Find the last opt/arg matched by a predicate in the general config, if there is one.+ conflookup predicate = case meconf of+ Just (Right conf) -> find predicate $ reverse $ confLookup "general" conf+ _ -> Nothing++ pdesc "the TERM variable is defined ?"+ mterm <- lookupEnv "TERM"+ let dumbterminal = (map toLower <$> mterm) == Just "dumb"+ case mterm of+ Nothing -> i N "terminal type is unknown"+ Just v -> i Y $ v <> if dumbterminal then " (color and styles will not be used)" else ""++ pdesc "the terminal supports ANSI color ?"+ isterminal <- hIsTerminalDevice stdout+ supportscolor <- hSupportsANSIColor stdout+ truecolor <- supportsTrueColor+ if not supportscolor then i N $ if isterminal then "" else "stdout is not a terminal"+ else i Y $ if+ | truecolor -> "24-bit color (COLORTERM is set)"+ | "256color" `isInfixOf` fromMaybe "" mterm -> "256 colors"+ | otherwise -> "16 colors"++ pdesc "the NO_COLOR variable is defined ?"+ mnocolor <- lookupEnv "NO_COLOR"+ case mnocolor of+ Nothing -> i N ""+ Just _ -> i Y ""++ meconfigcolor <- do+ pdesc "--color is configured by config file ?"+ let mcolorarg = conflookup (\a -> any (`isPrefixOf` a) ["--color", "--colour"])+ case mcolorarg of+ Nothing -> i N "" >> return Nothing+ Just a -> do+ i Y a+ let+ arg = reverse $ takeWhile (`notElem` ['=',' ']) $ reverse a+ return $ Just $ parseYNA arg++ -- Use the same logic as the rest of hledger, and explain a negative result.+ -- (The config file is not applied to setup itself, so its --color is checked here.)+ pdesc "hledger will use color by default ?"+ usecolor <- case meconfigcolor of+ Just (Right Yes) -> return True+ Just (Right No) -> return False+ _ -> useColorOnStdout+ coloropt <- colorOption+ if usecolor then p Y ""+ else i N $ if+ | meconfigcolor == Just (Right No) -> "disabled by config file"+ | coloropt == No -> "disabled by --color"+ | isJust mnocolor -> "disabled by NO_COLOR"+ | dumbterminal -> "disabled by TERM=dumb"+ | not isterminal -> "stdout is not a terminal"+ | not supportscolor -> "the terminal does not support ANSI color"+ | otherwise -> ""++ pdesc "the PAGER variable is defined ?"+ mv <- lookupEnv "PAGER"+ case mv of+ Nothing -> i N ""+ Just v -> i Y v++ pdesc "--pager is configured by config file ?"+ let mpagerarg = conflookup ("--pager" `isPrefixOf`)+ meconfpager <- case mpagerarg of+ Nothing -> i N "" >> return Nothing+ Just a -> do+ i Y a+ let arg = reverse $ takeWhile (`notElem` ['=',' ']) $ reverse a+ return $ Just $ parseYNA arg++ pdesc "hledger will use a pager when needed ?"+ mpager <- findPager+ case mpager of+ Nothing -> i N "no pager was found"+ Just pager ->+ case meconfpager of+ Just (Right No) -> i N "disabled in config file"+ _ -> do+ p Y pager++ when (map toLower (takeBaseName pager) == "more") $ do+ pdesc "the MORE variable is defined ?"+ mv <- lookupEnv "MORE"+ case mv of+ Nothing -> i N ""+ Just v -> i Y v++ when (map toLower (takeBaseName pager) == "less") $ do+ mHLEDGER_LESS <- lookupEnv "HLEDGER_LESS"+ mLESS <- lookupEnv "LESS"++ pdesc "the LESS variable is defined ?"+ case mLESS of+ Nothing -> i N ""+ Just v -> i Y $ v <> if isJust mHLEDGER_LESS then " (overridden)" else ""++ pdesc "the HLEDGER_LESS variable is defined ?"+ case mHLEDGER_LESS of+ Nothing -> i N ""+ Just v -> i Y v++ when (isNothing mHLEDGER_LESS) $ do+ pdesc "adjusting LESS var for consistent UX ?"+ usecolor <- useColorOnStdout+ i Y $ lessVarValue mHLEDGER_LESS mLESS usecolor++ pdesc "less is working, with these options ?"+ usecolor <- useColorOnStdout+ let newlessvar = lessVarValue mHLEDGER_LESS mLESS usecolor+ env <- getEnvironment+ let customEnv = ("LESS", newlessvar) : filter ((/= "LESS") . fst) env+ lessHasError <- lessIsWorking (Just customEnv)+ if lessHasError+ then p N "less --version shows a problem, check LESS/HLEDGER_LESS settings"+ else p Y ""++ pdesc "box-drawing chars are used by default ?"+ if isJust $ conflookup ("--pretty"==)+ then p Y ""+ else i N "you can add --pretty to enable them"++ -- pdesc "bash shell completions are installed ?" >> p U ""+ -- pdesc "zsh shell completions are installed ?" >> p U ""++------------------------------------------------------------------------------++setupJournal meconf = do+ pgroup "journal"+ let+ -- Find the last opt/arg matched by a predicate in the general config, if there is one.+ conflookup predicate = case meconf of+ Just (Right conf) -> find predicate $ reverse $ confLookup "general" conf+ _ -> Nothing++ -- pdesc "a home directory journal file exists ?"+ -- mh <- getHomeSafe+ -- (ok,msg) <- case mh of+ -- Just h -> do+ -- let f = h </> journalDefaultFilename+ -- e <- doesFileExist f+ -- return (if e then Y else N, if e then f else "")+ -- Nothing -> return (N, "")+ -- i ok msg++ pdesc "the LEDGER_FILE variable is defined ?"+ mf <- lookupEnv journalEnvVar+ let+ (ok, msg) = case mf of+ Just "" -> (N, "defined, but with a null value")+ Just f -> (Y, f)+ Nothing -> (N, "")+ i ok msg++ -- case mf of+ -- Nothing -> return ()+ -- Just f -> do+ -- pdesc "$LEDGER_FILE journal exists ?"+ -- e <- doesFileExist f+ -- i e "" ""++ -- when (isJust mh && isJust mf) $ do+ -- pdesc "$LEDGER_FILE is masking home journal ?"+ -- i Y ""++ pdesc "a default journal file is readable ?"+ ef <- defaultJournalPathSafely+ -- let+ -- args = concat [+ -- ["print"],+ -- ["--ignore-assertions" | supportsIgnoreAssertions version],+ -- ["--no-conf" | supportsConfigFiles version]+ -- ]+ -- (exit, _, err) <- readProcessWithExitCode progname args ""+ -- XXX can this ignore assertions and config files, like the above ?+ ej <- defaultJournalSafely+ let trim s = either (const s) id $ regexReplace (toRegex' "^Error: ") "" s+ case (ef, ej) of+ (Left err, _) -> p N $ trim err+ (Right f, Left err) -> do+ -- show a missing file compactly, other read errors in full+ exists <- doesFileExist f+ p N $ if exists then f <> ":\n" <> trim err else f <> " (not found)"+ journalFilesystemCanAppend f+ (Right f, Right j@Journal{..}) -> do+ p Y f+ journalFilesystemCanAppend f++ pdesc "it includes additional files ?"+ let numfiles = length jfiles+ if numfiles > 1+ then i Y (show (numfiles - 1) <> " files")+ else i N ""++ pdesc "all commodities are declared ?"+ let+ numcommodities = length $ journalCommodities j+ undeclaredcommodities = journalUndeclaredCommodities j -- same logic as "hledger check commodities"+ if null undeclaredcommodities+ then p Y (show numcommodities <> " commodities")+ else p N (show (length undeclaredcommodities) <> " undeclared commodities")++ let+ -- The basic types which the bs/bse/is/cf reports depend on+ -- (subtypes like Cash also count as their parent type, as in those reports),+ -- and the reports which will be empty when a type has no accounts.+ basictypes = [Asset, Liability, Equity, Revenue, Expense, Cash]+ typesdetected = nub $ M.elems jaccounttypes+ hastype t = any (`isAccountSubtypeOf` t) typesdetected+ typesnotfound = filter (not . hastype) basictypes+ missing = any (`elem` typesnotfound)+ reportsaffected = concat+ [ ["bs" | missing [Asset, Liability]] -- and bse, implied+ , ["bse" | missing [Equity], not $ missing [Asset, Liability]]+ , ["is" | missing [Revenue, Expense]]+ , ["cf" | missing [Cash]]+ ]+ acctswithdeclaredorinferredtype = nub (M.keys jaccounttypes)+ numaccts = length $ journalAccountNames j+ untypedaccts = journalAccountNames j \\ acctswithdeclaredorinferredtype+ undeclaredaccts = journalAccountNamesUsed j \\ journalAccountNamesDeclared j+ -- hasdeclaredaccts t = case M.lookup t jdeclaredaccounttypes of+ -- Just (_ : _) -> True+ -- _ -> False++ -- pdesc "Asset accounts declared ?" + -- if hasdeclaredaccts Asset then i Y "" else i N ""++ -- pdesc "Liability accounts declared ?"+ -- if hasdeclaredaccts Liability then i Y "" else i N ""++ -- pdesc "Equity accounts declared ?"+ -- if hasdeclaredaccts Equity then i Y "" else i N ""++ -- pdesc "Revenue accounts declared ?"+ -- if hasdeclaredaccts Revenue then i Y "" else i N ""++ -- pdesc "Expense accounts declared ?"+ -- if hasdeclaredaccts Expense then i Y "" else i N ""++ -- pdesc "Cash accounts declared ?"+ -- if hasdeclaredaccts Cash then i Y "" else i N ""++ -- pdesc "Conversion accounts declared ?"+ -- if hasdeclaredaccts Conversion then i Y "" else i N "" -- ("--infer-equity will use a default conversion account name")++ -- XXX hard to detect accounts where type was inferred from name+ -- unless arealltypesdeclared $ do+ -- let+ -- acctswithdeclaredtype = concat (M.elems jdeclaredaccounttypes)+ -- acctswithinferredtype = acctswithdeclaredorinferredtype \\ acctswithdeclaredtype+ -- arealltypesdeclared = all hasdeclaredaccts accttypes+ -- typesinferredfromnames =+ -- if arealltypesdeclared then []+ -- else sort $ nub $ catMaybes $ map (flip M.lookup jaccounttypes) acctswithinferredtype+ -- pdesc "types detected from account names ?"+ -- if null typesinferredfromnames then i N "" else i Y (concatMap show typesinferredfromnames)++ pdesc "all accounts are declared ?"+ if null undeclaredaccts then p Y (show numaccts <> " accounts") else i N (show (length undeclaredaccts) <> " undeclared accounts")++ pdesc "all accounts have types ?"+ if null untypedaccts then p Y "" else i N (show (length untypedaccts) <> " accounts without types")++ pdesc "accounts of all basic types exist ?"+ if null typesnotfound+ then p Y (concatMap show basictypes <> " accounts detected")+ else i N (intercalate "/" reportsaffected+ <> (if length reportsaffected == 1 then " needs " else " need ")+ <> concatMap show typesnotfound <> " accounts")++ let strict = isJust $ conflookup (\a -> any (==a) ["-s", "--strict"])++ pdesc "balance assertions checked by default ?"+ let ignoreassertions = isJust $ conflookup (\a -> any (==a) ["-I", "--ignore-assertions"])+ if + | ignoreassertions && not strict -> i N "you can add -s to check them"+ | not strict -> i Y "you can add -I to ignore them"+ | otherwise -> i Y "and can't be ignored, because strict checks are enabled"++ pdesc "lot movements checked by default ?"+ let ignorelots = isJust $ conflookup (\a -> any (==a) ["-I", "--ignore-lots"])+ if+ | ignorelots && not strict -> i N "you can add -s to check them"+ | not strict -> i Y "you can add -I to ignore them"+ | otherwise -> i Y "and can't be ignored, because strict checks are enabled"++ pdesc "strict checks checked by default ?"+ if strict+ then i Y "commodities and accounts must be declared"+ else i N "you can add -s to check them"++------------------------------------------------------------------------------++-- Test a hledger version for support of various features.+ver >=! str = ver >= (fromJust $ toVersion str)+supportsIgnoreAssertions = (>=! "0.24") -- --ignore-assertions (2014)+supportsCommodityDirective = (>=! "1.0") -- commodity directive (2016)+supportsPretty = (>=! "1.2") -- --pretty, to use box-drawing characters (2017)+supportsAccountDirective = (>=! "1.9") -- account directive (2018)+supportsAccountTypes = (>=! "1.13") -- ALERX account types, type: tag (2019)+supportsCashAccountType = (>=! "1.19") -- C/Cash account type (2020)+supportsBasicColor = (>=! "1.19") -- basic color detection/control (2020)+supportsConversionAccountType = (>=! "1.25") -- V/Conversion account type, accounts --types (2022)+supportsConfigFiles = (>=! "1.40") -- config files (2024)+supportsColor = (>=! "1.41") -- robust color detection/control (2024)+supportsPager = (>=! "1.41") -- use a pager for all output (2024)+supportsBashCompletions = (>=! "1.41") -- up to date bash shell completions (2024)++-- yes, no, unknown+data YNU = Y | N | U deriving (Eq)++-- ANSI styles+good = bold' . brightGreen'+neutral = bold' . brightBlue'+warning = bold' . brightYellow'+bad = bold' . brightRed'++-- Show status, in red/green/yellow if supported.+instance Show YNU where+ show Y = good "yes" -- ✅ apple emojis - won't work everywhere+ show N = bad " no" -- ❌+ show U = warning " ?"++-- Show status, in blue/yellow if supported.+showInfo Y = neutral "yes" -- ℹ️+showInfo N = neutral " no" -- ℹ️+showInfo U = warning " ?"++-- | Print a test's pass or fail status, as "yes" or "no" or "",+-- in green/red if supported, and the (possibly empty) provided message.+p :: YNU -> String -> IO ()+p ok msg = putStrLn $ unwords ["", show ok, "", msg]++-- | Like p, but display the status as info, in neutral blue.+i :: YNU -> String -> IO ()+i ok msg = putStrLn $ unwords ["", showInfo ok, "", msg]++-- | Print a setup test groups heading.+pgroup :: String -> IO ()+pgroup s = putStrLn $ -- "\n" <> + bold' s++-- | Print a setup test's description, formatting and padding it to a fixed width.+pdesc :: String -> IO ()+pdesc s = printf " %-40s" s++-- | Probe the journal file's directory to confirm it honors O_APPEND,+-- ie that 'hledger add' will be safe there. Reports the result as a+-- setup check. Any IOException (eg unwritable directory) is reported+-- as unknown rather than a failure.+journalFilesystemCanAppend :: FilePath -> IO ()+journalFilesystemCanAppend f = do+ pdesc "its filesystem supports appending ?"+ let dir = takeDirectory f+ eres <- try (ensureFilesystemCanAppend dir) :: IO (Either IOException Bool)+ case eres of+ Right True -> p Y ""+ Right False -> p N "add/import won't work; use a reliable filesystem"+ Left e -> i U $ "unknown; " <> show e++(getLatestHledgerVersion, latestHledgerVersionUrlStr) =+ -- (getLatestHledgerVersionFromHackage, "https://hackage.haskell.org/package/hledger/docs")+ (getLatestHledgerVersionFromHledgerOrg, "https://hledger.org/install.html")++httptimeout = 10000000 -- 10s++-- | Get the current hledger release version from the internet.+-- Currently requests the latest doc page from Hackage and inspects the redirect path.+-- Should catch all normal errors, and time out after 10 seconds.+getLatestHledgerVersionFromHackage :: IO (Either String String)+getLatestHledgerVersionFromHackage = do+ let url = https "hackage.haskell.org" /: "package" /: "hledger" /: "docs" /: ""+ result <- try $ runReq defaultHttpConfig{httpConfigRedirectCount=0} $+ req HEAD url NoReqBody bsResponse (R.responseTimeout httptimeout)+ case result of+ Right _ -> return $ Left "expected a redirect"+ Left (VanillaHttpException (HttpExceptionRequest _ (StatusCodeException rsp _))) -> do+ let status = statusCode $ responseStatus rsp+ if status >= 300 && status < 400+ then do+ let locationHeader = lookup hLocation (responseHeaders rsp)+ case fmap T.decodeUtf8 locationHeader of+ Nothing -> return $ Left "no Location header"+ Just location -> do+ let packagename = take 1 $ drop 1 $ reverse $ T.splitOn "/" location+ case packagename of+ [n] -> return $ Right $ dropWhile (`notElem` ['0'..'9']) $ T.unpack n+ _ -> return $ Left "couldn't parse Location"+ else return $ Left $ "HTTP status " ++ show status+ Left err -> return $ Left $ "other exception: " ++ show err++-- | Like the above, but get the version from the first number+-- in the first line containing "current hledger release"+-- on the hledger.org Install page.+-- (This has been hard coded for a while, so keep those words in the page to avoid breaking this.)+getLatestHledgerVersionFromHledgerOrg :: IO (Either String String)+getLatestHledgerVersionFromHledgerOrg = do+ let url = https "hledger.org" /: "install.html"+ do+ result <- try $ runReq defaultHttpConfig $ req GET url NoReqBody bsResponse (R.responseTimeout httptimeout)+ case result of+ Left (_ :: R.HttpException) -> return $ Left "(HTTP failure)"+ Right rsp -> case T.decodeUtf8' $ R.responseBody rsp of+ Left e -> return $ Left $ show e+ Right t -> return $+ if null version then Left "couldn't parse version" else Right version+ where+ -- keep synced+ versionline = take 1 $ dropWhile (not . ("current hledger release" `isInfixOf`)) $ lines $ T.unpack t+ version = takeWhile (`elem` ("0123456789."::[Char])) $ dropWhile (not . isDigit) $ headDef "" $ versionline+ -- work around potential failure on mac (& possible security issue, reported upstream)+ `catch` (\(_ :: IOError) -> return $ Left $ "(IO error" <> if os=="darwin" then " - mac PATH issue ?)" else ")")++-- | Try to run the hledger in PATH with one or more sets of command line arguments.+-- Returns the output from the first set of arguments that runs successfully,+-- or the error output from the last set.+tryHledgerArgs :: [[String]] -> IO (Either String String)+tryHledgerArgs [] = pure $ Left "tryHledgerArgs: no arguments provided"+tryHledgerArgs (args:rest) = do+ eresult <- runHledger args+ case eresult of+ Right out -> pure $ Right out+ Left err -> if null rest then pure $ Left err else tryHledgerArgs rest++-- | Run the hledger in PATH with the given command line arguments,+-- returning the output on success or the error output on failure.+runHledger :: [String] -> IO (Either String String)+runHledger args = do+ (exit, out, err) <- readProcessWithExitCode "hledger" args ""+ pure $ case exit of+ ExitSuccess -> Right out+ ExitFailure _ -> Left err++-- | Get the operating system version string, if possible.+-- Uses platform-specific commands to detect the OS version.+getOSVersion :: IO (Maybe String)+getOSVersion = case os of+ "darwin" -> tryProc "sw_vers" ["-productVersion"]+ -- Use shell mode so process composes the cmd.exe command line itself,+ -- avoiding cmd /c's quirky argument-quote parsing.+ "mingw32" -> tryShell "ver"+ "linux" -> tryProc "uname" ["-r"]+ _ -> return Nothing+ where+ tryProc cmd args = tryRead $ readProcess cmd args ""+ tryShell cmd = tryRead $ readCreateProcess (shell cmd) ""+ tryRead action =+ (Just . strip <$> action)+ `catch` (\(_ :: SomeException) -> return Nothing)
+ Hledger/Cli/Commands/Setup.txt view
@@ -0,0 +1,44 @@+setup++Check the status of the hledger installation.++Flags:+no command-specific flags++setup tests your hledger installation and prints a list of results,+sometimes with helpful hints. This is a good first command to run after+installing hledger. Also after upgrading, or when something's not+working, or just when you want a reminder of where things are.++It makes one network request to detect the latest hledger release+version. It's ok if this fails or times out. It will use ANSI color by+default, unless disabled by NO_COLOR or --color=n. It does not use a+pager or a config file.++It expects that the hledger version you are running is installed in your+PATH. If not, it will stop until you have done that (to keep things+simple).++Example:++$ hledger setup+Checking your setup (and contacting hledger.org to find out the current release):+hledger+ is running on macos 27.0 on aarch64+ is built with a supported compiler/RTS yes ghc 9.14.1, using threaded RTS+ is a native binary for this machine ? yes aarch64+ is a released version ? yes hledger 1.52.4, mac-aarch64+ is up to date ? checking latest... yes latest is 1.52.4, 1.52.4 is installed+ is installed in PATH (this version) ? yes /Users/user/.local/bin/hledger+ has a system text encoding configured ? yes UTF-8, data files must use this encoding+ has a user config file ? yes /Users/user/.hledger.conf+ has a local config file ? no + the config file is readable ? yes +terminal+ the TERM variable is defined ? yes xterm-256color+ the terminal supports ANSI color ? yes + ...+journal+ the LEDGER_FILE variable is defined ? yes /Users/user/finance/main.journal+ a default journal file is readable ? yes /Users/user/finance/main.journal+ ...
+ Hledger/Cli/Commands/Stats.hs view
@@ -0,0 +1,205 @@+{-|++Print some statistics for the journal.++-}++{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE RecordWildCards #-}++module Hledger.Cli.Commands.Stats (+ statsmode+ ,stats+)+where++import Control.Exception (evaluate)+import Data.Default (def)+import Data.List (intercalate, sort)+import Data.List.Extra (nubSort)+import Data.Maybe (fromMaybe)+import Data.HashSet qualified as HS+import Data.Text qualified as T+import Data.Text.Lazy qualified as TL+import Data.Time.Calendar (Day, addDays, diffDays)+import Data.Time.Clock.POSIX (getPOSIXTime)+import GHC.Stats+import System.Console.CmdArgs.Explicit hiding (Group)+import System.FilePath (takeFileName)+import System.Mem (performMajorGC)+import Text.Printf (printf)+import Text.Tabular.AsciiWide++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.GitInfo (gitInfo)+import Hledger.Cli.Utils (writeOutputWithTitle, warnIfLargeMultiPeriodReport)+import Hledger.Cli.Version (packageversion, versionStringWith)+++statsmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Stats.txt")+ [ flagNone ["oneline","q"] (setboolopt "oneline") "show a single line of output"+ -- Cli.hs converts -1 to --depth=1, no point giving it another name here+ , flagNone ["verbose","v"] (setboolopt "verbose") "show more detailed output"+ ,flagReq ["output-file","o"] (\s opts -> Right $ setopt "output-file" s opts) "FILE" "write output to FILE."+ ]+ cligeneralflagsgroups1+ hiddenflags+ ([], Just $ argsFlag "[QUERY]")++-- like Register.summarisePostings+-- | Print various statistics for the journal.+stats :: CliOpts -> Journal -> IO ()+stats opts@CliOpts{rawopts_=rawopts, reportspec_=rspec, progstarttime_} j = do+ warnIfLargeMultiPeriodReport rspec j+ -- the first lines - general journal stats for one or more periods+ let+ today = _rsDay rspec+ oneline = boolopt "oneline" rawopts+ verbose = boolopt "verbose" rawopts+ q = _rsQuery rspec+ l = ledgerFromJournal q j+ intervalspans = snd $ reportSpanBothDates j rspec+ ismultiperiod = length intervalspans > 1+ (txts, tnums) = unzip . map (showLedgerStats verbose l today) $ maybeDayPartitionToDateSpans intervalspans+ out1 = if oneline then "" else (if ismultiperiod then id else init) $ unlines txts+ -- Ensure the stats have been computed (even when not printed, in one-line mode),+ -- so that the run time measured below includes computing them.+ tnum <- evaluate $ sum tnums+ _ <- evaluate $ length out1++ -- the last line - overall performance stats, with memory info if available,+ -- in human-friendly or machine-friendly format+ -- normal:+ -- Runtime stats : 0.14 s elapsed, 7606 txns/s+ -- Runtime stats : 0.14 s elapsed, 7606 txns/s, 6 MB live, 18 MB alloc+ -- oneline:+ -- SHORTVERSION(<SPC><TAB>VALUE[<SPC>DESC])++ -- 1.50.99<SPC><TAB>hledger 1.50.99-g0835a2485-20251119, mac-aarch64<SPC><TAB>2025.journal<SPC><TAB>1.99 s elapsed<SPC><TAB>524 txns/s+ -- 1.50.99<SPC><TAB>hledger 1.50.99-g0835a2485-20251119, mac-aarch64<SPC><TAB>2025.journal<SPC><TAB>1.99 s elapsed<SPC><TAB>524 txns/s<SPC><TAB>788 MB live<SPC><TAB>2172 MB alloc+ -- + rtsstats <- getRTSStatsEnabled+ (maxlivemb, maxinusemb) <- if rtsstats+ then do+ -- do one last garbage collection; probably little effect, hopefully little wasted time+ performMajorGC+ RTSStats{..} <- getRTSStats+ return (toMegabytes max_live_bytes, toMegabytes max_mem_in_use_bytes)+ else+ return (0,0)+ -- Measure the run time as late as possible, so that it includes reading the journal,+ -- computing the stats above, and the memory measurement; only writing the output+ -- and exiting are left out, so it should agree closely with `time hledger stats`.+ t <- getPOSIXTime+ let+ (label, sep)+ | oneline = (lstrip $ versionStringWith gitInfo False "" packageversion <> "\t", "\t")+ | otherwise = (printf "%-*s: " labelwidth ("Runtime stats" :: String), ", ")+ dt = t - progstarttime_+ ss =+ [ takeFileName $ journalFilePath j | oneline ]+ <> [+ printf "%.2f s elapsed" (realToFrac dt :: Float)+ ,printf "%.0f txns/s" (fromIntegral tnum / realToFrac dt :: Float)+ ]+ <> if rtsstats then [+ printf "%0.0f MB live" maxlivemb+ ,printf "%0.0f MB alloc" maxinusemb+ -- printf "%0.0f MB avg live" (toMegabytes $ fromIntegral cumulative_live_bytes / fromIntegral major_gcs)+ ]+ else [+ "(add +RTS -T -RTS for more)"+ ]+ out2 = label <> intercalate sep ss <> "\n"+ tabstops = intercalate (replicate 7 ' ') (replicate 21 ".") <> "\n"++ -- write all of the output at once, so that eg -o FILE gets all of it+ writeOutputWithTitle opts $ T.pack $+ out1+ <> (if oneline && debugLevel>0 then tabstops else "")+ <> (if ismultiperiod then "\n" else "")+ <> out2++toMegabytes n = realToFrac n / 1000000 ::Float -- SI preferred definition, 10^6+-- toMebibytes n = realToFrac n / 1048576 ::Float -- traditional computing definition, 2^20++labelwidth :: Int+labelwidth = 20 -- adjust to suit labels++-- | Generate multiline stats output, possibly verbose,+-- for the given ledger and date period and current date.+-- Also return the number of transactions in the period.+showLedgerStats :: Bool -> Ledger -> Day -> DateSpan -> (String, Int)+showLedgerStats verbose l today spn =+ (unlines $ map (TL.unpack . renderRow def{tableBorders=False, borderSpaces=False} . showRow) stts+ ,tnum)+ where+ showRow (label, val) = Group NoLine $ map (Header . textCell TopLeft)+ [fitText (Just w) (Just w) False True label `T.append` ": ", T.pack val]+ w = labelwidth+ -- w = maximum $ map (T.length . fst) stts+ (stts, tnum) = ([+ ("Main file", path' :: String) -- ++ " (from " ++ source ++ ")")+ ,("Included files", if verbose then unlines includedpaths else show (length includedpaths))+ ,("Txns span", printf "%s to %s (%d days)" (showstart spn) (showend spn) days)+ ,("Last txn", maybe "none" show lastdate ++ showelapsed lastelapsed)+ ,("Txns", printf "%d (%0.1f per day)" tnum txnrate)+ ,("Txns last 30 days", printf "%d (%0.1f per day)" tnum30 txnrate30)+ ,("Txns last 7 days", printf "%d (%0.1f per day)" tnum7 txnrate7)+ ,("Payees/descriptions", show $ HS.size $ HS.fromList $ map tdescription ts)+ ,("Accounts", printf "%d (depth %d)" acctnum acctdepth)+ ,("Commodities", printf "%s%s" (show $ length cs) (if verbose then " (" <> T.intercalate ", " cs <> ")" else ""))+ ,("Base currency", basecurrency)+ ,("Market prices", printf "%s%s" (show $ length mktprices) (if verbose then " (" <> T.intercalate ", " mktpricecommodities <> ")" else ""))+ -- Txns this month : %(monthtxns)s (last month in the same period: %(lastmonthtxns)s)+ -- Unmarked txns : %(unmarked)s+ -- Days since reconciliation : %(reconcileelapsed)s+ -- Days since last txn : %(recentelapsed)s+ ]+ ,tnum1)+ where+ j = ljournal l+ path' = if verbose then path else ".../" <> takeFileName path where path = journalFilePath j+ -- The guessed base currency: the journal's symbol, with its ISO+ -- 4217 code alongside when that differs, eg "$ (USD)"; or "none".+ basecurrency = case journalBaseCurrency j of+ Nothing -> "none"+ Just (sym, code) | sym == code -> T.unpack code+ | otherwise -> T.unpack $ sym <> " (" <> code <> ")"+ includedpaths = drop 1 $ journalFilePaths j+ ts = filter (spanContainsDate spn . tdate) $ jtxns j+ ps = concatMap tpostings ts+ -- (hash sets: faster than sorting for these unique counts)+ as = HS.toList $ HS.fromList $ map paccount ps+ cs = sort $ HS.toList $ HS.fromList $ map acommodity $ concatMap (amountsRaw . pamount) ps+ lastdate | null ts = Nothing+ | otherwise = Just $ maximum $ map tdate ts+ lastelapsed = fmap (diffDays today) lastdate+ showelapsed Nothing = ""+ showelapsed (Just dys) = printf " (%d %s)" dys' direction+ where dys' = abs dys+ unit = if dys' == 1 then "day" else "days" :: String+ direction | dys >= 0 = unit ++ " ago"+ | otherwise = unit ++ " from now"+ tnum1 = length ts -- Integer would be better+ showstart (DateSpan (Just efd) _) = show $ fromEFDay efd+ showstart _ = ""+ showend (DateSpan _ (Just efd)) = show $ fromEFDay efd+ showend _ = ""+ days = fromMaybe 0 $ daysInSpan spn+ txnrate | days==0 = 0+ | otherwise = fromIntegral tnum1 / fromIntegral days :: Double+ tnum30 = length $ filter withinlast30 ts+ withinlast30 t = d >= addDays (-30) today && (d<=today) where d = tdate t+ txnrate30 = fromIntegral tnum30 / 30 :: Double+ tnum7 = length $ filter withinlast7 ts+ withinlast7 t = d >= addDays (-7) today && (d<=today) where d = tdate t+ txnrate7 = fromIntegral tnum7 / 7 :: Double+ acctnum = length as+ acctdepth | null as = 0+ | otherwise = maximum $ map accountNameLevel as+ mktprices = jpricedirectives j+ mktpricecommodities = nubSort $ map pdcommodity mktprices
+ Hledger/Cli/Commands/Stats.txt view
@@ -0,0 +1,54 @@+stats++Show journal and performance statistics.++Flags:+ -q --oneline show a single line of output+ -v --verbose show more detailed output+ -o --output-file=FILE write output to FILE.++The stats command shows summary information for the whole journal, or a+matched part of it. With a reporting interval, it shows a report for+each report period.++It also shows some performance statistics:++- how long the program ran for+- the number of transactions processed per second+- the peak live memory in use by the program to do its work+- the peak allocated memory as seen by the program++By default, the output is reasonably discreet; it reveals the main file+name, your activity level, and the speed of your machine.++With -v/--verbose, more details are shown: the full paths of all files,+and the names of the commodities you work with.++With -q/--oneline, only one line of output is shown, in a+machine-friendly tab-separated format: the program version, the main+journal file name, and the performance stats,++The run time of stats is similar to that of a balance report.++Example:++$ hledger stats -f examples/1ktxns-1kaccts.journal +Main file : .../1ktxns-1kaccts.journal+Included files : 0+Txns span : 2000-01-01 to 2002-09-27 (1000 days)+Last txn : 2002-09-26 (7827 days ago)+Txns : 1000 (1.0 per day)+Txns last 30 days : 0 (0.0 per day)+Txns last 7 days : 0 (0.0 per day)+Payees/descriptions : 1000+Accounts : 1000 (depth 10)+Commodities : 26+Base currency : B+Market prices : 1000+Runtime stats : 0.12 s elapsed, 8266 txns/s, 4 MB live, 16 MB alloc++$ hledger stats -q -f examples/10ktxns-1kaccts.journal+1.50.99-g0835a2485-20251119, mac-aarch64 10ktxns-1kaccts.journal 0.66 s elapsed 15244 txns/s 28 MB live 86 MB alloc++This command supports the -o/--output-file option (but not+-O/--output-format).
+ Hledger/Cli/Commands/Tags.hs view
@@ -0,0 +1,102 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE TemplateHaskell #-}+{-# LANGUAGE TupleSections #-}++module Hledger.Cli.Commands.Tags (+ tagsmode+ ,tags+)+where++import Control.Monad.Fail qualified as Fail+import Data.List.Extra (nubSort)+import Data.Text qualified as T+import Safe+import System.Console.CmdArgs.Explicit++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils (writeOutputWithTitle)+import Data.Function ((&))+import Data.Maybe (fromMaybe)+import Data.List (find)+++tagsmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Tags.txt")+ [+ flagNone ["used"] (setboolopt "used") "list tags used"+ ,flagNone ["declared"] (setboolopt "declared") "list tags declared"+ ,flagNone ["undeclared"] (setboolopt "undeclared") "list tags used but not declared"+ ,flagNone ["unused"] (setboolopt "unused") "list tags declared but not used"+ ,flagNone ["find"] (setboolopt "find") "list the first tag whose name is matched by the first argument (a case-insensitive infix regexp)"+ ,flagNone ["values"] (setboolopt "values") "list tag values instead of tag names"+ ,flagNone ["parsed"] (setboolopt "parsed") "show them in the order they were parsed (mostly), including duplicates"+ ,flagNone ["directives"] (setboolopt "directives") "show tag names as tag directives, for use in journals"+ ]+ cligeneralflagsgroups1+ hiddenflags+ ([], Just $ argsFlag "[TAGREGEX [QUERY..]]")++tags :: CliOpts -> Journal -> IO ()+tags opts@CliOpts{rawopts_=rawopts, reportspec_=rspec@ReportSpec{_rsQuery=_q, _rsReportOpts=ropts}} j = do+ let today = _rsDay rspec+ args = listofstringopt "args" rawopts+ -- For convenience/power, the first argument is a tag name regex, + -- separate from the main query arguments: hledger tags [TAGREGEX [QUERYARGS..]]+ -- So we have to re-parse the query here. Overcomplicated ?+ mtagpat <- mapM (either Fail.fail pure . toRegexCI . T.pack) $ headMay args+ let+ values = boolopt "values" rawopts+ parsed = boolopt "parsed" rawopts+ directives = boolopt "directives" rawopts && not values+ empty = empty_ ropts+ querystr = map T.pack $ drop 1 args+ query <- either usageError (return . fst) $ parseQueryList today querystr+ let+ q = simplifyQuery $ And [queryFromFlags ropts, query]+ txns = filter (q `matchesTransaction`) $ jtxns $ journalApplyValuationFromOpts rspec j+ accts =+ -- also search for tags in matched account declarations,+ -- unless there is a query for something transaction-specific, like date: or amt:.+ if dbg5 "queryIsTransactionRelated" $ queryIsTransactionRelated $ dbg4 "q" q+ then []+ else filter (matchesAccountExtra (journalAccountType j) (journalInheritedAccountTags j) q) $+ map fst $ jdeclaredaccounts j+ -- bit of a mess.+ used = dbg5 "used" $ concatMap (journalAccountTags j) accts ++ concatMap transactionAllTags txns+ declared' = dbg5 "declared'" $ map (,"") $ journalTagsDeclared j+ filtereddeclared = dbg5 "filtereddeclared'" $ filter (q `matchesTag`) declared'+ (usednames, declarednames) = (map fst used, map fst filtereddeclared)+ unused = dbg5 "unused" $ filter (not . (`elem` usednames) . fst) filtereddeclared+ undeclared = dbg5 "undeclared" $ filter (not . (`elem` declarednames) . fst) used+ all' = dbg5 "all''" $ filtereddeclared <> used+ found = dbg5 "found" $ foundtag+ where+ -- First find the name, then the first occurrence of that tag.+ -- So that --values and --parsed still work with --find (in some reasonably stable way).+ alltags = declared' <> used+ allnames = dbg5 "allnames" $ nubSort $ map fst alltags+ foundname = dbg5 "foundname" $ findMatchedByArgument rawopts "tag name" allnames+ foundtag = find ((==foundname).fst) alltags+ & fromMaybe (error' "tags: could not find a tag's first occurrence") -- PARTIAL: should not happen because allnames and alltags correspond++ tags' =+ case declarablesSelectorFromOpts opts of+ Nothing -> all'+ Just Used -> used+ Just Declared -> declared'+ Just Undeclared -> undeclared+ Just Unused -> unused+ Just FindFirst -> [found]++ results =+ (if parsed then id else nubSort)+ [ r+ | (t,v) <- tags'+ , maybe True (`regexMatchText` t) mtagpat+ , let r = if values then v else if directives then "tag " <> t else t+ , not (values && T.null v && not empty)+ ]++ writeOutputWithTitle opts $ T.unlines results
+ Hledger/Cli/Commands/Tags.txt view
@@ -0,0 +1,54 @@+tags++List the tag names used or declared in the journal, or their values.++Flags:+ --used list tags used+ --declared list tags declared+ --undeclared list tags used but not declared+ --unused list tags declared but not used+ --find list the first tag whose name is matched by the+ first argument (a case-insensitive infix regexp)+ --values list tag values instead of tag names+ --parsed show them in the order they were parsed (mostly),+ including duplicates+ --directives show tag names as tag directives, for use in+ journals++This command lists tag names - all of them by default, or just the ones+which have been used on transactions/postings/accounts, or declared with+tag directives, or used but not declared, or declared but not used, or+just the first one matched by a pattern (with --find, returning a+non-zero exit code if it fails).++Note this command's non-standard first argument: it is a+case-insensitive infix regular expression for matching tag names, which+limits the tags shown. Any additional arguments are standard query+arguments, which limit the transactions, postings, or accounts providing+tags.++With --values, the tags' unique non-empty values are listed instead.++With -E/--empty, blank/empty values are also shown.++With --parsed, tags or values are shown in the order they were parsed,+with duplicates included. (Except, tags from account declarations are+always shown first.)++With --directives, tag names are shown as valid tag directives, which+could be pasted into a journal file.++Remember that accounts also acquire tags from their parents; postings+also acquire tags from their account and transaction; and transactions+also acquire tags from their postings.++Examples:++$ hledger tags+broker+receipt+trip++$ hledger tags --values+acme+paris
+ Hledger/Cli/Commands/Transactions.hs view
@@ -0,0 +1,41 @@+{-|++The @transactions@ command lists transactions one per line.++-}++{-# LANGUAGE TemplateHaskell #-}++module Hledger.Cli.Commands.Transactions (+ transactionsmode+ ,transactions+) where++import System.Console.CmdArgs.Explicit++import Hledger+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils (withTitle, writeOutputLazyText)+import Hledger.Cli.Commands.Print (journalApplyMatchOpt, entriesReportAsTextHelper)+++-- | Command line options for this command.+transactionsmode = hledgerCommandMode+ $(embedFileRelative "Hledger/Cli/Commands/Transactions.txt")+ [+ let arg = "DESC" in+ flagReq ["match","m"] (\s opts -> Right $ setopt "match" s opts) arg+ ("fuzzy search for one recent transaction with description closest to "++arg)+ ]+ cligeneralflagsgroups1+ hiddenflags+ ([], Just $ argsFlag "[QUERY]")++-- | The transactions command: show each transaction's first line only.+transactions :: CliOpts -> Journal -> IO ()+transactions opts@CliOpts{reportspec_=rspec} =+ writeOutputLazyText opts+ . withTitle (_rsReportOpts rspec)+ . entriesReportAsTextHelper showTransactionOneLine+ . entriesReport rspec+ . journalApplyMatchOpt opts
+ Hledger/Cli/Commands/Transactions.txt view
@@ -0,0 +1,24 @@+transactions++(tx)++List transactions, one per line.++Flags:+ -m --match=DESC fuzzy search for one recent transaction with+ description closest to DESC++This command shows each transaction's first line only (the date, status,+code, description, and any same-line comment), giving a compact overview+of a journal, in the manner of git log --oneline. You can add a query to+select a subset of transactions. (To see full journal entries, use the+print command.)++Example:++$ hledger transactions -f examples/sample.journal+2008-01-01 income+2008-06-01 gift+2008-06-02 save+2008-06-03 * eat & shop+2008-12-31 * pay off
+ Hledger/Cli/CompoundBalanceCommand.hs view
@@ -0,0 +1,561 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE RecordWildCards #-}+{-# LANGUAGE LambdaCase #-}+{-|++Common helpers for making multi-section balance report commands+like balancesheet, cashflow, and incomestatement.++-}++module Hledger.Cli.CompoundBalanceCommand (+ CompoundBalanceCommandSpec(..)+ ,compoundBalanceCommandMode+ ,compoundBalanceCommand+ ,compoundBalanceReportTitle+ ,titleInterval+ ,applySubreportTitles+ ,compoundBalanceSectionTypes+ ,CompoundBalanceReportParts(..)+ ,compoundBalanceReportAsSpreadsheetParts+ ,allCommoditiesFromSubreports+) where++import Control.Monad (guard, unless, void)+import Data.Bifunctor (second)+import Data.Foldable (traverse_)+import Data.List.NonEmpty (NonEmpty((:|)))+import Data.Maybe (fromMaybe, mapMaybe, maybeToList)+import Safe (atMay)+import Data.Map qualified as Map+import Data.Set qualified as Set+import Data.List qualified as List+import Data.List.NonEmpty qualified as NonEmpty+import Data.Text qualified as T+import Data.Text.Lazy qualified as TL+import Data.Text.Lazy.Builder qualified as TB+import Data.Time.Calendar (Day, addDays)+import System.Console.CmdArgs.Explicit as C (Mode, flagNone, flagReq)+import System.IO qualified as IO+import Text.Blaze.Html5 ((!), preEscapedToHtml)+import Text.Blaze.Html5 qualified as H+import Text.Blaze.Html5.Attributes qualified as A+import Text.Tabular.AsciiWide as Tabular hiding (render)++import Hledger.Utils.I18n qualified as I18n+import Hledger+import Hledger.Cli.Anchor (LinkOpts(..), headerDateSpanCell)+import Hledger.Cli.Chart (compoundChartFlag, chartRequested, chartWidthFlag, compoundBalanceReportAsChart, writeChart)+import Hledger.Cli.Commands.Balance+import Hledger.Cli.CliOptions+import Hledger.Cli.Utils (unsupportedOutputFormatError, writeOutputLazyText, warnIfLargeMultiPeriodReport)+import Hledger.Cli.Commands.Balance.Internal+import Hledger.Write.Csv (CSV, printCSV, printTSV)+import Hledger.Write.Html (formatRow, formatTitle, htmlAsLazyText, nl, Html, toHtml)+import Hledger.Write.Html.Attribute (stylesheet, tableStyle)+import Hledger.Write.Ods (printFods)+import Hledger.Write.Spreadsheet qualified as Spr++-- | Description of a compound balance report command,+-- from which we generate the command's cmdargs mode and IO action.+-- A compound balance report command shows one or more sections/subreports,+-- each with its own title and subtotals row, in a certain order,+-- plus a grand totals row if there's more than one section.+-- Examples are the balancesheet, cashflow and incomestatement commands.+--+-- Compound balance reports do sign normalisation: they show all account balances+-- as normally positive, unlike the ordinary BalanceReport and most hledger commands+-- which show income/liability/equity balances as normally negative.+-- Each subreport specifies the normal sign of its amounts, and whether+-- it should be added to or subtracted from the grand total.+--+data CompoundBalanceCommandSpec = CompoundBalanceCommandSpec {+ cbcdoc :: CommandHelpStr, -- ^ the command's name(s) and documentation+ cbctitle :: Interval -> T.Text, -- ^ overall report title, by reporting interval+ cbcqueries :: [CBCSubreportSpec DisplayName], -- ^ subreport details+ cbcaccum :: BalanceAccumulation -- ^ how to accumulate balances (per-period, cumulative, historical)+ -- (overrides command line flags)+}++-- | Generate a cmdargs option-parsing mode from a compound balance command+-- specification.+compoundBalanceCommandMode :: CompoundBalanceCommandSpec -> Mode RawOpts+compoundBalanceCommandMode CompoundBalanceCommandSpec{..} =+ hledgerCommandMode+ cbcdoc+ -- keep roughly consistent order with Balance.hs. XXX refactor+ (+ -- https://hledger.org/dev/hledger.html#calculation-mode :+ [flagNone ["sum"] (setboolopt "sum")+ (calcprefix ++ "show sum of posting amounts (default)")+ ,flagNone ["valuechange"] (setboolopt "valuechange")+ (calcprefix ++ "show total change of value of period-end historical balances (caused by deposits, withdrawals, market price fluctuations)")+ ,flagNone ["gain"] (setboolopt "gain")+ (calcprefix ++ "show unrealised capital gain/loss (historical balance value minus cost basis)")+ -- currently not supported by compound balance commands:+ -- ,flagNone ["budget"] (setboolopt "budget")+ -- (calcprefix ++ "show sum of posting amounts compared to budget goals defined by periodic transactions")+ ,flagNone ["count"] (setboolopt "count") (calcprefix ++ "show the count of postings")++ -- https://hledger.org/dev/hledger.html#accumulation-mode :+ ,flagNone ["change"] (setboolopt "change")+ (accumprefix ++ "accumulate amounts from column start to column end (in multicolumn reports)" ++ defaultMarker PerPeriod)+ ,flagNone ["cumulative"] (setboolopt "cumulative")+ (accumprefix ++ "accumulate amounts from report start (specified by e.g. -b/--begin) to column end" ++ defaultMarker Cumulative)+ ,flagNone ["historical","H"] (setboolopt "historical")+ (accumprefix ++ "accumulate amounts from journal start to column end (includes postings before report start date)" ++ defaultMarker Historical)+ ]++ ++ flattreeflags True +++ [flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "in list mode, omit N leading account name parts"+ ,flagNone ["declared"] (setboolopt "declared") "include non-parent declared accounts (best used with -E)"+ ,flagNone ["average","A"] (setboolopt "average") "show a row average column (in multicolumn reports)"+ ,flagNone ["row-total","T"] (setboolopt "row-total") "show a row total column (in multicolumn reports)"+ ,flagNone ["summary-only"] (setboolopt "summary-only") "display only row summaries (e.g. row total, average) (in multicolumn reports)"+ ,flagNone ["no-total","N"] (setboolopt "no-total") "omit the final total row"+ ,flagNone ["no-elide"] (setboolopt "no-elide") "in tree mode, don't squash boring parent accounts; in list mode, also show parent accounts (usually zero, hidden without -E)"+ ,flagNone ["full-names"] (setboolopt "full-names") "in tree mode, show full account names instead of indented leaf names"+ ,flagReq ["format"] (\s opts -> Right $ setopt "format" s opts) "FORMATSTR" "use this custom line format (in simple reports)"+ ,flagNone ["sort-amount","S"] (setboolopt "sort-amount") "sort by amount instead of account code/name"+ ,flagNone ["percent", "%"] (setboolopt "percent") "express values in percentage of each column's total"+ ,flagReq ["layout"] (\s opts -> Right $ setopt "layout" s opts) "ARG"+ (unlines+ ["how to show multi-commodity amounts:"+ ,"'wide[,WIDTH]': all commodities on one line"+ ,"'tall' : each commodity on a new line"+ ,"'bare' : bare numbers, symbols in a column"+ ])+ ,flagReq ["base-url"] (\s opts -> Right $ setopt "base-url" s opts) "URLPREFIX" "in html output, generate hyperlinks to hledger-web, with this prefix. (Usually the base url shown by hledger-web; can also be relative.)"++ ,outputFormatFlag ["txt","html","csv","tsv","json","svg"]+ ,outputFileFlag+ ,outputViewFlag+ ,compoundChartFlag+ ,chartWidthFlag++ ])+ cligeneralflagsgroups1+ (hiddenflags +++ [ flagNone ["commodity-column"] (setboolopt "commodity-column")+ "show commodity symbols in a separate column, amounts as bare numbers, one row per commodity"+ ])+ ([], Just $ argsFlag "[QUERY]")+ where+ calcprefix = "calculation mode: "+ accumprefix = "accumulation mode: "+ defaultMarker :: BalanceAccumulation -> String+ defaultMarker bacc | bacc == cbcaccum = " (default)"+ | otherwise = ""++-- | Generate a runnable command from a compound balance command specification.+compoundBalanceCommand :: CompoundBalanceCommandSpec -> (CliOpts -> Journal -> IO ())+compoundBalanceCommand spec@CompoundBalanceCommandSpec{..} opts@CliOpts{reportspec_=rspec, rawopts_=rawopts} j = do+ warnIfLargeMultiPeriodReport rspec j+ if chartRequested opts+ then writeChart opts (Just $ render $ styleAmounts styles cbr) $ compoundBalanceReportAsChart (journalAccountType j) sectiontypes ropts' $ styleAmounts styles cbr+ else writeOutputLazyText opts $ render $ styleAmounts styles cbr+ where+ styles = balanceReportStyles ropts j+ ropts = _rsReportOpts rspec+ -- use the default balance type for this report, unless the user overrides+ mbalanceAccumulationOverride = balanceAccumulationOverride rawopts+ balanceaccumulation = fromMaybe cbcaccum mbalanceAccumulationOverride+ -- Set balance type in the report options.+ ropts' = ropts{balanceaccum_=balanceaccumulation}+ tr = I18n.tr (translations_ ropts)++ -- make a CompoundBalanceReport. The default heading is the auto-generated+ -- title; --title=TEXT overrides it (and =empty suppresses).+ -- --subreport-titles=A|B|... overrides per-subreport titles.+ cbr' = compoundBalanceReport rspec{_rsReportOpts=ropts'} j cbcqueries+ cbr = applySubreportTitles ropts' $+ cbr'{cbrTitle = effectiveTitle ropts' $ compoundBalanceReportTitle spec ropts mbalanceAccumulationOverride cbr'+ ,cbrSubreports = [ (tr t, r, b) | (t, r, b) <- cbrSubreports cbr' ]}++ sectiontypes = compoundBalanceSectionTypes cbcqueries++ -- render appropriately+ render = case outputFormatFromOpts opts of+ "txt" -> compoundBalanceReportAsText ropts'+ "csv" -> printCSV . compoundBalanceReportAsCsv ropts' cbcqueries+ "tsv" -> printTSV . compoundBalanceReportAsCsv ropts' cbcqueries+ "html" -> (<>"\n") . htmlAsLazyText . compoundBalanceReportAsHtml ropts' cbcqueries+ "fods" -> printFods IO.localeEncoding .+ fmap (second NonEmpty.toList) . uncurry Map.singleton .+ compoundBalanceReportAsSpreadsheet+ oneLineNoCostFmt "Account" (Just "") ropts' cbcqueries+ "json" -> toJsonText+ x -> error' $ unsupportedOutputFormatError x++-- | The title of a compound balance report: the interval and report+-- name, the dates, a note when the accumulation mode was overridden or+-- the calculation is not the plain one, and the valuation. The report+-- options are the command line's, with any accumulation override given+-- separately, since the title says which it was.+compoundBalanceReportTitle ::+ CompoundBalanceCommandSpec -> ReportOpts -> Maybe BalanceAccumulation -> CompoundPeriodicReport a b -> T.Text+compoundBalanceReportTitle CompoundBalanceCommandSpec{cbctitle=cbctitle, cbcaccum=cbcaccum} ReportOpts{..} mbalanceAccumulationOverride cbr =+ -- TRANSLATORS: the report title, eg "Monthly Balance Sheet 2024 (Historical Ending Balances), valued at period ends".+ -- {clarification} brings its own leading space when present.+ trf "{report} {dates}{clarification}{valuation}"+ [ ("report", tr $ cbctitle $ titleInterval interval_)+ , ("dates", titledatestr)+ , ("clarification", maybe "" (" " <>) mtitleclarification)+ , ("valuation", valuationdesc)+ ]+ where+ tr = I18n.tr translations_+ trf = I18n.trf translations_+ balanceaccumulation = fromMaybe cbcaccum mbalanceAccumulationOverride++ -- XXX #1078 the title of ending balance reports+ -- (Historical) should mention the end date(s) shown as+ -- column heading(s) (not the date span of the transactions).+ -- Also the dates should not be simplified (it should show+ -- "2008/01/01-2008/12/31", not "2008").+ titledatestr = case balanceaccumulation of+ Historical -> showEndDates enddates+ _ -> showDateSpan columnsspan+ where+ enddates = map (addDays (-1)) . mapMaybe spanEnd $ cbrDates cbr -- these spans will always have a definite end date+ -- the span the columns cover: the requested span, widened to whole intervals+ columnsspan = spansSpan $ cbrDates cbr++ -- when user overrides, add an indication to the report title+ -- Do we need to deal with overridden BalanceCalculation?+ mtitleclarification = case (balancecalc_, balanceaccumulation, mbalanceAccumulationOverride) of+ (CalcValueChange, PerPeriod, _ ) -> Just $ tr "(Period-End Value Changes)"+ (CalcValueChange, Cumulative, _ ) -> Just $ tr "(Cumulative Period-End Value Changes)"+ (CalcGain, PerPeriod, _ ) -> Just $ tr "(Incremental Gain)"+ (CalcGain, Cumulative, _ ) -> Just $ tr "(Cumulative Gain)"+ (CalcGain, Historical, _ ) -> Just $ tr "(Historical Gain)"+ (_, _, Just PerPeriod ) -> Just $ tr "(Balance Changes)"+ (_, _, Just Cumulative) -> Just $ tr "(Cumulative Ending Balances)"+ (_, _, Just Historical) -> Just $ tr "(Historical Ending Balances)"+ _ -> Nothing++ valuationdesc =+ (case conversionop_ of+ Just ToCost -> tr ", converted to cost"+ _ -> "")+ <> (case value_ of+ Just (AtThen _mc) -> tr ", valued at posting date"+ Just (AtEnd _mc) | changingValuation -> ""+ Just (AtEnd _mc) -> tr ", valued at period ends"+ Just (AtNow _mc) -> tr ", current value"+ Just (AtDate today _mc) -> trf ", valued at {date}" [("date", showDate today)]+ Nothing -> "")++ changingValuation = case (balancecalc_, balanceaccum_) of+ (CalcValueChange, PerPeriod) -> True+ (CalcValueChange, Cumulative) -> True+ _ -> False++-- | Apply --subreport-titles overrides to a compound report's subreports.+-- A `|`-separated argument overrides the corresponding subreport titles, in+-- order; subreports beyond the supplied list keep their default title. An+-- explicit empty argument suppresses all default subreport titles.+applySubreportTitles :: ReportOpts -> CompoundPeriodicReport a b -> CompoundPeriodicReport a b+applySubreportTitles ropts cbr@CompoundPeriodicReport{cbrSubreports=subs} =+ case subreport_titles_ ropts of+ Nothing -> cbr+ Just s+ | T.null s -> cbr{cbrSubreports = map (\(_,r,b) -> ("", r, b)) subs}+ | otherwise ->+ let custom = T.splitOn "|" s+ replace i (old,r,b) = (fromMaybe old (atMay custom i), r, b)+ in cbr{cbrSubreports = zipWith replace [0..] subs}++-- | Each section's account type, from its query, if that is a simple type query (for colouring charts).+compoundBalanceSectionTypes :: [CBCSubreportSpec a] -> [Maybe AccountType]+compoundBalanceSectionTypes specs = [case cbcsubreportquery q of Type (t:_) -> Just t; _ -> Nothing | q <- specs]++-- | Merge the intervals that a report title does not distinguish:+-- twelve months is a year, and a quarter is three months.+titleInterval :: Interval -> Interval+titleInterval = \case+ Months 12 -> Years 1+ Quarters 1 -> Months 3+ Quarters 2 -> Months 6+ i -> i++-- | Summarise one or more (inclusive) end dates, in a way that's+-- visually different from showDateSpan, suggesting discrete end dates+-- rather than a continuous span.+showEndDates :: [Day] -> T.Text+showEndDates es = case es of+ -- cf showPeriod+ (e:_:_) -> showDate e <> ".." <> showDate (last es)+ [e] -> showDate e+ [] -> ""++-- | Render a compound balance report as plain text suitable for console output.+{- Eg:+Balance Sheet++ || 2017/12/31 Total Average+=============++===============================+ Assets ||+-------------++-------------------------------+ assets:b || 1 1 1+-------------++-------------------------------+ || 1 1 1+=============++===============================+ Liabilities ||+-------------++-------------------------------+-------------++-------------------------------+ ||+=============++===============================+ Total || 1 1 1++-}+compoundBalanceReportAsText :: ReportOpts -> CompoundPeriodicReport DisplayName MixedAmount -> TL.Text+compoundBalanceReportAsText ropts (CompoundPeriodicReport title _colspans subreports totalsrow) =+ TB.toLazyText $+ titleBuilder <>+ multiBalanceReportTableAsText ropts bigtablewithtotalsrow+ where+ titleBuilder | T.null title = mempty+ | otherwise = TB.fromText title <> TB.fromText "\n\n"+ bigtable =+ case map (subreportAsTable ropts) subreports of+ [] -> Tabular.empty+ r:rs -> List.foldl' (concatTables tableInterSubreportBorder) r rs+ bigtablewithtotalsrow =+ if no_total_ ropts || length subreports == 1+ then bigtable+ else concatTables tableGrandTotalsTopBorder bigtable totalstable+ where+ -- Append the report's grand column totals at the bottom of the table.+ -- Note "row" is confusingly overloaded here; *Report rows, Table rows,+ -- and visually apparent table rows are all distinct.+ -- With multiple currencies, in some layout modes, the column totals (a single report row)+ -- occupy multiple lines, which currently we put into multiple table rows,+ -- for convenience I guess, borderless so they look like a single visual row.+ --+ -- multiBalanceRowAsText gets a matrix of each line of each column total rendered as text+ -- (actually as WideBuilders), in line-major-order:+ -- [+ -- [COL1LINE1, COL2LINE1]+ -- [COL1LINE2, COL2LINE2]+ -- ]+ coltotalslines = multiBalanceRowAsText ropts allCommodities totalsrow+ totalstable = Table+ (Group NoLine $ map Header $ I18n.tr (translations_ ropts) "Net:" : replicate (length coltotalslines - 1) "") -- row headers+ (Header []) -- column headers, concatTables will discard these+ coltotalslines -- cell values ++ allCommodities = allCommoditiesFromSubreports subreports++ -- | Convert a named multi balance report to a table suitable for+ -- concatenating with others to make a compound balance report table.+ -- An empty subreport title is omitted entirely (no title row above the data).+ subreportAsTable ropts1 (title1, r, _) = tablewithtitle+ where+ Table lefthdrs tophdrs cells =+ multiBalanceReportAsPartTable ropts1 allCommodities r+ tablewithtitle+ | T.null title1 = Table lefthdrs tophdrs cells+ | otherwise = Table+ (Group tableSubreportTitleBottomBorder [Header title1, lefthdrs]) -- row headers+ tophdrs -- column headers+ ([]:cells) -- cell values++ tableSubreportTitleBottomBorder = SingleLine+ tableInterSubreportBorder = DoubleLine+ tableGrandTotalsTopBorder = DoubleLine++-- | Render a compound balance report as CSV.+-- Subreports' CSV is concatenated, with the headings rows replaced by a+-- subreport title row, and an overall title row, one headings row, and an+-- optional overall totals row is added.+compoundBalanceReportAsCsv ::+ ReportOpts -> [CBCSubreportSpec DisplayName] -> CompoundPeriodicReport DisplayName MixedAmount -> CSV+compoundBalanceReportAsCsv ropts specs cbr =+ let spreadsheet =+ snd $ snd $+ compoundBalanceReportAsSpreadsheet+ machineFmt "Account" Nothing ropts specs cbr+ title = cbrTitle cbr+ titleRows | T.null title = []+ | otherwise =+ [Spr.horizontalSpan (NonEmpty.head spreadsheet)+ (Spr.headerCell title)]+ in Spr.rawTableContent $+ titleRows ++ NonEmpty.toList spreadsheet++-- | Render a compound balance report as HTML.+compoundBalanceReportAsHtml ::+ ReportOpts -> [CBCSubreportSpec DisplayName] -> CompoundPeriodicReport DisplayName MixedAmount -> Html+compoundBalanceReportAsHtml ropts specs cbr =+ let (title, (_fixed, cells)) =+ compoundBalanceReportAsSpreadsheet+ oneLineNoCostFmt "" (Just nbsp) ropts specs cbr+ in do+ -- the builtin styles, then the optional user stylesheet so it can override them+ H.style $ preEscapedToHtml $ stylesheet $+ tableStyle ++ [+ ("td:nth-child(1)", "white-space:nowrap"),+ ("tr:nth-child(odd) td", "background-color:#eee")+ ]+ nl+ H.link ! A.rel "stylesheet" ! A.href "hledger.css"+ nl+ unless (T.null title) $ formatTitle title+ -- Do not use `styledTableHtml` here since that leads to nested `<table>`s.+ H.table $ nl <> (traverse_ formatRow $ fmap (map (fmap toHtml)) cells)++-- | Render a compound balance report as Spreadsheet: the heading row,+-- then each section's title row, body rows, totals rows, and a blank row+-- for whitespace if wanted, then the net total rows.+compoundBalanceReportAsSpreadsheet ::+ AmountFormat -> T.Text -> Maybe T.Text ->+ ReportOpts -> [CBCSubreportSpec DisplayName] -> CompoundPeriodicReport DisplayName MixedAmount ->+ (T.Text, ((Int, Int), NonEmpty [Spr.Cell Spr.NumLines T.Text]))+compoundBalanceReportAsSpreadsheet fmt accountLabel maybeBlank ropts specs cbr =+ let+ CompoundBalanceReportParts{..} = compoundBalanceReportAsSpreadsheetParts fmt accountLabel ropts specs cbr+ dataHeaders = map Spr.cellContent cbrpDataHeaders+ headerrow =+ cbrpLeadingHeaders +++ concatMap (Spr.horizontalSpan subColumns) cbrpDataHeaders++ blankrow =+ fmap (Spr.horizontalSpan headerrow . Spr.defaultCell) maybeBlank+ subColumns =+ case layout_ ropts of+ LayoutBareWide -> void allCommodities+ _ -> [()]+ allCommodities = allCommoditiesFromSubreports $ cbrSubreports cbr++ sectionrows (subreporttitle, bodyrows, totalsrows) =+ let+ accountCell =+ (Spr.defaultCell subreporttitle) {+ Spr.cellStyle = Spr.Body Spr.Total,+ Spr.cellClass = accountClass+ }+ titleRows+ | T.null subreporttitle = []+ | otherwise =+ [case layout_ ropts of+ LayoutBareWide ->+ accountCell :+ map Spr.headerCell (dataHeaders >> allCommodities)+ _ -> Spr.horizontalSpan headerrow accountCell]+ in+ titleRows +++ bodyrows +++ totalsrows +++ maybeToList blankrow++ in (cbrTitle cbr,+ ((1, multiBalanceReportNumHeaderColumns $ layout_ ropts),+ headerrow :| concatMap sectionrows cbrpSections ++ cbrpNetRows))++-- | The parts of a compound balance report as spreadsheet cells, to be+-- laid out as one table, or as a table with sections as hledger-web does.+data CompoundBalanceReportParts = CompoundBalanceReportParts {+ cbrpLeadingHeaders :: [Spr.Cell Spr.NumLines T.Text],+ -- ^ The heading row's first cell(s): the account column's, and the+ -- tidy and bare layouts' extra columns'.+ cbrpDataHeaders :: [Spr.Cell Spr.NumLines T.Text],+ -- ^ Then a heading per data column: each period, linking to the+ -- register for it, then the row total and average when shown.+ -- In the bare-wide layout each of these spans the commodity columns.+ cbrpSections :: [(T.Text, [[Spr.Cell Spr.NumLines T.Text]], [[Spr.Cell Spr.NumLines T.Text]])],+ -- ^ Each section's title, body rows, and totals rows.+ cbrpNetRows :: [[Spr.Cell Spr.NumLines T.Text]]+ -- ^ The net total rows; none when there is one section or no totals.+}++-- | Render a compound balance report's parts as spreadsheet cells. The+-- subreport specs it was made from say how each section's figures link:+-- a section is rendered with its own report options, so that its links+-- say when its figures are negated, and its totals link to the registers+-- of its account types.+compoundBalanceReportAsSpreadsheetParts ::+ AmountFormat -> T.Text ->+ ReportOpts -> [CBCSubreportSpec DisplayName] -> CompoundPeriodicReport DisplayName MixedAmount ->+ CompoundBalanceReportParts+compoundBalanceReportAsSpreadsheetParts fmt accountLabel ropts specs cbr =+ CompoundBalanceReportParts {+ cbrpLeadingHeaders = leadingHeaders,+ cbrpDataHeaders = dataHeaderCells,+ cbrpSections = zipWith section specs subreports,+ cbrpNetRows = netrows+ }+ where+ CompoundPeriodicReport _ colspans subreports totalrow = cbr+ leadingHeaders =+ Spr.headerCell accountLabel :+ case layout_ ropts of+ LayoutTidy -> map Spr.headerCell tidyColumnLabels+ LayoutBare -> [Spr.headerCell "Commodity"]+ _ -> []+ -- A period heading links to the register for that period; its text+ -- is the period's end date in a historical report.+ dataHeaderCells =+ (guard (layout_ ropts /= LayoutTidy) >>) $+ [ (headerDateSpanCell (date2_ ropts) (period_titles_ ropts) (balance_base_url_ ropts) (querystring_ ropts) spn) {+ Spr.cellBorder = Spr.noBorder,+ -- column headings stay English in these formats, month names included+ Spr.cellContent = reportPeriodName ropts{translations_ = I18n.noTranslations} colspans spn+ }+ | not (summary_only_ ropts), spn <- colspans ] +++ (guard (multiBalanceHasTotalsColumn ropts) >> [Spr.headerCell "Total"]) +++ (guard (average_ ropts) >> [Spr.headerCell "Average"])+ allCommodities = allCommoditiesFromSubreports subreports++ -- The account type codes a section is selected by, which its totals'+ -- registers need; a section not selected by type gets no such links.+ typeCodes q = case q of+ Type ts -> Just $ T.concat $ map (T.pack . show) ts+ _ -> Nothing+ typeTerm = fmap ("type:" <>) . typeCodes+ -- Is a section shown with its figures negated, as normally negative+ -- accounts are ?+ negated spec = normalbalance_ (cbcsubreportoptions spec ropts) == Just NormallyNegative+ unlinked = map (map (\c -> c {Spr.cellAnchor = mempty, Spr.cellTitle = mempty}))+ linkedWhen mterm rows = maybe (unlinked rows) (const rows) mterm++ -- A section's rows link with its type term as well, so that their+ -- registers exclude a subaccount of another type, as the figures do.+ section spec (subreporttitle, mbr, _increasestotal) = (subreporttitle, bodyrows, totalsrows)+ where+ sropts = cbcsubreportoptions spec ropts+ sectionterm = typeTerm $ cbcsubreportquery spec+ (_, bodyrows, _) =+ balanceSubReportAsSpreadsheetParts fmt+ sropts{no_total_ = True, querystring_ = maybeToList sectionterm ++ querystring_ sropts}+ allCommodities mbr+ totalsrows+ | no_total_ ropts = []+ | otherwise =+ linkedWhen sectionterm $+ multiBalanceTotalsRows fmt sropts (reportLinkOpts sropts (prDates mbr)) (maybeToList sectionterm)+ allCommodities (prDates mbr) totalRowHeadingSpreadsheet (prTotals mbr)++ -- The net total's register is that of all the sections' account+ -- types. It shows the net with the opposite sign when a section's+ -- negation is not undone by subtracting it, as an income statement's+ -- revenues are added negated.+ netterm = fmap (("type:" <>) . T.concat) $ traverse (typeCodes . cbcsubreportquery) specs+ netnegated = any (\spec -> negated spec /= not (cbcsubreportincreasestotal spec)) specs+ netrows =+ if no_total_ ropts || length subreports == 1 then []+ else+ linkedWhen netterm $+ multiBalanceTotalsRows fmt ropts (reportLinkOpts ropts colspans){loNegated = netnegated}+ (maybeToList netterm) allCommodities colspans "Net:" totalrow++-- | All commodities appearing in any of these subreports, sorted.+-- Used as the commodity column order for LayoutBareWide across the whole+-- compound report; it must cover every row rendered, including the totals+-- row, see 'setDisplayCommodityBare' in "Hledger.Cli.Commands.Balance.Internal".+allCommoditiesFromSubreports ::+ [(text, PeriodicReport a MixedAmount, bool)] -> [CommoditySymbol]+allCommoditiesFromSubreports =+ Set.toAscList .+ foldMap (\(_,mbr,_) ->+ foldMap (foldMap maCommodities . prrAmounts) $ prRows mbr)
+ Hledger/Cli/Conf.hs view
@@ -0,0 +1,455 @@+{-|+Read extra CLI arguments from a hledger config file.+-}++{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE NamedFieldPuns #-}+{-# LANGUAGE MultiWayIf #-}+{-# LANGUAGE TupleSections #-}++module Hledger.Cli.Conf (+ Conf+ ,SectionName+ ,CommandAlias+ ,CommandLine+ ,getConf+ ,getConf'+ ,nullconf+ ,confLookup+ ,confAliases+ ,ResolvedCommand(..)+ ,expandCommandAlias+ ,confFileIsTrusted+ ,activeConfFile+ ,activeLocalConfFile+ ,activeUserConfFile+ ,confFiles+ ,userConfFiles+ ,parseConf+)+where++import Control.Exception (handle)+import Control.Monad (void, forM, guard)+import Control.Monad.Identity (Identity)+import Data.Functor ((<&>))+import Data.Map qualified as M+import Data.Maybe (catMaybes)+import Data.Text (Text)+import Data.Text qualified as T (empty, lines, pack, unpack)+import Safe (headDef, headMay, lastDef)+import System.Directory (getHomeDirectory, getXdgDirectory, XdgDirectory (XdgConfig), doesFileExist, getCurrentDirectory)+import System.FilePath ((</>), takeDirectory)+import Text.Megaparsec as M+import Text.Megaparsec.Char+import Text.Printf (printf)++import Hledger (decorateExcerpt, error', strip, words', wordsmay, RawOpts, expandPath)+import Hledger.Read.Common+import Hledger.Utils.Parse+import Hledger.Utils.Debug+import Hledger.Data.RawOptions (collectopts)+++-- | A hledger config file.+data Conf = Conf {+ confFile :: FilePath+ ,confText :: Text+ ,confFormat :: Int+ ,confSections :: [ConfSection]+} deriving (Eq,Show)++-- | One section in a hledger config file.+data ConfSection = ConfSection {+ csName :: SectionName+ ,csArgs :: [(Int, Arg)] -- ^ arguments, with the config file line number where each appeared+} deriving (Eq,Show)++-- | The name of a config file section, with surrounding brackets and whitespace removed.+type SectionName = String++-- | A command line argument to be passed to CmdArgs.process.+-- It seems this should be a single command line argument (or flag or flag value).+-- If it contains spaces, those are treated as part of a single argument, as with CMD a "b c".+type Arg = String++-- | The name of a command alias (a custom command) defined in a config file.+type CommandAlias = String++-- | A command line (a command name followed by arguments), as a single string.+-- Eg the command line which a command alias expands to.+type CommandLine = String++nullconf = Conf {+ confFile = ""+ ,confText = T.empty+ ,confFormat = 1+ ,confSections = []+}++-- | The --conf or --no-conf or default config file specified by command line options.+data ConfFileSpec =+ SomeConfFile FilePath -- ^ use config file specified with --conf+ | NoConfFile -- ^ don't use any config file (--no-conf)+ | AutoConfFile -- ^ use the config file found by directory search (default)+ deriving (Eq,Show)++-- Get the conf file specification from options,+-- considering the rightmost --conf or --no-conf option if any.+confFileSpecFromRawOpts :: RawOpts -> ConfFileSpec+confFileSpecFromRawOpts = lastDef AutoConfFile . collectopts cfsFromRawOpt+ where+ cfsFromRawOpt ("conf",f) = Just $ SomeConfFile f+ cfsFromRawOpt ("no-conf",_) = Just $ NoConfFile+ cfsFromRawOpt _ = Nothing++-- config reading++-- | Fetch all the arguments/options defined in a section with this name, if it exists.+-- This should be "general" for the unnamed first section, or a hledger command name.+confLookup :: SectionName -> Conf -> [Arg]+confLookup cmd Conf{confSections} =+ maybe [] (concatMap $ words' . snd) $ -- XXX PARTIAL+ M.lookup cmd $+ M.fromList [(csName,csArgs) | ConfSection{csName,csArgs} <- confSections]++-- | Get the command aliases (custom commands) defined in this config file,+-- in order of definition. They are defined git-style in an @[alias]@+-- section, like @NAME = CMDLINE@; a value may continue on following, more-indented lines.+-- If a name is defined more than once, the last definition should win (callers can rely+-- on the ordering here). An [alias] section line without an @=@ raises a usage error.+-- (In practice it won't, since readConfFile validates with confAliasesE first.)+confAliases :: Conf -> [(CommandAlias, CommandLine)]+confAliases = either error' id . confAliasesE++-- | Like confAliases, but return a (pretty, multiline) error message+-- if a bad alias definition is found.+confAliasesE :: Conf -> Either String [(CommandAlias, CommandLine)]+confAliasesE conf@Conf{confSections} = concat <$> mapM sectionaliases confSections+ where+ sectionaliases ConfSection{csName, csArgs}+ | csName == "alias" = mapM aliasline csArgs+ | otherwise = Right []+ aliasline (lnum, l) = case break (=='=') l of+ (name, '=':cmdline) | not $ null $ strip name -> Right (strip name, strip cmdline)+ _ -> Left $ confErrorAt conf lnum l+ "an [alias] section line should look like: NAME = COMMAND [ARGS..]"++-- | Check that each argument line in this config file can be parsed as command line+-- arguments (eg, quotes must be balanced); return a pretty, multiline error message if not.+confArgsE :: Conf -> Either String ()+confArgsE conf@Conf{confSections} =+ mapM_ argline [lnuma | ConfSection{csArgs} <- confSections, lnuma <- csArgs]+ where+ argline (lnum, l) = case wordsmay l of+ Just _ -> Right ()+ Nothing -> Left $ confErrorAt conf lnum l $+ "this config file line has an unmatched quote (' or \")."++-- | Make a pretty, multiline error message about a problem on the given line+-- of this config file: file path and line number, an excerpt showing the line+-- as written (or the given fallback text), and an explanation.+confErrorAt :: Conf -> Int -> String -> String -> String+confErrorAt Conf{confFile, confText} lnum fallbacktxt explanation =+ printf "%s:%d:\n%s%s" confFile lnum (T.unpack excerpt) explanation+ where+ excerpt = decorateExcerpt lnum Nothing $ (<> T.pack "\n") $+ headDef (T.pack fallbacktxt) $ drop (lnum-1) $ T.lines confText++-- | The result of resolving a command name that may be a command alias.+data ResolvedCommand+ = HledgerCommand String [Arg] -- ^ a resolved hledger command name, and arguments to prepend+ | ShellCommand String -- ^ a shell command line (from a !-prefixed alias, ! stripped)+ deriving (Eq,Show)++-- | Resolve a command name which may be a command alias, to either a real hledger command+-- (with any arguments to prepend) or a shell command line (for a @!@-prefixed alias).+-- Aliases can refer to other aliases; a name that is an exact builtin command name (per the+-- given predicate), or already seen during this expansion (a self-reference or cycle), stops+-- the recursion. If a name is defined more than once, the first definition in the given list+-- wins (callers wanting the config file's last-definition-wins behaviour should pass+-- @reverse (confAliases conf)@). This does not enforce the shell-alias trust policy; callers do.+expandCommandAlias :: (String -> Bool) -> [(CommandAlias, CommandLine)] -> String -> ResolvedCommand+expandCommandAlias isbuiltincmd cmdaliases = go []+ where+ go seen name+ | name `notElem` seen+ , not $ isbuiltincmd name+ , Just cmdline <- lookup name cmdaliases =+ case strip cmdline of+ '!':shellcmd -> ShellCommand (strip shellcmd)+ hledgercmd -> case words' hledgercmd of+ (realcmd:defargs) -> case go (name:seen) realcmd of+ HledgerCommand realcmd' defargs' -> HledgerCommand realcmd' (defargs' <> defargs)+ ShellCommand shellcmd -> ShellCommand (unwords $ shellcmd : defargs)+ [] -> HledgerCommand name []+ | otherwise = HledgerCommand name []++-- | Is the active config file trusted enough to run its @!@-prefixed shell command aliases?+-- True if the config file was given explicitly with --conf, or is a user-level config file+-- (~/.hledger.conf or the XDG hledger.conf). False for a config file found automatically in the+-- current directory or a parent (which could come from an untrusted downloaded/shared directory),+-- or when there is no config file.+confFileIsTrusted :: RawOpts -> Maybe FilePath -> IO Bool+confFileIsTrusted _ Nothing = return False+confFileIsTrusted rawopts (Just f) =+ case confFileSpecFromRawOpts rawopts of+ SomeConfFile _ -> return True+ _ -> (f `elem`) <$> userConfFiles++-- | Try to read a hledger config from a config file specified by --conf,+-- or the first config file found in any of several default file paths.+-- If --no-conf was used, or if no file was specified or found, this returns a null Conf.+-- If a specified file, or the first file found, can not be read or parsed, this returns an error message.+-- Otherwise this returns the parsed Conf, and the file path.+getConf :: RawOpts -> IO (Either String (Conf, Maybe FilePath))+getConf rawopts = do+ -- As in Cli.hs, conf debug output always goes to stderr;+ -- that's ok as conf is a hledger cli feature for now.+ case confFileSpecFromRawOpts rawopts of+ NoConfFile -> return $ Right $ dbg1Msg "ignoring config files" (nullconf, Nothing)+ SomeConfFile f -> getCurrentDirectory >>= flip expandPath f >>= readConfFile . dbg1 "using specified config file"+ AutoConfFile -> do+ fs <- confFiles+ case fs of+ f:_ -> dbg8IO "found config files" fs >> dbg1IO "using nearest config file" f >> readConfFile f+ [] -> return $ Right $ dbg1Msg "no config file found" (nullconf, Nothing)++-- | Like getConf but throws an error on failure.+getConf' :: RawOpts -> IO (Conf, Maybe FilePath)+getConf' rawopts = getConf rawopts >>= either error' return++-- | Read this config file and parse its contents, or return an error message.+readConfFile :: FilePath -> IO (Either String (Conf, Maybe FilePath))+readConfFile f = handle (\(e::IOError) -> return $ Left $ show e) $ do+ -- avoid GHC 9.10.1's ugly stack trace when calling readFile on a nonexistent file+ exists <- doesFileExist f+ case exists of+ False -> return $ Left $ f <> " does not exist"+ True -> do+ txt <- readFile f <&> T.pack+ case parseConf f txt of+ Left err -> return $ Left $ customErrorBundlePretty err+ Right cs -> do+ let conf = nullconf{+ confFile = f+ ,confText = txt+ ,confFormat = 1+ ,confSections = cs+ }+ -- validate the config now, so problems are reported promptly:+ -- argument lines must be parseable as command line arguments,+ -- and command alias definitions must be well formed+ return $ (conf, Just f) <$ (confArgsE conf >> confAliasesE conf)++-- -- | Like readConf, but throw an error on failure.+-- readConfFile' :: FilePath -> IO (Conf, Maybe FilePath)+-- readConfFile' f = readConfFile f >>= either (error' . show) return++-- | Get the highest precedence config file, based on the current directory.+activeConfFile :: IO (Maybe FilePath)+activeConfFile = headMay <$> confFiles++-- | Get the highest precedence local config file: +-- a config file in the current directory or above, that is not a user-wide config file.+activeLocalConfFile :: IO (Maybe FilePath)+activeLocalConfFile = do+ ufs <- userConfFiles+ mf <- headMay <$> confFiles+ return $ case mf of+ Just f | f `notElem` ufs -> Just f+ _ -> Nothing++-- | Get the highest precedence user-wide config file, based on the current directory.+-- (This may not be the active config file.)+activeUserConfFile :: IO (Maybe FilePath)+activeUserConfFile = headMay <$> userConfFiles++-- | Get the possibleConfFiles which exist, based on the current directory.+confFiles :: IO [FilePath]+confFiles = possibleConfFiles >>= existingFiles++-- | Get the possibleUserConfFiles which exist, based on the current directory.+userConfFiles :: IO [FilePath]+userConfFiles = possibleUserConfFiles >>= existingFiles++-- | Filter a list of paths to just the existing files.+existingFiles :: [FilePath] -> IO [FilePath]+existingFiles fs =+ fmap catMaybes $ forM fs $ \f -> do+ exists <- doesFileExist f+ return $ if exists then Just f else Nothing++-- | Get the possible paths for a hledger config file, highest precedence first:+-- hledger.conf in the current directory, +-- hledger.conf in any parent directory, +-- .hledger.conf in the home directory,+-- or hledger.conf in the XdgConfig directory.+possibleConfFiles :: IO [FilePath]+possibleConfFiles = do+ ds <- possibleConfDirs+ home <- getHomeDirectory+ return $ dbg8 "possible config file paths" $+ flip map ds $ \d -> d </> if d==home then ".hledger.conf" else "hledger.conf"++-- | Like possibleConfFiles, but consider only user-wide hledger config files:+-- .hledger.conf in the home directory,+-- or hledger.conf in the XdgConfig directory.+possibleUserConfFiles :: IO [FilePath]+possibleUserConfFiles = do+ home <- getHomeDirectory+ xdgc <- getXdgDirectory XdgConfig "hledger"+ let ds = [home,xdgc]+ return $ dbg8 "possible user config file paths" $+ flip map ds $ \d -> d </> if d==home then ".hledger.conf" else "hledger.conf"++-- | Get the directories where a hledger config file could be, highest precedence first:+-- the current directory, any parent directory, the home directory, or the XdgConfig directory.+possibleConfDirs :: IO [FilePath]+possibleConfDirs = do+ xdgc <- getXdgDirectory XdgConfig "hledger"+ home <- getHomeDirectory+ here <- getCurrentDirectory+ dirs <- getDirsUpToRoot here+ let dirs2 = if home `elem` dirs then dirs else dirs <> [home]+ let dirs3 = if xdgc `elem` dirs2 then dirs2 else dirs2 <> [xdgc]+ return $ dbg8 "searching config dirs" dirs3++-- | Get this directory and all of its parents up to /.+getDirsUpToRoot :: FilePath -> IO [FilePath]+getDirsUpToRoot dir = return $ go [] dir+ where+ go seen d = if+ | d `elem` seen || length seen >= 100 -> [] -- just in case+ | d=="/" -> [d]+ | otherwise -> d : go (d:seen) (takeDirectory d)++-- config file parsing++parseConf :: FilePath -> Text -> Either (ParseErrorBundle Text HledgerParseErrorData) [ConfSection]+parseConf = runParser confp++dp :: String -> TextParser m ()+dp = const $ return () -- no-op+-- dp = dbgparse 0 -- trace parse state at this --debug level++-- get the config file line number at the current parse position+sourceLineNumberp :: TextParser Identity Int+sourceLineNumberp = unPos . sourceLine <$> getSourcePos++whitespacep, commentlinesp, restoflinep :: TextParser Identity ()+whitespacep = void $ {- dp "whitespacep" >> -} many spacenonewline+-- Uses try so that a non-empty, non-comment line (possibly indented) is left for+-- another parser instead of failing here after consuming its leading whitespace.+commentlinesp = void $ {- dp "commentlinesp" >> -} many (try $ emptyorcommentlinep2 "#")+restoflinep = void $ {- dp "restoflinep" >> -} whitespacep >> emptyorcommentlinep2 "#"++confp :: TextParser Identity [ConfSection] -- a monadic TextParser to allow reusing other hledger parsers+confp = do+ dp "confp"+ commentlinesp+ genas <- many arglinep+ let s = ConfSection "general" genas+ ss <- many $ do+ (n, ma) <- sectionstartp+ -- In an [alias] section, a NAME = ... value can span more-indented lines; parse each+ -- alias as one logical (joined) line. Other sections keep one argument per line.+ as <- if n == "alias" then many aliasdefp else many arglinep+ return $ ConfSection n (maybe as (:as) ma)+ whitespacep -- tolerate trailing whitespace with no final newline (a blank last line)+ eof+ return $ s:ss++-- parse a section name and possibly arguments written on the same line+sectionstartp :: TextParser Identity (String, Maybe (Int, Arg))+sectionstartp = do+ dp "sectionstartp"+ try (whitespacep <* lookAhead (char '[')) -- ignore any leading whitespace before the [+ char '['+ n <- fmap strip $ some $ noneOf "]#\n"+ char ']'+ -- dp "sectionstartp2"+ whitespacep+ -- dp "sectionstartp3"+ lnum <- sourceLineNumberp+ ma <- fmap (fmap strip) $ optional argtextp+ -- dp "sectionstartp4"+ restoflinep+ -- dp "sectionstartp5"+ commentlinesp+ -- dp "sectionstartp6"+ return (n, (lnum,) <$> ma)++-- | Parse config argument-line text up to an unquoted '#' (which starts a comment) or end of line,+-- keeping any '#' that appears inside single or double quotes (so quoted arguments can contain '#').+argtextp :: TextParser Identity String+argtextp = fmap concat $ some $+ quotedspanp '\'' <|> quotedspanp '"' <|> some (noneOf "'\"#\n")+ where+ quotedspanp q = do+ _ <- char q+ s <- many (noneOf [q,'\n'])+ qc <- optional (char q)+ return $ q : s ++ maybe "" pure qc++-- Uses try so that an indented section header ([..]) is left for sectionstartp+-- rather than failing here after consuming its leading whitespace.+arglinep :: TextParser Identity (Int, Arg)+arglinep = try $ do+ dp "arglinep"+ whitespacep -- ignore any leading whitespace+ -- dp "arglinep2"+ notFollowedBy $ char '[' -- an indented section header is not an argument line+ -- dp "arglinep3"+ lnum <- sourceLineNumberp+ a <- argtextp+ -- dp "arglinep4"+ restoflinep <|> whitespacep -- whitespace / same-line comment, possibly with no newline+ commentlinesp+ return (lnum, strip a)++-- | Parse one alias definition in an [alias] section: a "NAME = ..." line, plus any+-- following lines indented more than it, joined (whitespace-normalised) into one logical line.+-- Blank and comment lines are skipped; a line indented no more than the NAME line, a section+-- header, or end of file ends the definition. This is what lets an alias's command line span+-- several indented lines.+aliasdefp :: TextParser Identity (Int, Arg)+aliasdefp = try $ do+ whitespacep -- ignore any leading whitespace+ notFollowedBy $ char '[' -- an indented section header is not an alias definition+ lnum <- sourceLineNumberp+ ref <- indentcolp -- the column of this alias's NAME+ first <- argtextp+ restoflinep <|> whitespacep+ conts <- many (continuationp ref)+ commentlinesp -- consume trailing blank/comment lines before the next definition or header+ return (lnum, strip $ unwords $ strip first : conts)+ where+ -- a line indented more than ref (the NAME column), continuing the alias's command line+ continuationp ref = try $ do+ commentlinesp -- skip any blank/comment lines within the indented block+ whitespacep+ col <- indentcolp+ guard $ col > ref+ notFollowedBy $ char '[' -- a section header ends the definition even if indented+ s <- argtextp+ restoflinep <|> whitespacep+ return $ strip s++-- the column (1-based) at the current parse position, used to compare indentation+indentcolp :: TextParser Identity Int+indentcolp = unPos . sourceColumn <$> getSourcePos+++-- initialiseAndParseJournal :: ErroringJournalParser IO ParsedJournal -> InputOpts+-- -> FilePath -> Text -> ExceptT String IO Journal+-- initialiseAndParseJournal parser iopts f txt =+-- prettyParseErrors $ runParserT (evalStateT parser initJournal) f txt+-- where+-- y = first3 . toGregorian $ _ioDay iopts+-- initJournal = nulljournal{jparsedefaultyear = Just y, jparseincludefilestack = [f]}+-- -- Flatten parse errors and final parse errors, and output each as a pretty String.+-- prettyParseErrors :: ExceptT FinalParseError IO (Either (ParseErrorBundle Text HledgerParseErrorData) a)+-- -> ExceptT String IO a+-- prettyParseErrors = withExceptT customErrorBundlePretty . liftEither+-- <=< withExceptT (finalErrorBundlePretty . attachSource f txt)
− Hledger/Cli/Convert.hs
@@ -1,546 +0,0 @@-{-|-Convert account data in CSV format (eg downloaded from a bank) to journal-format, and print it on stdout. See the manual for more details.--}--module Hledger.Cli.Convert where-import Control.Monad (when, guard, liftM)-import Data.List-import Data.Maybe-import Data.Ord-import Data.Time.Format (parseTime)-import Safe-import System.Directory (doesFileExist)-import System.Exit (exitFailure)-import System.FilePath (takeBaseName, replaceExtension)-import System.IO (stderr)-import System.Locale (defaultTimeLocale)-import Test.HUnit-import Text.CSV (parseCSV, parseCSVFromFile, CSV)-import Text.ParserCombinators.Parsec-import Text.Printf (hPrintf)--import Prelude hiding (getContents)-import Hledger.Utils.UTF8 (getContents)-import Hledger-import Hledger.Cli.Format-import qualified Hledger.Cli.Format as Format-import Hledger.Cli.Version-import Hledger.Cli.Options--{- |-A set of data definitions and account-matching patterns sufficient to-convert a particular CSV data file into meaningful journal transactions. See above.--}-data CsvRules = CsvRules {- dateField :: Maybe FieldPosition,- dateFormat :: Maybe String,- statusField :: Maybe FieldPosition,- codeField :: Maybe FieldPosition,- descriptionField :: [FormatString],- amountField :: Maybe FieldPosition,- amountInField :: Maybe FieldPosition,- amountOutField :: Maybe FieldPosition,- currencyField :: Maybe FieldPosition,- baseCurrency :: Maybe String,- accountField :: Maybe FieldPosition,- account2Field :: Maybe FieldPosition,- effectiveDateField :: Maybe FieldPosition,- baseAccount :: AccountName,- accountRules :: [AccountRule]-} deriving (Show, Eq)--nullrules = CsvRules {- dateField=Nothing,- dateFormat=Nothing,- statusField=Nothing,- codeField=Nothing,- descriptionField=[],- amountField=Nothing,- amountInField=Nothing,- amountOutField=Nothing,- currencyField=Nothing,- baseCurrency=Nothing,- accountField=Nothing,- account2Field=Nothing,- effectiveDateField=Nothing,- baseAccount="unknown",- accountRules=[]-}--type FieldPosition = Int--type AccountRule = (- [(String, Maybe String)] -- list of regex match patterns with optional replacements- ,AccountName -- account name to use for a transaction matching this rule- )--type CsvRecord = [String]----- | Read the CSV file named as an argument and print equivalent journal transactions,--- using/creating a .rules file.-convert :: CliOpts -> IO ()-convert opts = do- let csvfile = case headDef "" $ patterns_ $ reportopts_ opts of- "" -> "-"- s -> s- usingStdin = csvfile == "-"- rulesFileSpecified = isJust $ rules_file_ opts- rulesfile = rulesFileFor opts csvfile- when (usingStdin && (not rulesFileSpecified)) $ error' "please use --rules-file to specify a rules file when converting stdin"- csvparse <- parseCsv csvfile- let records = case csvparse of- Left e -> error' $ show e- Right rs -> filter (/= [""]) rs- exists <- doesFileExist rulesfile- if (not exists) then do- hPrintf stderr "creating conversion rules file %s, edit this file for better results\n" rulesfile- writeFile rulesfile initialRulesFileContent- else- hPrintf stderr "using conversion rules file %s\n" rulesfile- rules <- liftM (either (error'.show) id) $ parseCsvRulesFile rulesfile- let invalid = validateRules rules- when (debug_ opts) $ hPrintf stderr "rules: %s\n" (show rules)- when (isJust invalid) $ error (fromJust invalid)- let requiredfields = max 2 (maxFieldIndex rules + 1)- badrecords = take 1 $ filter ((< requiredfields).length) records- if null badrecords- then do- mapM_ (putStr . show) $ sortBy (comparing tdate) $ map (transactionFromCsvRecord rules) records- else do- hPrintf stderr (unlines [- "Warning, at least one CSV record does not contain a field referenced by the"- ,"conversion rules file, or has less than two fields. Are you converting a"- ,"valid CSV file ? First bad record:\n%s"- ]) (show $ head badrecords)- exitFailure--parseCsv :: FilePath -> IO (Either ParseError CSV)-parseCsv path =- case path of- "-" -> liftM (parseCSV "(stdin)") getContents- p -> parseCSVFromFile p---- | The highest (0-based) field index referenced in the field--- definitions, or -1 if no fields are defined.-maxFieldIndex :: CsvRules -> Int-maxFieldIndex r = maximumDef (-1) $ catMaybes [- dateField r- ,statusField r- ,codeField r- ,amountField r- ,amountInField r- ,amountOutField r- ,currencyField r- ,accountField r- ,account2Field r- ,effectiveDateField r- ]--rulesFileFor :: CliOpts -> FilePath -> FilePath-rulesFileFor CliOpts{rules_file_=Just f} _ = f-rulesFileFor CliOpts{rules_file_=Nothing} csvfile = replaceExtension csvfile ".rules"--initialRulesFileContent :: String-initialRulesFileContent =- "# csv conversion rules file generated by "++(progversionstr progname)++"\n" ++- "# Add rules to this file for more accurate conversion, see\n"++- "# http://hledger.org/MANUAL.html#convert\n" ++- "\n" ++- "base-account assets:bank:checking\n" ++- "date-field 0\n" ++- "description-field 4\n" ++- "amount-field 1\n" ++- "base-currency $\n" ++- "\n" ++- "# account-assigning rules\n" ++- "\n" ++- "SPECTRUM\n" ++- "expenses:health:gym\n" ++- "\n" ++- "ITUNES\n" ++- "BLKBSTR=BLOCKBUSTER\n" ++- "expenses:entertainment\n" ++- "\n" ++- "(TO|FROM) SAVINGS\n" ++- "assets:bank:savings\n"--validateRules :: CsvRules -> Maybe String-validateRules rules = let- hasAmount = isJust $ amountField rules- hasIn = isJust $ amountInField rules- hasOut = isJust $ amountOutField rules- in case (hasAmount, hasIn, hasOut) of- (True, True, _) -> Just "Don't specify amount-in-field when specifying amount-field"- (True, _, True) -> Just "Don't specify amount-out-field when specifying amount-field"- (_, False, True) -> Just "Please specify amount-in-field when specifying amount-out-field"- (_, True, False) -> Just "Please specify amount-out-field when specifying amount-in-field"- (False, False, False) -> Just "Please specify either amount-field, or amount-in-field and amount-out-field"- _ -> Nothing---- rules file parser--parseCsvRulesFile :: FilePath -> IO (Either ParseError CsvRules)-parseCsvRulesFile f = do- s <- readFile f- return $ parseCsvRules f s--parseCsvRules :: FilePath -> String -> Either ParseError CsvRules-parseCsvRules rulesfile s = runParser csvrulesfile nullrules{baseAccount=takeBaseName rulesfile} rulesfile s--csvrulesfile :: GenParser Char CsvRules CsvRules-csvrulesfile = do- many blankorcommentline- many definitions- r <- getState- ars <- many accountrule- many blankorcommentline- eof- return r{accountRules=ars}--definitions :: GenParser Char CsvRules ()-definitions = do- choice' [- datefield- ,dateformat- ,statusfield- ,codefield- ,descriptionfield- ,amountfield- ,amountinfield- ,amountoutfield- ,currencyfield- ,accountfield- ,account2field- ,effectivedatefield- ,basecurrency- ,baseaccount- ,commentline- ] <?> "definition"- return ()--datefield = do- string "date-field"- many1 spacenonewline- v <- restofline- updateState (\r -> r{dateField=readMay v})--effectivedatefield = do- string "effective-date-field"- many1 spacenonewline- v <- restofline- updateState (\r -> r{effectiveDateField=readMay v})--dateformat = do- string "date-format"- many1 spacenonewline- v <- restofline- updateState (\r -> r{dateFormat=Just v})--codefield = do- string "code-field"- many1 spacenonewline- v <- restofline- updateState (\r -> r{codeField=readMay v})--statusfield = do- string "status-field"- many1 spacenonewline- v <- restofline- updateState (\r -> r{statusField=readMay v})--descriptionFieldValue :: GenParser Char st [FormatString]-descriptionFieldValue = do--- try (fieldNo <* spacenonewline)- try fieldNo- <|> formatStrings- where- fieldNo = many1 digit >>= \x -> return [FormatField False Nothing Nothing $ FieldNo $ read x]--descriptionfield = do- string "description-field"- many1 spacenonewline- formatS <- descriptionFieldValue- restofline- updateState (\x -> x{descriptionField=formatS})--amountfield = do- string "amount-field"- many1 spacenonewline- v <- restofline- x <- updateState (\r -> r{amountField=readMay v})- return x--amountinfield = do- choice [string "amount-in-field", string "in-field"]- many1 spacenonewline- v <- restofline- updateState (\r -> r{amountInField=readMay v})--amountoutfield = do- choice [string "amount-out-field", string "out-field"]- many1 spacenonewline- v <- restofline- updateState (\r -> r{amountOutField=readMay v})--currencyfield = do- string "currency-field"- many1 spacenonewline- v <- restofline- updateState (\r -> r{currencyField=readMay v})--accountfield = do- string "account-field"- many1 spacenonewline- v <- restofline- updateState (\r -> r{accountField=readMay v})--account2field = do- string "account2-field"- many1 spacenonewline- v <- restofline- updateState (\r -> r{account2Field=readMay v})--basecurrency = do- choice [string "base-currency", string "currency"]- many1 spacenonewline- v <- restofline- updateState (\r -> r{baseCurrency=Just v})--baseaccount = do- string "base-account"- many1 spacenonewline- v <- ledgeraccountname- optional newline- updateState (\r -> r{baseAccount=v})--accountrule :: GenParser Char CsvRules AccountRule-accountrule = do- many blankorcommentline- pats <- many1 matchreplacepattern- guard $ length pats >= 2- let pats' = init pats- acct = either (fail.show) id $ runParser ledgeraccountname () "" $ fst $ last pats- many blankorcommentline- return (pats',acct)- <?> "account rule"--blanklines = many1 blankline--blankline = many spacenonewline >> newline >> return () <?> "blank line"--commentchar = oneOf ";#"--commentline = many spacenonewline >> commentchar >> restofline >> return () <?> "comment line"--blankorcommentline = choice' [blankline, commentline]--matchreplacepattern = do- notFollowedBy commentchar- matchpat <- many1 (noneOf "=\n")- replpat <- optionMaybe $ do {char '='; many $ noneOf "\n"}- newline- return (matchpat,replpat)---- csv record conversion-formatD :: CsvRecord -> Bool -> Maybe Int -> Maybe Int -> Field -> String-formatD record leftJustified min max f = case f of - FieldNo n -> maybe "" show $ atMay record n- -- Some of these might in theory in read from fields- Format.Account -> ""- DepthSpacer -> ""- Total -> ""- DefaultDate -> ""- Description -> ""- where- show = formatValue leftJustified min max--formatDescription :: CsvRecord -> [FormatString] -> String-formatDescription _ [] = ""-formatDescription record (f:fs) = s ++ (formatDescription record fs)- where s = case f of- FormatLiteral l -> l- FormatField leftJustified min max field -> formatD record leftJustified min max field--transactionFromCsvRecord :: CsvRules -> CsvRecord -> Transaction-transactionFromCsvRecord rules fields =- let - date = parsedate $ normaliseDate (dateFormat rules) $ maybe "1900/1/1" (atDef "" fields) (dateField rules)- effectivedate = do idx <- effectiveDateField rules- return $ parsedate $ normaliseDate (dateFormat rules) $ (atDef "" fields) idx- status = maybe False (null . strip . (atDef "" fields)) (statusField rules)- code = maybe "" (atDef "" fields) (codeField rules)- desc = formatDescription fields (descriptionField rules)- comment = ""- precomment = ""- baseacc = maybe (baseAccount rules) (atDef "" fields) (accountField rules)- amountstr = getAmount rules fields- amountstr' = strnegate amountstr where strnegate ('-':s) = s- strnegate s = '-':s- currency = maybe (fromMaybe "" $ baseCurrency rules) (atDef "" fields) (currencyField rules)- amountstr'' = currency ++ amountstr'- amountparse = runParser someamount nullctx "" amountstr''- amount = either (const nullmixedamt) id amountparse- -- Using costOfMixedAmount here to allow complex costs like "10 GBP @@ 15 USD".- -- Aim is to have "10 GBP @@ 15 USD" applied to account "acct", but have "-15USD" applied to "baseacct"- baseamount = costOfMixedAmount amount- unknownacct | (readDef 0 amountstr' :: Double) < 0 = "income:unknown"- | otherwise = "expenses:unknown"- (acct',newdesc) = identify (accountRules rules) unknownacct desc- acct = maybe acct' (atDef "" fields) (account2Field rules)- t = Transaction {- tdate=date,- teffectivedate=effectivedate,- tstatus=status,- tcode=code,- tdescription=newdesc,- tcomment=comment,- tpreceding_comment_lines=precomment,- tmetadata=[],- tpostings=[- Posting {- pstatus=False,- paccount=acct,- pamount=amount,- pcomment="",- ptype=RegularPosting,- pmetadata=[],- ptransaction=Just t- },- Posting {- pstatus=False,- paccount=baseacc,- pamount=(-baseamount),- pcomment="",- ptype=RegularPosting,- pmetadata=[],- ptransaction=Just t- }- ]- }- in t---- | Convert some date string with unknown format to YYYY/MM/DD.-normaliseDate :: Maybe String -- ^ User-supplied date format: this should be tried in preference to all others- -> String -> String-normaliseDate mb_user_format s =- let parsewith = flip (parseTime defaultTimeLocale) s in- maybe (error' $ "could not parse \""++s++"\" as a date, consider adding a date-format directive or upgrading")- showDate $- firstJust $ (map parsewith $- maybe [] (:[]) mb_user_format- -- the - modifier requires time-1.2.0.5, released- -- in 2011/5, so for now we emulate it for wider- -- compatibility. time < 1.2.0.5 also has a buggy- -- %y which we don't do anything about.- -- ++ [- -- "%Y/%m/%d"- -- ,"%Y/%-m/%-d"- -- ,"%Y-%m-%d"- -- ,"%Y-%-m-%-d"- -- ,"%m/%d/%Y"- -- ,"%-m/%-d/%Y"- -- ,"%m-%d-%Y"- -- ,"%-m-%-d-%Y"- -- ]- )- ++ [- parseTime defaultTimeLocale "%Y/%m/%e" s- ,parseTime defaultTimeLocale "%Y-%m-%e" s- ,parseTime defaultTimeLocale "%m/%e/%Y" s- ,parseTime defaultTimeLocale "%m-%e-%Y" s- ,parseTime defaultTimeLocale "%Y/%m/%e" (take 5 s ++ "0" ++ drop 5 s)- ,parseTime defaultTimeLocale "%Y-%m-%e" (take 5 s ++ "0" ++ drop 5 s)- ,parseTime defaultTimeLocale "%m/%e/%Y" ('0':s)- ,parseTime defaultTimeLocale "%m-%e-%Y" ('0':s)- ]---- | Apply account matching rules to a transaction description to obtain--- the most appropriate account and a new description.-identify :: [AccountRule] -> String -> String -> (String,String)-identify rules defacct desc | null matchingrules = (defacct,desc)- | otherwise = (acct,newdesc)- where- matchingrules = filter ismatch rules :: [AccountRule]- where ismatch = any ((`regexMatchesCI` desc) . fst) . fst- (prs,acct) = head matchingrules- p_ms_r = filter (\(_,m,_) -> m) $ map (\(p,r) -> (p, p `regexMatchesCI` desc, r)) prs- (p,_,r) = head p_ms_r- newdesc = case r of Just repl -> regexReplaceCI p repl desc- Nothing -> desc--caseinsensitive = ("(?i)"++)--getAmount :: CsvRules -> CsvRecord -> String-getAmount rules fields = case amountField rules of- Just f -> maybe "" (atDef "" fields) $ Just f- Nothing ->- case (i, o) of- (x, "") -> x- ("", x) -> "-"++x- p -> error' $ "using amount-in-field and amount-out-field, found a value in both fields: "++show p- where- i = maybe "" (atDef "" fields) (amountInField rules)- o = maybe "" (atDef "" fields) (amountOutField rules)--tests_Hledger_Cli_Convert = TestList (test_parser ++ test_description_parsing)--test_description_parsing = [- "description-field 1" ~: assertParseDescription "description-field 1\n" [FormatField False Nothing Nothing (FieldNo 1)]- , "description-field 1 " ~: assertParseDescription "description-field 1 \n" [FormatField False Nothing Nothing (FieldNo 1)]- , "description-field %(1)" ~: assertParseDescription "description-field %(1)\n" [FormatField False Nothing Nothing (FieldNo 1)]- , "description-field %(1)/$(2)" ~: assertParseDescription "description-field %(1)/%(2)\n" [- FormatField False Nothing Nothing (FieldNo 1)- , FormatLiteral "/"- , FormatField False Nothing Nothing (FieldNo 2)- ]- ]- where- assertParseDescription string expected = do assertParseEqual (parseDescription string) (nullrules {descriptionField = expected})- parseDescription :: String -> Either ParseError CsvRules- parseDescription x = runParser descriptionfieldWrapper nullrules "(unknown)" x- descriptionfieldWrapper :: GenParser Char CsvRules CsvRules- descriptionfieldWrapper = do- descriptionfield- r <- getState- return r--test_parser = [-- "convert rules parsing: empty file" ~: do- -- let assertMixedAmountParse parseresult mixedamount =- -- (either (const "parse error") showMixedAmountDebug parseresult) ~?= (showMixedAmountDebug mixedamount)- assertParseEqual (parseCsvRules "unknown" "") nullrules-- ,"convert rules parsing: accountrule" ~: do- assertParseEqual (parseWithCtx nullrules accountrule "A\na\n") -- leading blank line required- ([("A",Nothing)], "a")-- ,"convert rules parsing: trailing comments" ~: do- assertParse (parseWithCtx nullrules csvrulesfile "A\na\n# \n#\n")-- ,"convert rules parsing: trailing blank lines" ~: do- assertParse (parseWithCtx nullrules csvrulesfile "A\na\n\n \n")-- -- not supported- -- ,"convert rules parsing: no final newline" ~: do- -- assertParse (parseWithCtx nullrules csvrulesfile "A\na")- -- assertParse (parseWithCtx nullrules csvrulesfile "A\na\n# \n#")- -- assertParse (parseWithCtx nullrules csvrulesfile "A\na\n\n ")-- -- (nullrules{- -- -- dateField=Maybe FieldPosition,- -- -- statusField=Maybe FieldPosition,- -- -- codeField=Maybe FieldPosition,- -- -- descriptionField=Maybe FieldPosition,- -- -- amountField=Maybe FieldPosition,- -- -- currencyField=Maybe FieldPosition,- -- -- baseCurrency=Maybe String,- -- -- baseAccount=AccountName,- -- accountRules=[- -- ([("A",Nothing)], "a")- -- ]- -- })-- ]
+ Hledger/Cli/DocFiles.hs view
@@ -0,0 +1,323 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE PackageImports #-}+{-# LANGUAGE ScopedTypeVariables #-}+{-# LANGUAGE TemplateHaskell #-}+{-|++Embedded documentation files in various formats, and helpers for viewing them.++|-}++module Hledger.Cli.DocFiles (++ Topic+ ,TopicResolution(..)+ ,manualTitle+ ,manualHeadings+ ,manualTopicsMatching+ ,resolveManualTopic+ ,printHelpForTopic+ ,runManForTopic+ ,runInfoForTopic+ ,runPagerForTopic+ ,runTldrForPage++ ) where++import Control.Exception+import Data.ByteString (ByteString)+import Data.Char (isUpper, isLower, toLower)+import Data.ByteString.Char8 qualified as BC+import Data.List (dropWhileEnd, isInfixOf, isPrefixOf, nub)+import Data.Maybe (fromMaybe, maybeToList)+import Data.String+import System.Directory (findExecutable)+import System.Environment (setEnv)+import System.IO+import System.IO.Temp+import System.Process++import Hledger.Utils (first3, second3, third3, embedFileRelative, error', shellQuoteIfNeeded)+import Text.Printf (printf)+import System.Environment (lookupEnv)+import Hledger.Utils.Debug++-- The name of any hledger executable.+type Tool = String++-- Any heading in the hledger user manual (and perhaps later the hledger-ui/hledger-web manuals).+type Topic = String++-- Any name of a hledger tldr page (hledger, hledger-ui, hledger-print etc.)+type TldrPage = String++-- | All hledger-related pages from the tldr-pages project.+-- All are symlinked into the hledger package directory to allow embeddeding.+tldrs :: [(TldrPage, ByteString)]+tldrs = [+ ("hledger-accounts", $(embedFileRelative "embeddedfiles/hledger-accounts.md"))+ ,("hledger-add", $(embedFileRelative "embeddedfiles/hledger-add.md"))+ ,("hledger-aregister", $(embedFileRelative "embeddedfiles/hledger-aregister.md"))+ ,("hledger-balance", $(embedFileRelative "embeddedfiles/hledger-balance.md"))+ ,("hledger-balancesheet", $(embedFileRelative "embeddedfiles/hledger-balancesheet.md"))+ ,("hledger-import", $(embedFileRelative "embeddedfiles/hledger-import.md"))+ ,("hledger-incomestatement", $(embedFileRelative "embeddedfiles/hledger-incomestatement.md"))+ ,("hledger-print", $(embedFileRelative "embeddedfiles/hledger-print.md"))+ ,("hledger-ui", $(embedFileRelative "embeddedfiles/hledger-ui.md"))+ ,("hledger-web", $(embedFileRelative "embeddedfiles/hledger-web.md"))+ ,("hledger", $(embedFileRelative "embeddedfiles/hledger.md"))+ ]++-- | The main hledger manuals as source for man, info and as plain text.+-- All are symlinked into the hledger package directory to allow embeddeding.+manuals :: [(Tool, (ByteString, ByteString, ByteString))]+manuals = [+ ("hledger",+ ($(embedFileRelative "embeddedfiles/hledger.1")+ ,$(embedFileRelative "embeddedfiles/hledger.txt")+ ,$(embedFileRelative "embeddedfiles/hledger.info")+ ))+ ,("hledger-ui",+ ($(embedFileRelative "embeddedfiles/hledger-ui.1")+ ,$(embedFileRelative "embeddedfiles/hledger-ui.txt")+ ,$(embedFileRelative "embeddedfiles/hledger-ui.info")+ ))+ ,("hledger-web",+ ($(embedFileRelative "embeddedfiles/hledger-web.1")+ ,$(embedFileRelative "embeddedfiles/hledger-web.txt")+ ,$(embedFileRelative "embeddedfiles/hledger-web.info")+ ))+ ]++-- | Get the manual as plain text for this tool, or a not found message.+manualTxt :: Tool -> ByteString+manualTxt name = maybe (fromString $ "No text manual found for tool: "++name) second3 $ lookup name manuals++-- | This tool's manual title, taken from the top running-header line+-- (eg "HLEDGER(1) hledger User Manuals HLEDGER(1)"), with the "(N)" section+-- number stripped (eg "HLEDGER"). Nothing if the manual has no such header.+-- Note this title is not itself a line the viewers can scroll to, so callers+-- resolving a topic to it should show the manual from the top.+manualTitle :: Tool -> Maybe Topic+manualTitle tool = case dropWhile null . lines . BC.unpack $ manualTxt tool of+ (l:_) | (w:_) <- words l, '(' `elem` w -> Just $ takeWhile (/= '(') w+ _ -> Nothing++-- | The section headings in this tool's manual, each with its hierarchy level,+-- usable as help topics. Some heading hierarchy is lost in the rendered plain+-- text, but we recover an approximate level for each: the manual title (see+-- 'manualTitle') is level 1; an all-caps column-0 heading (eg OPTIONS,+-- PART 1: ...) is level 2; any other column-0 heading (eg Options, Journal) is+-- level 3; and a heading indented three spaces is level 4. Headings are+-- non-blank lines at the left margin or indented exactly three spaces,+-- containing no run of two or more spaces (which would indicate wrapped prose,+-- a table, an option entry, or a running header). The standard man-page+-- headings NAME, SYNOPSIS and DESCRIPTION are dropped, as they aren't useful+-- topics and their generic names could clash with real ones.+manualHeadings :: Tool -> [(Topic, Int)]+manualHeadings tool = maybeToList (fmap (\t -> (t, 1)) $ manualTitle tool) ++ sections+ where+ sections =+ [ hl+ | l <- lines . BC.unpack $ manualTxt tool+ , hl@(h, _) <- maybeToList $ headingOf l+ , map toLower h `notElem` ["name", "synopsis", "description"]+ ]+ headingOf l = case span (==' ') l of+ ("", rest) -> (\h -> (h, if level2Caps h then 2 else 3)) <$> headingText rest+ (" ", rest) -> (\h -> (h, 4)) <$> headingText rest+ _ -> Nothing+ headingText s+ | null s' || " " `isInfixOf` s' = Nothing+ | otherwise = Just s'+ where s' = dropWhileEnd (==' ') s+ -- An all-caps column-0 heading is normally a level-2 section, except for a+ -- few that are really level-3 subsections, eg CSV (a data format, sibling of+ -- the Journal/Timeclock/Timedot sections).+ level2Caps h = allCaps h && h `notElem` ["CSV"]+ allCaps s = any isUpper s && not (any isLower s)++-- | Every matchable help topic as (name, tool, heading): every manual's headings+-- (each with the tool whose manual it belongs to), given a unique name for+-- matching and listing. The name is the heading, but with "-ui"/"-web" appended+-- for a hledger-ui/hledger-web heading whose bare name also occurs in another+-- manual (so eg OPTIONS becomes OPTIONS-ui / OPTIONS-web, keeping every name+-- unique and unambiguously matchable). hledger headings always keep their bare+-- name, as does any section name unique to one manual.+manualTopics :: [(Topic, Tool, Topic, Int)]+manualTopics = [(topicName tool h, tool, h, lvl) | (tool, (h, lvl)) <- rawpairs]+ where+ rawpairs = [(tool, hl) | tool <- map fst manuals, hl <- manualHeadings tool]+ manualsWith lch = nub [tool | (tool, (h, _)) <- rawpairs, map toLower h == lch]+ topicName tool h = case tool of+ "hledger-ui" | shared -> h ++ "-ui"+ "hledger-web" | shared -> h ++ "-web"+ _ -> h+ where shared = length (manualsWith (map toLower h)) > 1++-- | The result of resolving a user-supplied topic against all the manuals'+-- topics. A found match carries the tool whose manual it belongs to and the+-- heading to scroll to; an ambiguous match carries the matching topic names,+-- each with its manual heading level (for hierarchical listing).+data TopicResolution = TopicNotFound | TopicFound Tool Topic | TopicAmbiguous [(Topic, Int)]++-- | Resolve a topic to a manual section, searching all the manuals' topic names.+-- A case-insensitive exact match wins; otherwise a unique prefix match is used;+-- otherwise a unique infix match is used. Resolving to a heading (and its tool)+-- lets all viewers (including info and the web anchor) locate the section+-- reliably, and lets callers respond to a bad topic. When the match is+-- ambiguous, all matches of any kind (ie all infix matches) are listed.+resolveManualTopic :: Topic -> TopicResolution+resolveManualTopic topic =+ case exacts of+ [tp] -> found tp+ [] -> case (prefixes, infixes) of+ ([tp], _) -> found tp+ ([], [tp]) -> found tp+ ([], []) -> TopicNotFound+ (_, tps) -> TopicAmbiguous (map nameLevel tps)+ _ -> TopicAmbiguous (map nameLevel infixes)+ where+ exacts = nub $ filter ((== t) . lc . name) manualTopics+ prefixes = nub $ filter ((t `isPrefixOf`) . lc . name) manualTopics+ infixes = nub $ filter ((t `isInfixOf`) . lc . name) manualTopics+ found (_, tool, h, _) = TopicFound tool h+ name (n, _, _, _) = n+ nameLevel (n, _, _, lvl) = (n, lvl)+ lc = map toLower+ t = lc . dropWhileEnd (==' ') $ dropWhile (==' ') topic++-- | The topic names (each with its manual heading level, for hierarchical+-- listing) that contain the given topic as a case-insensitive substring (all+-- topics if the topic is empty). Used by help's -l list mode.+manualTopicsMatching :: Topic -> [(Topic, Int)]+manualTopicsMatching topic = nub $ map nameLevel $ filter ((t `isInfixOf`) . lc . name) manualTopics+ where+ name (n, _, _, _) = n+ nameLevel (n, _, _, lvl) = (n, lvl)+ lc = map toLower+ t = lc . dropWhileEnd (==' ') $ dropWhile (==' ') topic++-- | Get the manual as man source (nroff) for this tool, or a not found message.+manualMan :: Tool -> ByteString+manualMan name = maybe (fromString $ "No man page found for tool: "++name) first3 $ lookup name manuals++-- | Get the manual as info source (texinfo) for this tool, or a not found message.+manualInfo :: Tool -> ByteString+manualInfo name = maybe (fromString $ "No info manual found for tool: "++name) third3 $ lookup name manuals++-- | Print plain text help for this tool. This is the fallback "viewer" used+-- for non-interactive output or a dumb terminal, where no pager is available.+-- To avoid dumping the whole (large) manual, when no topic is requested we print+-- only the introduction: everything up to and including the DESCRIPTION section+-- (ie stopping at the first all-caps top-level heading after it, such as PART 1),+-- followed by a note on how to read the rest.+-- If a topic is requested, or there's no DESCRIPTION heading (eg the+-- hledger-ui/hledger-web manuals), the whole manual is printed.+printHelpForTopic :: Tool -> Maybe Topic -> IO ()+printHelpForTopic tool mtopic = do+ let manual = manualTxt tool+ case mtopic of+ Just _ -> BC.putStr manual -- topic requested: show all, so it isn't hidden+ Nothing ->+ case break (== "DESCRIPTION") (BC.lines manual) of+ (_, []) -> BC.putStr manual -- no DESCRIPTION heading: show all+ (before, desc:after) ->+ case break isTopHeading after of+ (_, []) -> BC.putStr manual -- no following heading: show all+ (body, _) -> do+ BC.putStr $ BC.unlines $ before ++ desc : body+ BC.putStrLn helpTruncationNote++-- | Is this a top-level manual heading: a non-empty line starting in column 0+-- with an uppercase letter and containing no lowercase letters (eg NAME, PART 1: ...)?+isTopHeading :: ByteString -> Bool+isTopHeading l = case BC.uncons l of+ Just (c, _) -> isUpper c && not (BC.any isLower l)+ Nothing -> False++-- | Note appended to the truncated plain-text help.+helpTruncationNote :: ByteString+helpTruncationNote =+ "(This is just the introduction. To read the full manual, run `hledger help`\n\+ \in a more capable terminal, or `hledger help -p` (pager), `-m` (man) or `-i`\n\+ \(info), or see https://hledger.org.)"++-- | Display an info manual for this topic, opened at the given topic if provided,+-- using the "info" executable in $PATH.+-- Topic can be an exact heading or a heading prefix; info will favour an exact match.+runInfoForTopic :: Tool -> Maybe Topic -> IO ()+runInfoForTopic tool mtopic =+ withSystemTempFile ("hledger-"++tool++".info") $ \f h -> do+ BC.hPutStrLn h $ manualInfo tool+ hClose h+ callCommand $ dbg1 "info command" $+ "info -f " ++ shellQuoteIfNeeded f ++ maybe "" (printf " -n '%s'") mtopic++-- less with any vertical whitespace squashed, case-insensitive searching, the $ regex metacharacter accessible as \$.+less = "less -s -i --use-backslash"++-- | Display plain text help for this tool, scrolled to the given topic if any, using the users $PAGER or "less".+-- When a topic is provided we always use less, ignoring $PAGER.+--+-- This is less robust than the newer Hledger.Utils.IO.runPager,+-- but that one doesn't yet support scrolling to a topic.+runPagerForTopic :: Tool -> Maybe Topic -> IO ()+runPagerForTopic tool mtopic = do+ withSystemTempFile ("hledger-"++tool++".txt") $ \f h -> do+ BC.hPutStrLn h $ manualTxt tool+ hClose h+ envpager <- fromMaybe less <$> lookupEnv "PAGER"+ let+ exactmatch = True+ (pager, searcharg) =+ case mtopic of+ Nothing -> (envpager, "")+ Just t -> (less, "-p'^( )?" ++ t ++ if exactmatch then "\\$'" else "")+ callCommand $ dbg1 "pager command" $ unwords [pager, searcharg, shellQuoteIfNeeded f]++-- | Display a man page for this tool, scrolled to the given topic if provided, using "man".+-- When a topic is provided we force man to use "less", ignoring $MANPAGER and $PAGER.+runManForTopic :: Tool -> Maybe Topic -> IO ()+runManForTopic tool mtopic =+ -- This temp file path should have a slash in it, man requires at least one.+ withSystemTempFile ("hledger-"++tool++".1") $ \f h -> do+ BC.hPutStrLn h $ manualMan tool+ hClose h+ let+ exactmatch = True+ pagerarg =+ case mtopic of+ Nothing -> ""+ Just t -> "-P \"" ++ less ++ " -p'^( )?" ++ t ++ (if exactmatch then "\\\\$" else "") ++ "'\""+ callCommand $ dbg1 "man command" $ unwords ["man", pagerarg, shellQuoteIfNeeded f]++-- | Get the named tldr page's source, if we know it.+tldr :: TldrPage -> Maybe ByteString+tldr name = lookup name tldrs++-- | Display one of the hledger tldr pages, using "tldr".+runTldrForPage :: TldrPage -> IO ()+runTldrForPage name =+ case tldr name of+ Nothing -> error' $ "sorry, there are no examples for " <> name <> " yet"+ Just b -> do+ let fallback = do+ hPutStrLn stderr "Warning: could not run tldr --render, using fallback viewer instead.\n"+ BC.putStrLn b+ -- Check for a tldr client first, so we can fall back quietly without the+ -- shell printing a "command not found" error.+ mtldr <- findExecutable "tldr"+ case mtldr of+ Nothing -> fallback+ Just _ -> (do+ withSystemTempFile (name++".md") $ \f h -> do+ BC.hPutStrLn h b+ hClose h+ -- tldr clients tend to auto-update their data, try to discourage that here+ -- tealdeer - doesn't auto-update by default+ -- tlrc - ?+ -- tldr-node-client - undocumented env var suggested in output+ setEnv "TLDR_AUTO_UPDATE_DISABLED" "1"+ callCommand $ dbg1 "tldr command" $ "tldr --render " <> shellQuoteIfNeeded f+ ) `catch` (\(_e::IOException) -> fallback)
− Hledger/Cli/Format.hs
@@ -1,133 +0,0 @@-module Hledger.Cli.Format (- parseFormatString- , formatStrings- , formatValue- , FormatString(..)- , Field(..)- , tests- ) where--import Numeric-import Data.Char (isPrint)-import Data.Maybe-import Test.HUnit-import Text.ParserCombinators.Parsec-import Text.Printf---data Field =- Account- | DefaultDate- | Description- | Total- | DepthSpacer- | FieldNo Int- deriving (Show, Eq)--data FormatString =- FormatLiteral String- | FormatField Bool -- Left justified ?- (Maybe Int) -- Min width- (Maybe Int) -- Max width- Field -- Field- deriving (Show, Eq)--formatValue :: Bool -> Maybe Int -> Maybe Int -> String -> String-formatValue leftJustified min max value = printf formatS value- where- l = if leftJustified then "-" else ""- min' = maybe "" show min- max' = maybe "" (\i -> "." ++ (show i)) max- formatS = "%" ++ l ++ min' ++ max' ++ "s"--parseFormatString :: String -> Either String [FormatString]-parseFormatString input = case (runParser formatStrings () "(unknown)") input of- Left y -> Left $ show y- Right x -> Right x--{--Parsers--}--field :: GenParser Char st Field-field = do- try (string "account" >> return Account)- <|> try (string "depth_spacer" >> return DepthSpacer)- <|> try (string "date" >> return Description)- <|> try (string "description" >> return Description)- <|> try (string "total" >> return Total)- <|> try (many1 digit >>= (\s -> return $ FieldNo $ read s))--formatField :: GenParser Char st FormatString-formatField = do- char '%'- leftJustified <- optionMaybe (char '-')- minWidth <- optionMaybe (many1 $ digit)- maxWidth <- optionMaybe (do char '.'; many1 $ digit) -- TODO: Can this be (char '1') *> (many1 digit)- char '('- f <- field- char ')'- return $ FormatField (isJust leftJustified) (parseDec minWidth) (parseDec maxWidth) f- where- parseDec s = case s of- Just text -> Just m where ((m,_):_) = readDec text- _ -> Nothing--formatLiteral :: GenParser Char st FormatString-formatLiteral = do- s <- many1 c- return $ FormatLiteral s- where- isPrintableButNotPercentage x = isPrint x && (not $ x == '%')- c = (satisfy isPrintableButNotPercentage <?> "printable character")- <|> try (string "%%" >> return '%')--formatString :: GenParser Char st FormatString-formatString =- formatField- <|> formatLiteral--formatStrings :: GenParser Char st [FormatString]-formatStrings = many formatString--testFormat :: FormatString -> String -> String -> Assertion-testFormat fs value expected = assertEqual name expected actual- where- (name, actual) = case fs of- FormatLiteral l -> ("literal", formatValue False Nothing Nothing l)- FormatField leftJustify min max _ -> ("field", formatValue leftJustify min max value)--testParser :: String -> [FormatString] -> Assertion-testParser s expected = case (parseFormatString s) of- Left error -> assertFailure $ show error- Right actual -> assertEqual ("Input: " ++ s) expected actual--tests = test [ formattingTests ++ parserTests ]--formattingTests = [- testFormat (FormatLiteral " ") "" " "- , testFormat (FormatField False Nothing Nothing Description) "description" "description"- , testFormat (FormatField False (Just 20) Nothing Description) "description" " description"- , testFormat (FormatField False Nothing (Just 20) Description) "description" "description"- , testFormat (FormatField True Nothing (Just 20) Description) "description" "description"- , testFormat (FormatField True (Just 20) Nothing Description) "description" "description "- , testFormat (FormatField True (Just 20) (Just 20) Description) "description" "description "- , testFormat (FormatField True Nothing (Just 3) Description) "description" "des"- ]--parserTests = [- testParser "" []- , testParser "D" [FormatLiteral "D"]- , testParser "%(date)" [FormatField False Nothing Nothing Description]- , testParser "%(total)" [FormatField False Nothing Nothing Total]- , testParser "Hello %(date)!" [FormatLiteral "Hello ", FormatField False Nothing Nothing Description, FormatLiteral "!"]- , testParser "%-(date)" [FormatField True Nothing Nothing Description]- , testParser "%20(date)" [FormatField False (Just 20) Nothing Description]- , testParser "%.10(date)" [FormatField False Nothing (Just 10) Description]- , testParser "%20.10(date)" [FormatField False (Just 20) (Just 10) Description]- , testParser "%20(account) %.10(total)\n" [ FormatField False (Just 20) Nothing Account- , FormatLiteral " "- , FormatField False Nothing (Just 10) Total- , FormatLiteral "\n"- ]- ]
+ Hledger/Cli/GitInfo.hs view
@@ -0,0 +1,17 @@+{-# LANGUAGE TemplateHaskell #-}+{-|+The git info (commit hash, date..) of the source being built, if available,+for the version strings of hledger, hledger-ui and hledger-web.++This is the only git lookup at compile time. Since a git change (commit, amend,+switch, or even staging) forces it to be recompiled, it is kept in this small module.+And NOINLINE keeps the value out of this module's interface, so that the modules+using it are not recompiled too; only the executables need to be relinked.+-}+module Hledger.Cli.GitInfo (gitInfo) where++import GitHash (GitInfo, tGitInfoCwdTry)++gitInfo :: Either String GitInfo+gitInfo = $$tGitInfoCwdTry+{-# NOINLINE gitInfo #-}
− Hledger/Cli/Histogram.hs
@@ -1,53 +0,0 @@-{-| --Print a histogram report.---}--module Hledger.Cli.Histogram-where-import Data.List-import Data.Maybe-import Data.Ord-import Text.Printf--import Hledger.Cli.Options-import Hledger.Data-import Hledger.Reports-import Prelude hiding (putStr)-import Hledger.Utils.UTF8 (putStr)---barchar = '*'---- | Print a histogram of some statistic per reporting interval, such as--- number of postings per day.-histogram :: CliOpts -> Journal -> IO ()-histogram CliOpts{reportopts_=reportopts_} j = do- d <- getCurrentDay- putStr $ showHistogram reportopts_ (optsToFilterSpec reportopts_ d) j--showHistogram :: ReportOpts -> FilterSpec -> Journal -> String-showHistogram opts filterspec j = concatMap (printDayWith countBar) spanps- where- i = intervalFromOpts opts- interval | i == NoInterval = Days 1- | otherwise = i- span = datespan filterspec `orDatesFrom` journalDateSpan j- spans = filter (DateSpan Nothing Nothing /=) $ splitSpan interval span- spanps = [(s, filter (isPostingInDateSpan s) ps) | s <- spans]- -- same as Register- -- should count transactions, not postings ?- ps = sortBy (comparing postingDate) $ filterempties $ filter matchapats $ filterdepth $ journalPostings j- filterempties- | empty_ opts = id- | otherwise = filter (not . isZeroMixedAmount . pamount)- matchapats = matchpats apats . paccount- apats = acctpats filterspec- filterdepth | interval == NoInterval = filter (\p -> accountNameLevel (paccount p) <= depth)- | otherwise = id- depth = fromMaybe 99999 $ depth_ opts--printDayWith f (DateSpan b _, ts) = printf "%s %s\n" (show $ fromJust b) (f ts)--countBar ps = replicate (length ps) barchar
− Hledger/Cli/Main.hs
@@ -1,114 +0,0 @@-{-|-hledger - a ledger-compatible accounting tool.-Copyright (c) 2007-2011 Simon Michael <simon@joyful.com>-Released under GPL version 3 or later.--hledger is a partial haskell clone of John Wiegley's "ledger". It-generates ledger-compatible register & balance reports from a plain text-journal, and demonstrates a functional implementation of ledger.-For more information, see http:\/\/hledger.org .--This module provides the main function for the hledger command-line-executable. It is exposed here so that it can be imported by eg benchmark-scripts.--You can use the command line:--> $ hledger --help--or ghci:--> $ ghci hledger-> > j <- readJournalFile "data/sample.journal"-> > register [] ["income","expenses"] j-> 2008/01/01 income income:salary $-1 $-1-> 2008/06/01 gift income:gifts $-1 $-2-> 2008/06/03 eat & shop expenses:food $1 $-1-> expenses:supplies $1 0-> > balance [Depth "1"] [] l-> $-1 assets-> $2 expenses-> $-2 income-> $1 liabilities-> > l <- myLedger--See "Hledger.Data.Ledger" for more examples.---}--module Hledger.Cli.Main where--import Control.Monad-import Data.List-import Safe-import System.Environment-import System.Exit-import System.Process-import Text.Printf--import Hledger (ensureJournalFile)-import Hledger.Cli.Add-import Hledger.Cli.Balance-import Hledger.Cli.Convert-import Hledger.Cli.Histogram-import Hledger.Cli.Print-import Hledger.Cli.Register-import Hledger.Cli.Stats-import Hledger.Cli.Options-import Hledger.Cli.Tests-import Hledger.Cli.Utils-import Hledger.Cli.Version-import Hledger.Utils--main :: IO ()-main = do- args <- getArgs- addons <- getHledgerAddonCommands- opts <- getHledgerCliOpts addons- when (debug_ opts) $ printf "%s\n" progversion >> printf "opts: %s\n" (show opts)- run' opts addons args- where- run' opts@CliOpts{command_=cmd} addons args- -- delicate, add tests before changing (eg --version, ADDONCMD --version, INTERNALCMD --version)- | (null matchedaddon) && "version" `in_` (rawopts_ opts) = putStrLn progversion- | (null matchedaddon) && "binary-filename" `in_` (rawopts_ opts) = putStrLn $ binaryfilename progname- | null cmd = putStr $ showModeHelp mainmode'- | cmd `isPrefixOf` "add" = showModeHelpOr addmode $ journalFilePathFromOpts opts >>= ensureJournalFile >> withJournalDo opts add- | cmd `isPrefixOf` "convert" = showModeHelpOr convertmode $ convert opts- | cmd `isPrefixOf` "test" = showModeHelpOr testmode $ runtests opts- | any (cmd `isPrefixOf`) ["accounts","balance"] = showModeHelpOr accountsmode $ withJournalDo opts balance- | any (cmd `isPrefixOf`) ["entries","print"] = showModeHelpOr entriesmode $ withJournalDo opts print'- | any (cmd `isPrefixOf`) ["postings","register"] = showModeHelpOr postingsmode $ withJournalDo opts register- | any (cmd `isPrefixOf`) ["activity","histogram"] = showModeHelpOr activitymode $ withJournalDo opts histogram- | cmd `isPrefixOf` "stats" = showModeHelpOr statsmode $ withJournalDo opts stats- | not (null matchedaddon) = do- when (debug_ opts) $ printf "running %s\n" shellcmd- system shellcmd >>= exitWith- | otherwise = optserror ("command "++cmd++" is not recognized") >> exitFailure- where- mainmode' = mainmode addons- showModeHelpOr mode f | "help" `in_` (rawopts_ opts) = putStr $ showModeHelp mode- | otherwise = f- matchedaddon | null cmd = ""- | otherwise = headDef "" $ filter (cmd `isPrefixOf`) addons- shellcmd = printf "%s-%s %s" progname matchedaddon (unwords' subcmdargs)- subcmdargs = args1 ++ drop 1 args2 where (args1,args2) = break (== cmd) $ filter (/="--") args--{- tests:--hledger -> main help-hledger --help -> main help-hledger --help command -> command help-hledger command --help -> command help-hledger badcommand -> unrecognized command, try --help (non-zero exit)-hledger badcommand --help -> main help-hledger --help badcommand -> main help-hledger --mainflag command -> works-hledger command --mainflag -> works-hledger command --commandflag -> works-hledger command --mainflag --commandflag -> works-XX hledger --mainflag command --commandflag -> works-XX hledger --commandflag command -> works-XX hledger --commandflag command --mainflag -> works---}
− Hledger/Cli/Options.hs
@@ -1,452 +0,0 @@-{-|--Command-line options for the hledger program, and option-parsing utilities.---}--module Hledger.Cli.Options-where-import Data.List-import Data.List.Split-import Data.Maybe-import Data.Time.Calendar-import Safe-import System.Console.CmdArgs-import System.Console.CmdArgs.Explicit-import System.Console.CmdArgs.Text-import System.Directory-import System.Environment-import Test.HUnit-import Text.ParserCombinators.Parsec-import Text.Printf--import Hledger-import Hledger.Cli.Format as Format-import Hledger.Cli.Version---progname = "hledger"-progversion = progversionstr progname---- 1. cmdargs mode and flag definitions, for the main and subcommand modes.--- Flag values are parsed initially to simple RawOpts to permit reuse.--type RawOpts = [(String,String)]--defmode :: Mode RawOpts-defmode = Mode {- modeNames = []- ,modeHelp = ""- ,modeHelpSuffix = []- ,modeValue = []- ,modeCheck = Right- ,modeReform = const Nothing- ,modeGroupFlags = toGroup []- ,modeArgs = ([], Nothing)- ,modeGroupModes = toGroup []- }--mainmode addons = defmode {- modeNames = [progname]- ,modeHelp = "run the specified hledger command. hledger COMMAND --help for more detail. \nIn general, COMMAND should precede OPTIONS."- ,modeHelpSuffix = [""]- ,modeGroupFlags = Group {- groupUnnamed = helpflags- ,groupHidden = [flagNone ["binary-filename"] (setboolopt "binary-filename") "show the download filename for this executable, and exit"]- ++ fileflags -- quietly permit these flags before COMMAND as well- ,groupNamed = []- }- ,modeArgs = ([], Just mainargsflag)- ,modeGroupModes = Group {- groupUnnamed = [- ]- ,groupHidden = [- ]- ,groupNamed = [- ("Misc commands", [- addmode- ,convertmode- ,testmode- ])- ,("\nReport commands", [- accountsmode- ,entriesmode- ,postingsmode- -- ,transactionsmode- ,activitymode- ,statsmode- ])- ]- ++ case addons of [] -> []- cs -> [("\nAdd-on commands found", map addonmode cs)]- }- }--addonmode name = defmode {- modeNames = [name]- ,modeHelp = printf "[-- OPTIONS] run the %s-%s program" progname name- ,modeValue=[("command",name)]- ,modeGroupFlags = Group {- groupUnnamed = []- ,groupHidden = []- ,groupNamed = [(generalflagstitle, generalflags1)]- }- ,modeArgs = ([], Just addonargsflag)- }--help_postscript = [- -- "DATES can be Y/M/D or smart dates like \"last month\"."- -- ,"PATTERNS are regular"- -- ,"expressions which filter by account name. Prefix a pattern with desc: to"- -- ,"filter by transaction description instead, prefix with not: to negate it."- -- ,"When using both, not: comes last."- ]--generalflagstitle = "\nGeneral flags"-generalflags1 = fileflags ++ reportflags ++ helpflags-generalflags2 = fileflags ++ helpflags-generalflags3 = helpflags--fileflags = [- flagReq ["file","f"] (\s opts -> Right $ setopt "file" s opts) "FILE" "use a different journal file; - means stdin"- ,flagReq ["alias"] (\s opts -> Right $ setopt "alias" s opts) "ACCT=ALIAS" "display ACCT's name as ALIAS in reports"- ]--reportflags = [- flagReq ["begin","b"] (\s opts -> Right $ setopt "begin" s opts) "DATE" "report on transactions on or after this date"- ,flagReq ["end","e"] (\s opts -> Right $ setopt "end" s opts) "DATE" "report on transactions before this date"- ,flagReq ["period","p"] (\s opts -> Right $ setopt "period" s opts) "PERIODEXP" "report on transactions during the specified period and/or with the specified reporting interval"- ,flagNone ["daily","D"] (\opts -> setboolopt "daily" opts) "report by day"- ,flagNone ["weekly","W"] (\opts -> setboolopt "weekly" opts) "report by week"- ,flagNone ["monthly","M"] (\opts -> setboolopt "monthly" opts) "report by month"- ,flagNone ["quarterly","Q"] (\opts -> setboolopt "quarterly" opts) "report by quarter"- ,flagNone ["yearly","Y"] (\opts -> setboolopt "yearly" opts) "report by year"- ,flagNone ["cleared","C"] (\opts -> setboolopt "cleared" opts) "report only on cleared transactions"- ,flagNone ["uncleared","U"] (\opts -> setboolopt "uncleared" opts) "report only on uncleared transactions"- ,flagNone ["cost","B"] (\opts -> setboolopt "cost" opts) "report cost of commodities"- ,flagReq ["depth"] (\s opts -> Right $ setopt "depth" s opts) "N" "hide accounts/transactions deeper than this"- ,flagReq ["display","d"] (\s opts -> Right $ setopt "display" s opts) "DISPLAYEXP" "show only transactions matching the expression, which is 'dOP[DATE]' where OP is <, <=, =, >=, >"- ,flagNone ["effective"] (\opts -> setboolopt "effective" opts) "use transactions' effective dates, if any"- ,flagNone ["empty","E"] (\opts -> setboolopt "empty" opts) "show empty/zero things which are normally elided"- ,flagNone ["real","R"] (\opts -> setboolopt "real" opts) "report only on real (non-virtual) transactions"- ]--helpflags = [- flagHelpSimple (setboolopt "help")- ,flagNone ["debug"] (setboolopt "debug") "Show extra debug output"- ,flagVersion (setboolopt "version")- ]--mainargsflag = flagArg (\s opts -> Right $ setopt "args" s opts) ""-commandargsflag = flagArg (\s opts -> Right $ setopt "args" s opts) "[PATTERNS]"-addonargsflag = flagArg (\s opts -> Right $ setopt "args" s opts) "[ARGS]"--commandmode names = defmode {modeNames=names, modeValue=[("command",headDef "" names)]}--addmode = (commandmode ["add"]) {- modeHelp = "prompt for new transactions and append them to the journal"- ,modeHelpSuffix = ["Defaults come from previous similar transactions; use query patterns to restrict these."]- ,modeArgs = ([], Just commandargsflag)- ,modeGroupFlags = Group {- groupUnnamed = [- flagNone ["no-new-accounts"] (\opts -> setboolopt "no-new-accounts" opts) "don't allow creating new accounts"- ]- ,groupHidden = []- ,groupNamed = [(generalflagstitle, generalflags2)]- }- }--convertmode = (commandmode ["convert"]) {- modeValue = [("command","convert")]- ,modeHelp = "show the specified CSV file as hledger journal entries"- ,modeArgs = ([], Just $ flagArg (\s opts -> Right $ setopt "args" s opts) "[CSVFILE]")- ,modeGroupFlags = Group {- groupUnnamed = [- flagReq ["rules-file"] (\s opts -> Right $ setopt "rules-file" s opts) "FILE" "rules file to use (default: CSVFILE.rules)"- ]- ,groupHidden = []- ,groupNamed = [(generalflagstitle, generalflags3)]- }- }--testmode = (commandmode ["test"]) {- modeHelp = "run self-tests, or just the ones matching REGEXPS"- ,modeArgs = ([], Just $ flagArg (\s opts -> Right $ setopt "args" s opts) "[REGEXPS]")- ,modeGroupFlags = Group {- groupUnnamed = []- ,groupHidden = []- ,groupNamed = [(generalflagstitle, generalflags3)]- }- }--accountsmode = (commandmode ["balance","accounts"]) {- modeHelp = "(or accounts) show matched accounts and their balances"- ,modeArgs = ([], Just commandargsflag)- ,modeGroupFlags = Group {- groupUnnamed = [- flagNone ["flat"] (\opts -> setboolopt "flat" opts) "show full account names, unindented"- ,flagReq ["drop"] (\s opts -> Right $ setopt "drop" s opts) "N" "with --flat, omit this many leading account name components"- ,flagReq ["format"] (\s opts -> Right $ setopt "format" s opts) "FORMATSTR" "use this custom line format"- ,flagNone ["no-elide"] (\opts -> setboolopt "no-elide" opts) "no eliding at all, stronger than --empty"- ,flagNone ["no-total"] (\opts -> setboolopt "no-total" opts) "don't show the final total"- ]- ,groupHidden = []- ,groupNamed = [(generalflagstitle, generalflags1)]- }- }--entriesmode = (commandmode ["print","entries"]) {- modeHelp = "(or entries) show matched journal entries"- ,modeArgs = ([], Just commandargsflag)- ,modeGroupFlags = Group {- groupUnnamed = []- ,groupHidden = []- ,groupNamed = [(generalflagstitle, generalflags1)]- }- }--postingsmode = (commandmode ["register","postings"]) {- modeHelp = "(or postings) show matched postings and running total"- ,modeArgs = ([], Just commandargsflag)- ,modeGroupFlags = Group {- groupUnnamed = []- ,groupHidden = []- ,groupNamed = [(generalflagstitle, generalflags1)]- }- }--transactionsmode = (commandmode ["transactions"]) {- modeHelp = "show matched transactions and balance in some account(s)"- ,modeArgs = ([], Just commandargsflag)- ,modeGroupFlags = Group {- groupUnnamed = []- ,groupHidden = []- ,groupNamed = [(generalflagstitle, generalflags1)]- }- }--activitymode = (commandmode ["activity","histogram"]) {- modeHelp = "show a barchart of transactions per interval"- ,modeHelpSuffix = ["The default interval is daily."]- ,modeArgs = ([], Just commandargsflag)- ,modeGroupFlags = Group {- groupUnnamed = []- ,groupHidden = []- ,groupNamed = [(generalflagstitle, generalflags1)]- }- }--statsmode = (commandmode ["stats"]) {- modeHelp = "show quick statistics for a journal (or part of it)"- ,modeArgs = ([], Just commandargsflag)- ,modeGroupFlags = Group {- groupUnnamed = []- ,groupHidden = []- ,groupNamed = [(generalflagstitle, generalflags1)]- }- }---- 2. ADT holding options used in this package and above, parsed from RawOpts.--- This represents the command-line options that were provided, with all--- parsing completed, but before adding defaults or derived values (XXX add)---- cli options, used in hledger and above-data CliOpts = CliOpts {- rawopts_ :: RawOpts- ,command_ :: String- ,file_ :: Maybe FilePath- ,alias_ :: [String]- ,debug_ :: Bool- ,no_new_accounts_ :: Bool -- add- ,rules_file_ :: Maybe FilePath -- convert- ,reportopts_ :: ReportOpts- } deriving (Show)--defcliopts = CliOpts- def- def- def- def- def- def- def- def--instance Default CliOpts where def = defcliopts---- | Parse raw option string values to the desired final data types.--- Any relative smart dates will be converted to fixed dates based on--- today's date. Parsing failures will raise an error.-toCliOpts :: RawOpts -> IO CliOpts-toCliOpts rawopts = do- d <- getCurrentDay- return defcliopts {- rawopts_ = rawopts- ,command_ = stringopt "command" rawopts- ,file_ = maybestringopt "file" rawopts- ,alias_ = listofstringopt "alias" rawopts- ,debug_ = boolopt "debug" rawopts- ,no_new_accounts_ = boolopt "no-new-accounts" rawopts -- add- ,rules_file_ = maybestringopt "rules-file" rawopts -- convert- ,reportopts_ = defreportopts {- begin_ = maybesmartdateopt d "begin" rawopts- ,end_ = maybesmartdateopt d "end" rawopts- ,period_ = maybeperiodopt d rawopts- ,cleared_ = boolopt "cleared" rawopts- ,uncleared_ = boolopt "uncleared" rawopts- ,cost_ = boolopt "cost" rawopts- ,depth_ = maybeintopt "depth" rawopts- ,display_ = maybedisplayopt d rawopts- ,effective_ = boolopt "effective" rawopts- ,empty_ = boolopt "empty" rawopts- ,no_elide_ = boolopt "no-elide" rawopts- ,real_ = boolopt "real" rawopts- ,flat_ = boolopt "flat" rawopts -- balance- ,drop_ = intopt "drop" rawopts -- balance- ,no_total_ = boolopt "no-total" rawopts -- balance- ,daily_ = boolopt "daily" rawopts- ,weekly_ = boolopt "weekly" rawopts- ,monthly_ = boolopt "monthly" rawopts- ,quarterly_ = boolopt "quarterly" rawopts- ,yearly_ = boolopt "yearly" rawopts- ,format_ = maybestringopt "format" rawopts- ,patterns_ = listofstringopt "args" rawopts- }- }---- | Get all command-line options, specifying any extra commands that are allowed, or fail on parse errors.-getHledgerCliOpts :: [String] -> IO CliOpts-getHledgerCliOpts addons = do- args <- getArgs- toCliOpts (decodeRawOpts $ processValue (mainmode addons) $ rearrangeForCmdArgs args) >>= checkCliOpts---- utils---- | Get the unique suffixes (without hledger-) of hledger-* executables--- found in the current user's PATH, or the empty list if there is any--- problem.-getHledgerAddonCommands :: IO [String]-getHledgerAddonCommands = map (drop (length progname + 1)) `fmap` getHledgerProgramsInPath---- | Get the unique names of hledger-* executables found in the current--- user's PATH, or the empty list if there is any problem.-getHledgerProgramsInPath :: IO [String]-getHledgerProgramsInPath = do- pathdirs <- splitOn ":" `fmap` getEnvSafe "PATH"- pathexes <- concat `fmap` mapM getDirectoryContentsSafe pathdirs- return $ nub $ sort $ filter (isRight . parsewith hledgerprog) pathexes- where- hledgerprog = string progname >> char '-' >> many1 (letter <|> char '-') >> eof--getEnvSafe v = getEnv v `catch` (\_ -> return "")-getDirectoryContentsSafe d = getDirectoryContents d `catch` (\_ -> return [])---- | Convert possibly encoded option values to regular unicode strings.-decodeRawOpts = map (\(name,val) -> (name, fromPlatformString val))---- A hacky workaround for http://code.google.com/p/ndmitchell/issues/detail?id=470 :--- we'd like to permit options before COMMAND as well as after it.--- Here we make sure at least -f FILE will be accepted in either position.-rearrangeForCmdArgs (fopt@('-':'f':_:_):cmd:rest) = cmd:fopt:rest-rearrangeForCmdArgs ("-f":fval:cmd:rest) = cmd:"-f":fval:rest-rearrangeForCmdArgs as = as--optserror = error' . (++ " (run with --help for usage)")--setopt name val = (++ [(name,singleQuoteIfNeeded val)])--setboolopt name = (++ [(name,"")])--in_ :: String -> RawOpts -> Bool-in_ name = isJust . lookup name--boolopt = in_--maybestringopt name = maybe Nothing (Just . stripquotes) . lookup name--stringopt name = fromMaybe "" . maybestringopt name--listofstringopt name rawopts = [stripquotes v | (n,v) <- rawopts, n==name]--maybeintopt :: String -> RawOpts -> Maybe Int-maybeintopt name rawopts =- let ms = maybestringopt name rawopts in- case ms of Nothing -> Nothing- Just s -> Just $ readDef (optserror $ "could not parse "++name++" number: "++s) s--intopt name = fromMaybe 0 . maybeintopt name--maybesmartdateopt :: Day -> String -> RawOpts -> Maybe Day-maybesmartdateopt d name rawopts =- case maybestringopt name rawopts of- Nothing -> Nothing- Just s -> either- (\e -> optserror $ "could not parse "++name++" date: "++show e)- Just- $ fixSmartDateStrEither' d s--maybedisplayopt :: Day -> RawOpts -> Maybe DisplayExp-maybedisplayopt d rawopts =- maybe Nothing (Just . regexReplaceBy "\\[.+?\\]" fixbracketeddatestr) $ maybestringopt "display" rawopts- where- fixbracketeddatestr "" = ""- fixbracketeddatestr s = "[" ++ fixSmartDateStr d (init $ tail s) ++ "]"--maybeperiodopt :: Day -> RawOpts -> Maybe (Interval,DateSpan)-maybeperiodopt d rawopts =- case maybestringopt "period" rawopts of- Nothing -> Nothing- Just s -> either- (\e -> optserror $ "could not parse period option: "++show e)- Just- $ parsePeriodExpr d s---- | Do final validation of processed opts, raising an error if there is trouble.-checkCliOpts :: CliOpts -> IO CliOpts -- or pure..-checkCliOpts opts@CliOpts{reportopts_=ropts} = do- case formatFromOpts ropts of- Left err -> optserror $ "could not parse format option: "++err- Right _ -> return ()- return opts---- | Parse any format option provided, possibly raising an error, or get--- the default value.-formatFromOpts :: ReportOpts -> Either String [FormatString]-formatFromOpts = maybe (Right defaultBalanceFormatString) parseFormatString . format_---- | Default line format for balance report: "%20(total) %2(depth_spacer)%-(account)"-defaultBalanceFormatString :: [FormatString]-defaultBalanceFormatString = [- FormatField False (Just 20) Nothing Total- , FormatLiteral " "- , FormatField True (Just 2) Nothing DepthSpacer- , FormatField True Nothing Nothing Format.Account- ]---- | Get the journal file path from options, an environment variable, or a default.--- If the path contains a literal tilde raise an error to avoid confusion.-journalFilePathFromOpts :: CliOpts -> IO String-journalFilePathFromOpts opts = do- f <- myJournalPath- return $ errorIfContainsTilde $ fromMaybe f $ file_ opts--errorIfContainsTilde s |'~' `elem` s = error' "unsupported literal ~ found in environment variable, please adjust"- | otherwise = s--aliasesFromOpts :: CliOpts -> [(AccountName,AccountName)]-aliasesFromOpts = map parseAlias . alias_- where- -- similar to ledgerAlias- parseAlias :: String -> (AccountName,AccountName)- parseAlias s = (accountNameWithoutPostingType $ strip orig- ,accountNameWithoutPostingType $ strip alias')- where- (orig, alias) = break (=='=') s- alias' = case alias of ('=':rest) -> rest- _ -> orig--showModeHelp = showText defaultWrap . helpText HelpFormatDefault--tests_Hledger_Cli_Options = TestList- [- ]
− Hledger/Cli/Print.hs
@@ -1,29 +0,0 @@-{-| --A ledger-compatible @print@ command.---}--module Hledger.Cli.Print (- print'- ,showTransactions-) where-import Data.List--import Hledger-import Prelude hiding (putStr)-import Hledger.Utils.UTF8 (putStr)-import Hledger.Cli.Options---- | Print journal transactions in standard format.-print' :: CliOpts -> Journal -> IO ()-print' CliOpts{reportopts_=ropts} j = do- d <- getCurrentDay- putStr $ showTransactions ropts (optsToFilterSpec ropts d) j--showTransactions :: ReportOpts -> FilterSpec -> Journal -> String-showTransactions opts fspec j = entriesReportAsText opts fspec $ entriesReport opts fspec j--entriesReportAsText :: ReportOpts -> FilterSpec -> EntriesReport -> String-entriesReportAsText _ _ items = concatMap showTransactionUnelided items-
− Hledger/Cli/Register.hs
@@ -1,64 +0,0 @@-{-| --A ledger-compatible @register@ command.---}--module Hledger.Cli.Register (- register- ,postingsReportAsText- ,showPostingWithBalanceForVty- ,tests_Hledger_Cli_Register-) where--import Data.List-import Data.Maybe-import Test.HUnit-import Text.Printf--import Hledger-import Prelude hiding (putStr)-import Hledger.Utils.UTF8 (putStr)-import Hledger.Cli.Options----- | Print a (posting) register report.-register :: CliOpts -> Journal -> IO ()-register CliOpts{reportopts_=ropts} j = do- d <- getCurrentDay- putStr $ postingsReportAsText ropts $ postingsReport ropts (optsToFilterSpec ropts d) j---- | Render a register report as plain text suitable for console output.-postingsReportAsText :: ReportOpts -> PostingsReport -> String-postingsReportAsText opts = unlines . map (postingsReportItemAsText opts) . snd---- | Render one register report line item as plain text. Eg:--- @--- date (10) description (20) account (22) amount (11) balance (12)--- DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaaaaa AAAAAAAAAAA AAAAAAAAAAAA--- ^ displayed for first postings^--- only, otherwise blank--- @-postingsReportItemAsText :: ReportOpts -> PostingsReportItem -> String-postingsReportItemAsText _ (dd, p, b) = concatTopPadded [datedesc, pstr, " ", bal]- where- datedesc = case dd of Nothing -> replicate datedescwidth ' '- Just (da, de) -> printf "%s %s " date desc- where- date = showDate da- desc = printf ("%-"++(show descwidth)++"s") $ elideRight descwidth de :: String- where- descwidth = datedescwidth - datewidth - 2- datedescwidth = 32- datewidth = 10- pstr = showPostingForRegister p- bal = padleft 12 (showMixedAmountWithoutPrice b)---- XXX-showPostingWithBalanceForVty showtxninfo p b = postingsReportItemAsText defreportopts $ mkpostingsReportItem showtxninfo p b--tests_Hledger_Cli_Register :: Test-tests_Hledger_Cli_Register = TestList- [-- ]
+ Hledger/Cli/Script.hs view
@@ -0,0 +1,56 @@+{-|+A convenient module to import in hledger scripts, +aiming to provide the most useful imports and reduce boilerplate.+|-}++{-# LANGUAGE CPP #-}+{-# LANGUAGE PackageImports #-}++module Hledger.Cli.Script +( module M+) +where++import Control.Applicative as M+import Control.Concurrent as M+import Control.Monad as M+import Data.Char as M+import Data.Either as M++import Data.Functor as M+#if MIN_VERSION_base(4,19,0)+ hiding (unzip)+#endif+-- import Data.Functor as M (Functor, fmap, (<$), ($>), (<$>), (<&>)) -- or without CPP ? redundant import warning++import Data.List as M+import Data.Maybe as M+import Data.Ord as M+-- import Data.String.QQ (s) -- https://github.com/audreyt/string-qq/pull/3+import Data.Time as M+import Text.Printf as M hiding (formatString)+import "text" Data.Text as M (Text, pack, unpack)+ -- can't re-export much of Data.Text & Data.Text.IO, they need to be qualified+import Safe as M hiding (at)+-- import System.Console.CmdArgs.Explicit qualified as M+import System.Directory as M+import System.Environment as M+import System.Exit as M+import System.FilePath as M+import System.IO as M+import System.IO.Error as M+import System.Process as M++-- import Hledger.Cli as M hiding (main)+import Hledger.Cli as M (argsToCliOpts)+import Hledger.Cli.CliOptions as M+import Hledger.Cli.Commands as M+import Hledger.Cli.DocFiles as M+import Hledger.Cli.Utils as M+import Hledger.Cli.Version as M+import Hledger.Cli.CompoundBalanceCommand as M++import Hledger as M+import System.Console.CmdArgs.Explicit as M++-- import Hledger.Cli as M (argsToCliOpts)
− Hledger/Cli/Stats.hs
@@ -1,86 +0,0 @@-{-|--Print some statistics for the journal.---}--module Hledger.Cli.Stats-where-import Data.List-import Data.Maybe-import Data.Ord-import Data.Time.Calendar-import Text.Printf-import qualified Data.Map as Map--import Hledger-import Hledger.Cli.Options-import Prelude hiding (putStr)-import Hledger.Utils.UTF8 (putStr)----- like Register.summarisePostings--- | Print various statistics for the journal.-stats :: CliOpts -> Journal -> IO ()-stats CliOpts{reportopts_=reportopts_} j = do- d <- getCurrentDay- let filterspec = optsToFilterSpec reportopts_ d- l = journalToLedger filterspec j- reportspan = (ledgerDateSpan l) `orDatesFrom` (datespan filterspec)- intervalspans = splitSpan (intervalFromOpts reportopts_) reportspan- showstats = showLedgerStats l d- s = intercalate "\n" $ map showstats intervalspans- putStr s--showLedgerStats :: Ledger -> Day -> DateSpan -> String-showLedgerStats l today span =- unlines (map (uncurry (printf fmt)) stats)- where- fmt = "%-" ++ show w1 ++ "s: %-" ++ show w2 ++ "s"- w1 = maximum $ map (length . fst) stats- w2 = maximum $ map (length . show . snd) stats- stats = [- ("Journal file", journalFilePath $ journal l)- ,("Transactions span", printf "%s to %s (%d days)" (start span) (end span) days)- ,("Last transaction", maybe "none" show lastdate ++ showelapsed lastelapsed)- ,("Transactions", printf "%d (%0.1f per day)" tnum txnrate)- ,("Transactions last 30 days", printf "%d (%0.1f per day)" tnum30 txnrate30)- ,("Transactions last 7 days", printf "%d (%0.1f per day)" tnum7 txnrate7)- ,("Payees/descriptions", show $ length $ nub $ map tdescription ts)- ,("Accounts", printf "%d (depth %d)" acctnum acctdepth)- ,("Commodities", printf "%s (%s)" (show $ length cs) (intercalate ", " cs))- -- Transactions this month : %(monthtxns)s (last month in the same period: %(lastmonthtxns)s)- -- Uncleared transactions : %(uncleared)s- -- Days since reconciliation : %(reconcileelapsed)s- -- Days since last transaction : %(recentelapsed)s- ]- where- ts = sortBy (comparing tdate) $ filter (spanContainsDate span . tdate) $ jtxns $ journal l- as = nub $ map paccount $ concatMap tpostings ts- cs = Map.keys $ canonicaliseCommodities $ nub $ map commodity $ concatMap amounts $ map pamount $ concatMap tpostings ts- lastdate | null ts = Nothing- | otherwise = Just $ tdate $ last ts- lastelapsed = maybe Nothing (Just . diffDays today) lastdate- showelapsed Nothing = ""- showelapsed (Just days) = printf " (%d %s)" days' direction- where days' = abs days- direction | days >= 0 = "days ago"- | otherwise = "days from now"- tnum = length ts- start (DateSpan (Just d) _) = show d- start _ = ""- end (DateSpan _ (Just d)) = show d- end _ = ""- days = fromMaybe 0 $ daysInSpan span- txnrate | days==0 = 0- | otherwise = fromIntegral tnum / fromIntegral days :: Double- tnum30 = length $ filter withinlast30 ts- withinlast30 t = d >= addDays (-30) today && (d<=today) where d = tdate t- txnrate30 = fromIntegral tnum30 / 30 :: Double- tnum7 = length $ filter withinlast7 ts- withinlast7 t = d >= addDays (-7) today && (d<=today) where d = tdate t- txnrate7 = fromIntegral tnum7 / 7 :: Double- acctnum = length as- acctdepth | null as = 0- | otherwise = maximum $ map accountNameLevel as-
− Hledger/Cli/Tests.hs
@@ -1,58 +0,0 @@-{- |--This module contains hledger's unit tests. These are built in to hledger,-and can be run at any time by doing @hledger test@ (or, with a few more-options, by doing @make unittest@ in the hledger source tree.)--Other kinds of tests:--hledger's functional tests are a set of shell/command-line tests defined-by .test files in the tests\/ subdirectory. These can be run by doing-@make functest@ in the hledger source tree.--hledger's doctests are shell commands with expected output in literal-blocks in the haddock documentation, run by doing @make doctest@ in the-hledger source tree. They are hardly used, but here is an example:--@-$ bin\/hledger -f data\/sample.journal balance o- $1 expenses:food- $-2 income- $-1 gifts- $-1 salary---------------------- $-1-@---}--module Hledger.Cli.Tests-where-import Control.Monad-import System.Exit-import Test.HUnit--import Hledger-import Hledger.Cli----- | Run unit tests and exit with success or failure.-runtests :: CliOpts -> IO ()-runtests opts = do- (hunitcounts,_) <- runtests' opts- if errors hunitcounts > 0 || (failures hunitcounts > 0)- then exitFailure- else exitWith ExitSuccess---- | Run unit tests and exit on failure.-runTestsOrExit :: CliOpts -> IO ()-runTestsOrExit opts = do- (hunitcounts,_) <- runtests' opts- when (errors hunitcounts > 0 || (failures hunitcounts > 0)) $ exitFailure--runtests' :: Num b => CliOpts -> IO (Counts, b)-runtests' opts = liftM (flip (,) 0) $ runTestTT ts- where- ts = TestList $ filter matchname $ tflatten tests_Hledger_Cli -- show flat test names- -- ts = tfilter matchname $ TestList tests -- show hierarchical test names- matchname = matchpats (patterns_ $ reportopts_ opts) . tname
Hledger/Cli/Utils.hs view
@@ -1,3 +1,5 @@+{-# LANGUAGE OverloadedStrings #-}+{-# LANGUAGE ScopedTypeVariables #-} {-| Utilities for top-level modules and ghci. See also Hledger.Read and@@ -7,147 +9,466 @@ module Hledger.Cli.Utils (+ unsupportedOutputFormatError,+ withJournal, withJournalDo,- readJournal',+ withPossibleJournal,+ writeOutput,+ writeOutputLazyText,+ warnIfLargeMultiPeriodReport,+ withTitle,+ writeOutputWithTitle,+ journalTransform,+ journalPrepareLotDetail, journalReload,+ journalCheckChange, journalReloadIfChanged, journalFileIsNewer,- journalSpecifiedFileIsNewer,- fileModificationTime,+ maybeFileModificationTime, openBrowserOn, writeFileWithBackup, writeFileWithBackupIfChanged,- readFileStrictly,- Test(TestList),+ journalSimilarTransaction,+ postingsOrTransactionsReportAsText,+ tests_Cli_Utils, ) where-import Control.Exception++import Control.Exception (IOException, evaluate, try)+import Control.Monad.Except (ExceptT)+import Control.Monad.IO.Class (liftIO) import Data.List+import Data.List.NonEmpty qualified as NE (head, toList)+import Data.Map qualified as M import Data.Maybe-import Safe (readMay)+import Data.Set qualified as S+import Data.Text qualified as T+import Data.Text.IO qualified as T+import Data.Text.Lazy qualified as TL+import Data.Text.Lazy.Builder qualified as TB+import Data.Text.Lazy.IO qualified as TL+import Data.Time (Day)+import Data.Time.Clock.POSIX (POSIXTime, utcTimeToPOSIXSeconds)+import Lens.Micro ((^.))+import Safe (readMay, headMay) import System.Console.CmdArgs-import System.Directory (getModificationTime, getDirectoryContents, copyFile)+import System.Directory (canonicalizePath, getModificationTime, getDirectoryContents, copyFile, createDirectoryIfMissing, doesFileExist, getXdgDirectory, renameFile, XdgDirectory(..)) import System.Exit import System.FilePath ((</>), splitFileName, takeDirectory) import System.Info (os)+import System.IO (hClose, openTempFile, hPutStrLn, stderr) import System.Process (readProcessWithExitCode)-import System.Time (ClockTime, getClockTime, diffClockTimes, TimeDiff(TimeDiff))-import Test.HUnit import Text.Printf+import Text.Regex.TDFA ((=~))+import Web.Browser (openBrowser) -import Hledger.Cli.Options+import Hledger.Cli.CliOptions+import Hledger.Cli.Anon import Hledger.Data import Hledger.Read+import Hledger.Reports import Hledger.Utils+import Control.Monad (when)+import Data.Functor ((<&>)) +-- | Standard error message for a bad output format specified with -O/-o.+-- If it looks like a file name with a known format's extension, it suggests -o.+unsupportedOutputFormatError :: String -> String+unsupportedOutputFormatError fmt =+ "Sorry, output format \""++fmt++"\" is unrecognised or not yet supported for this kind of report."+ ++ if '.' `elem` fmt && filePathExtension fmt `elem` outputFormats+ then "\nTo write to a file named " ++ fmt ++ ", use -o (--output-file), not -O (--output-format)."+ else "" --- | Parse the user's specified journal file and run a hledger command on--- it, or throw an error.-withJournalDo :: CliOpts -> (CliOpts -> Journal -> IO ()) -> IO ()-withJournalDo opts cmd = do+-- | If a multi-period report has an implausible number of periods (more than 10,000;+-- in practice this means a mistyped date in the journal, making the report span thousands of years),+-- print a warning on stderr before starting it, so the user can cancel (#1683).+-- Such a report can need a lot of memory (a balance report needs a column per period).+-- The periods are counted without building the report, in constant memory.+--+-- This is called explicitly by each command that runs such a report (balance, the compound+-- balance commands, stats, roi, activity), rather than living in the report code: the report functions+-- are pure, so warning from them would need unsafePerformIO or trace, with no guarantee the+-- message appears before the work starts. Doing it in the command's IO, before the report is+-- forced, keeps the ordering reliable. New multi-period report commands should call this too.+warnIfLargeMultiPeriodReport :: ReportSpec -> Journal -> IO ()+warnIfLargeMultiPeriodReport rspec@ReportSpec{_rsReportOpts=ropts} j =+ when (interval_ ropts /= NoInterval && nperiods > maxExpectedPeriods) $ warnIO $ printf+ ("this report has %d periods (%s), and may use a lot of memory.\n"+ <> "If not intended, press control-C now, and check for a mistyped date, or narrow the report.")+ nperiods (showDateSpan rspan)+ where+ (rspan, spans) = reportSpanLazy j rspec+ nperiods = length spans -- constant memory: the lazy spans are counted, not kept+ maxExpectedPeriods = 10000 :: Int++-- | Parse the user's specified journal file(s) as a Journal, maybe apply some+-- transformations according to options, and run a hledger command with it.+-- Or, throw an error.+--+-- Sets 'InputOpts._journaldir' on the iopts used for this read, so CSV+-- @source@/@archive@ rules find the journal's @data/@ directory. If the+-- callback subsequently performs another 'readJournalFile' / 'readJournalFiles'+-- call (eg in the @import@ command), it should apply 'inputOptsSetJournalDir'+-- to those iopts using the loaded journal — the local @opts.inputopts_@ does+-- not yet carry @_journaldir@ at the call site here.+withJournal :: CliOpts -> (Journal -> IO a) -> IO a+withJournal opts cmd = do -- We kludgily read the file before parsing to grab the full text, unless -- it's stdin, or it doesn't exist and we are adding. We read it strictly -- to let the add command work.- journalFilePathFromOpts opts >>= readJournalFile Nothing >>=- either error' (cmd opts . journalApplyAliases (aliasesFromOpts opts))+ journalpaths <- journalFilePathFromOpts opts+ let iopts = (inputopts_ opts){_journaldir = Just (takeDirectory (NE.head journalpaths))}+ ej <- runExceptT $ journalTransform opts <$> readJournalFiles iopts (NE.toList journalpaths)+ case ej of+ Left e -> error' e -- PARTIAL:+ Right j -> do+ maybeWarnUnknownValuationCommodity opts j+ cmd j --- -- | Get a journal from the given string and options, or throw an error.--- readJournalWithOpts :: CliOpts -> String -> IO Journal--- readJournalWithOpts opts s = readJournal Nothing s >>= either error' return+-- | Warn on stderr if -X/--value requests a valuation commodity for which+-- valuation will certainly have no effect: one appearing in no P directive+-- or cost (from which conversion prices could come) and in which no+-- amounts are already denominated, and which is not a commodity alias. Also suggest a journal commodity+-- equivalent under ISO 4217 currency code normalisation, if any+-- (eg $ for USD).+maybeWarnUnknownValuationCommodity :: CliOpts -> Journal -> IO ()+maybeWarnUnknownValuationCommodity opts j =+ case valuationTypeValuationCommodity =<< value_ (_rsReportOpts $ reportspec_ opts) of+ Just c+ | c `S.notMember` journalCommoditiesFromPriceDirectives j+ , c `S.notMember` journalCommoditiesFromTransactions j+ , c `notElem` concatMap commodityAliases (jdeclaredcommodities j) ->+ warnIO $ "no conversion prices to \"" <> T.unpack c <> "\" can be found." <> suggestion c+ _ -> return ()+ where+ suggestion c = case [s | s <- S.toList (journalCommodities j), s /= c, toCurrencyCode s == toCurrencyCode c] of+ (s:_) -> " Did you mean \"" <> T.unpack s <> "\" ?"+ [] -> "" --- | Get a journal from the given string, or throw an error.-readJournal' :: String -> IO Journal-readJournal' s = readJournal Nothing s >>= either error' return+{-# DEPRECATED withJournalDo "renamed, please use withJournal instead" #-}+withJournalDo = withJournal --- | Re-read a journal from its data file, or return an error string.-journalReload :: Journal -> IO (Either String Journal)-journalReload j = readJournalFile Nothing $ journalFilePath j+-- | Like withJournal, but if the first journal file does not exist, provides an empty+-- journal with that file path set. This is useful for commands like add and import+-- that need to work with a potentially non-existent first journal file,+-- while still reading all specified files (for completions, etc).+--+-- See 'withJournal' for the note about 'inputOptsSetJournalDir' and secondary reads.+withPossibleJournal :: CliOpts -> (Journal -> IO a) -> IO a+withPossibleJournal opts cmd = do+ journalpaths <- journalFilePathFromOptsNoDefault opts+ fs <- case journalpaths of+ Just paths -> return $ NE.toList paths+ Nothing -> (:[]) <$> defaultJournalPath+ let iopts = (inputopts_ opts){_journaldir = takeDirectory <$> headMay fs}+ j <- runExceptT $ journalTransform opts <$> readPossibleJournalFiles iopts fs+ either error' cmd j -- PARTIAL: --- | Re-read a journal from its data file mostly, only if the file has--- changed since last read (or if there is no file, ie data read from--- stdin). The provided options are mostly ignored. Return a journal or--- the error message while reading it, and a flag indicating whether it--- was re-read or not.-journalReloadIfChanged :: CliOpts -> Journal -> IO (Either String Journal, Bool)-journalReloadIfChanged _ j = do- let maybeChangedFilename f = do newer <- journalSpecifiedFileIsNewer j f+-- | Apply some journal transformations, if enabled by options, that should happen late.+-- These happen after parsing, finalising the journal, strict checks, and .latest filtering/updating,+-- but before report calculation. They are, in processing order:+-- --pivot, --anonymise error message, --obfuscate, and preparing lot detail+-- (converting to cost basis for -B or --gain, then, when --lots is off, collapsing it).+--+-- Why not do these in journalFinalise ?+-- That step is supposed to check the data's intrinsic correctness, regardless of view options;+-- whereas here we assume correctness and are just transforming the view (based only on InputOpts).+-- XXX But it's easy to forget to call this. Current callers include withJournal, journalReload, uiReload, withJournalCached.+journalTransform :: CliOpts -> Journal -> Journal+journalTransform opts =+ maybePivot opts+ <&> maybeWarnAboutAnon opts+ <&> maybeObfuscate opts+ <&> maybePrepareLotDetail opts++-- | Prepare lot detail for the report options (see 'journalPrepareLotDetail'),+-- collapsing it so reports show the user's original form. Collapsing is skipped+-- when --lots is set, or when --ignore-lots/-I is set (in which case leaf-@{...}@+-- accounts are treated as ordinary account names).+-- The holdings command gets the journal unchanged: it aggregates lots itself,+-- and needs their units unconverted even with -B.+maybePrepareLotDetail :: CliOpts -> Journal -> Journal+maybePrepareLotDetail opts+ | command_ opts == "holdings" = id+ | otherwise = journalPrepareLotDetail (_rsReportOpts $ reportspec_ opts) keeplots+ where+ rawopts = rawopts_ opts+ keeplots = boolopt "lots" rawopts+ || boolopt "ignore-lots" rawopts++-- | Prepare a journal's lot detail for reports with these options: convert lot+-- postings to their cost basis where -B or --gain needs it, then, unless+-- keeplots is true, collapse lot detail ('journalCollapseLotDetail').+-- hledger, hledger-ui, and hledger-web all display lots this way, so that+-- they report the same amounts.+journalPrepareLotDetail :: ReportOpts -> Bool -> Journal -> Journal+journalPrepareLotDetail ropts keeplots+ | keeplots = setCostsToBasisForGain+ | otherwise = journalCollapseLotDetail . setCostsToBasisForGain . convertFragmentsToCostBasis+ where+ -- With -B/--value=cost, when lot detail will be collapsed, convert the+ -- per-lot fragments of split postings (eg a disposal from several lots)+ -- to their cost basis now: collapsing merges them into one amount with an+ -- unspecified basis, after which the basis values would be lost. The later+ -- per-report cost conversion is then a no-op for these amounts.+ -- Other amounts are left for that per-report conversion, which comes after+ -- query matching, so that cur: and amt: still match their original+ -- commodity and quantity (as they do with -V/-X).+ convertFragmentsToCostBasis+ | conversionop_ ropts == Just ToCost = \j -> j{jtxns = map convertTxn $ jtxns j}+ | otherwise = id+ convertTxn t+ | any isfragment (tpostings t) = t{tpostings = mapMaybe (\p -> if isfragment p then postingToCost ToCost p else Just p) $ tpostings t}+ | otherwise = t+ isfragment = postingHasTag lotsplitPostingTagName+ -- With --gain, replace lot postings' transacted costs with their cost basis+ -- now, before lot detail is collapsed, for the same reason: the gain+ -- calculation subtracts cost from summed account balances, and summing+ -- merges amounts by commodity and transacted cost (dropping differing+ -- bases), so the basis is carried in the transacted cost, which sums+ -- correctly. Then gain is value minus cost basis for lot postings however+ -- their costs were written (@ or @@), as it already was for -B (#2751).+ setCostsToBasisForGain+ | balancecalc_ ropts == CalcGain = journalMapPostingAmounts (mapMixedAmount amountSetCostToBasis)+ | otherwise = id++-- | If the --pivot option is present, replace the journal's account names by specified other values.+maybePivot :: CliOpts -> Journal -> Journal+maybePivot opts =+ case maybestringopt "pivot" . rawopts_ $ opts of+ Just tag -> journalPivot $ T.pack tag+ Nothing -> id++-- #2133+-- | If the --anon flag is present, raise an informative error.+maybeWarnAboutAnon :: CliOpts -> Journal -> Journal+maybeWarnAboutAnon opts =+ if boolopt "anon" $ rawopts_ opts+ then error' $ unlines [+ "--anon does not give privacy, and perhaps should be avoided;"+ ,"please see https://github.com/hledgerorg/hledger/issues/2133 ."+ ,"For now it has been renamed to --obfuscate (a hidden flag)."+ ]+ else id++-- | If the --obfuscate flag is present, apply light obfuscation to the journal data.+maybeObfuscate :: CliOpts -> Journal -> Journal+maybeObfuscate opts =+ if anon_ . inputopts_ $ opts+ then anon+ else id++-- | Write some output to stdout or to a file selected by --output-file.+-- If the file exists it will be overwritten.+writeOutput :: CliOpts -> String -> IO ()+writeOutput opts s = do+ mf <- outputFileOrViewFile opts+ case mf of+ Nothing -> putStr s+ Just f -> evaluate (length s) >> writeFile f s >> viewIfRequested opts f -- generate all output first, see writeOutputLazyText++-- | Write some output, to a file specified by --output-file if any,+-- otherwise to stdout.+-- If writing to a file and the file exists, it will be overwritten.+-- If writing to stdout, a pager is used when appropriate and possible.+writeOutputLazyText :: CliOpts -> TL.Text -> IO ()+writeOutputLazyText opts s = do+ mf <- outputFileOrViewFile opts+ case mf of+ Nothing -> runPager $ TL.unpack s+ -- Generate all of the output before opening the file, so that an error while generating it+ -- doesn't leave an empty or truncated file.+ Just f -> evaluate (TL.length s) >> TL.writeFile f s >> viewIfRequested opts f++-- | The file to write output to: the --output-file if any; or with --view, hledger's view file+-- (see 'viewFile'); or Nothing for stdout.+outputFileOrViewFile :: CliOpts -> IO (Maybe FilePath)+outputFileOrViewFile opts = do+ mf <- outputFileFromOpts opts+ case mf of+ Nothing | viewRequested opts -> Just <$> viewFile opts+ _ -> return mf++-- | Create (or replace) view.FMT in hledger's cache directory (eg ~/.cache/hledger), to write output to,+-- and return its path. It's in the user's own files, not a shared temporary directory,+-- so that other users can't interfere with it; and it's created readable only by the user (on unix),+-- since a home directory may be readable by others.+-- Since it is in a place the user didn't choose, this always warns where it is, before creating it.+viewFile :: CliOpts -> IO FilePath+viewFile opts = do+ d <- getXdgDirectory XdgCache "hledger"+ createDirectoryIfMissing True d+ let f = d </> "view." ++ outputFormatFromOpts opts+ hPutStrLn stderr $ "writing " ++ f ++ " (if it's sensitive, delete it after viewing)"+ -- openTempFile creates a file with owner-only permissions, which writing it later keeps+ (tmp, h) <- openTempFile d "view.tmp"+ hClose h+ renameFile tmp f+ return f++-- | With --view, open a written output file in the system's default viewer for it.+-- If that fails, the file is still there.+viewIfRequested :: CliOpts -> FilePath -> IO ()+viewIfRequested opts f = when (viewRequested opts) $+ launch f >>= either couldnotopen return+ where+ couldnotopen tried = warnIO $ printf "could not open a viewer (tried: %s)" (intercalate ", " tried)++-- | Prepend the effective report heading (followed by a blank line) to a+-- report's lazy text output, if non-empty. Used by reports whose default+-- heading is empty; pass the explicit --title value or "" via+-- effectiveTitle.+withTitle :: ReportOpts -> TL.Text -> TL.Text+withTitle ropts body =+ let h = effectiveTitle ropts ""+ in if T.null h then body+ else TL.fromStrict h <> "\n\n" <> body++-- | Write some text output with 'writeOutput', after the effective report heading+-- if any (see 'withTitle'). For commands producing simple text, like lists of names.+writeOutputWithTitle :: CliOpts -> T.Text -> IO ()+writeOutputWithTitle opts =+ writeOutput opts . TL.unpack . withTitle (_rsReportOpts $ reportspec_ opts) . TL.fromStrict++-- -- | Get a journal from the given string and options, or throw an error.+-- readJournal :: CliOpts -> String -> IO Journal+-- readJournal opts s = readJournal def Nothing s >>= either error' return++-- | Re-read the option-specified journal file(s), but only if any of+-- them has changed since last read. (If the file is standard input,+-- this will either do nothing or give an error, not tested yet).+-- Returns a journal or error message, and a flag indicating whether+-- it was re-read or not. Like withJournal and journalReload, reads+-- the full journal, without filtering.+journalReloadIfChanged :: CliOpts -> Day -> Journal -> ExceptT String IO (Journal, Bool)+journalReloadIfChanged opts _d j = do+ let maybeChangedFilename f = do newer <- journalFileIsNewer j f return $ if newer then Just f else Nothing- changedfiles <- catMaybes `fmap` mapM maybeChangedFilename (journalFilePaths j)- if not $ null changedfiles- then do- whenLoud $ printf "%s has changed, reloading\n" (head changedfiles)- jE <- journalReload j- return (jE, True)- else- return (Right j, False)+ changedfiles <- liftIO $ catMaybes <$> mapM maybeChangedFilename (journalAllFilePaths j)+ case changedfiles of+ [] -> return (j, False)+ f:_ -> do+ -- XXX not sure why we use cmdarg's verbosity here, but keep it for now+ verbose <- liftIO isLoud+ when (verbose || debugLevel >= 6) . liftIO $ printf "%s has changed, reloading\n" f+ newj <- journalReload opts+ return (newj, True) --- | Has the journal's main data file changed since the journal was last--- read ?-journalFileIsNewer :: Journal -> IO Bool-journalFileIsNewer j@Journal{filereadtime=tread} = do- tmod <- fileModificationTime $ journalFilePath j- return $ diffClockTimes tmod tread > (TimeDiff 0 0 0 0 0 0 0)+-- | Re-read the journal file(s) specified by options, applying any+-- transformations specified by options. Or return an error string.+-- Reads the full journal, without filtering.+--+-- Sets 'InputOpts._journaldir' on the iopts used for this read. Callers that+-- subsequently do another 'readJournalFile' / 'readJournalFiles' call should+-- apply 'inputOptsSetJournalDir' to those iopts (see 'withJournal').+journalReload :: CliOpts -> ExceptT String IO Journal+journalReload opts = journalReloadWithOverrides opts M.empty --- | Has the specified file (presumably one of journal's data files)--- changed since journal was last read ?-journalSpecifiedFileIsNewer :: Journal -> FilePath -> IO Bool-journalSpecifiedFileIsNewer Journal{filereadtime=tread} f = do- tmod <- fileModificationTime f- return $ diffClockTimes tmod tread > (TimeDiff 0 0 0 0 0 0 0)+-- | Check a change to one of the journal's files before writing it:+-- re-read the journal as 'journalReload' would after this text was written to this file+-- (which need not exist yet), without writing anything.+-- Return the journal that read gives, or its error message.+-- So the change passes exactly the checks the next read will make, with these options+-- (balancing, balance assertions, lots, strict checks, etc), in the context of all the journal's files.+-- The text should have \n line endings.+journalCheckChange :: CliOpts -> FilePath -> T.Text -> ExceptT String IO Journal+journalCheckChange opts f t = do+ cf <- liftIO $ canonicalizePath f+ journalReloadWithOverrides opts $ M.singleton cf t --- | Get the last modified time of the specified file, or if it does not--- exist or there is some other error, the current time.-fileModificationTime :: FilePath -> IO ClockTime-fileModificationTime f- | null f = getClockTime- | otherwise = getModificationTime f `Prelude.catch` \_ -> getClockTime+-- | Like 'journalReload', but reading the given replacement text for some files (see 'InputOpts._fileoverrides').+journalReloadWithOverrides :: CliOpts -> M.Map FilePath T.Text -> ExceptT String IO Journal+journalReloadWithOverrides opts overrides = do+ journalpaths <- liftIO $ dbg6 "reloading files" <$> journalFilePathFromOpts opts+ let iopts = (inputopts_ opts){_journaldir = Just (takeDirectory (NE.head journalpaths)), _fileoverrides = overrides}+ journalTransform opts <$> readJournalFiles iopts (NE.toList journalpaths) +-- | Has the specified file changed since the journal was last read ?+-- Typically this is one of the journal's journalFilePaths. These are+-- not always real files, so the file's existence is tested first;+-- for non-files the answer is always no.+journalFileIsNewer :: Journal -> FilePath -> IO Bool+journalFileIsNewer Journal{jlastreadtime=tread} f = do+ mtmod <- maybeFileModificationTime f+ return $+ case mtmod of+ Just tmod -> tmod > tread+ Nothing -> False++-- | Get the last modified time of the specified file, if it exists.+maybeFileModificationTime :: FilePath -> IO (Maybe POSIXTime)+maybeFileModificationTime f = do+ exists <- doesFileExist f+ if exists+ then do+ utc <- getModificationTime f+ return . Just $ utcTimeToPOSIXSeconds utc+ else+ return Nothing+ -- | Attempt to open a web browser on the given url, all platforms.+-- On Windows this goes through the open-browser package, which asks the+-- Win32 API to open the url. Elsewhere it runs the platform's launchers in+-- turn until one exits successfully (one that is not installed counts as+-- failing): `open` on mac; `xdg-open` and then some older launchers that+-- may be installed on Linux. If nothing starts, print the url instead. openBrowserOn :: String -> IO ExitCode-openBrowserOn u = trybrowsers browsers u+openBrowserOn u = launch u >>= either couldnotstart (const $ return ExitSuccess)+ where+ couldnotstart tried = do+ putStrLn $ printf "Could not start a web browser (tried: %s)" $ intercalate ", " tried+ putStrLn $ printf "Please open your browser and visit %s" u+ return $ ExitFailure 127++-- | Open a url or file with the platform's default application for it, as described for 'openBrowserOn'.+-- If nothing could be started, return what was tried.+launch :: String -> IO (Either [String] ())+launch u+ | os == "mingw32" = do+ ok <- openBrowser u+ return $ if ok then Right () else Left ["the Win32 API"]+ | otherwise = trylaunchers launchers where- trybrowsers (b:bs) u = do- (e,_,_) <- readProcessWithExitCode b [u] ""- case e of- ExitSuccess -> return ExitSuccess- ExitFailure _ -> trybrowsers bs u- trybrowsers [] u = do- putStrLn $ printf "Could not start a web browser (tried: %s)" $ intercalate ", " browsers- putStrLn $ printf "Please open your browser and visit %s" u- return $ ExitFailure 127- browsers | os=="darwin" = ["open"]- | os=="mingw32" = ["c:/Program Files/Mozilla Firefox/firefox.exe"]- | otherwise = ["sensible-browser","gnome-www-browser","firefox"]- -- jeffz: write a ffi binding for it using the Win32 package as a basis- -- start by adding System/Win32/Shell.hsc and follow the style of any- -- other module in that directory for types, headers, error handling and- -- what not.- -- ::ShellExecute(NULL, "open", "www.somepage.com", NULL, NULL, SW_SHOWNORMAL);+ trylaunchers (cmd:rest) = do+ r <- try $ readProcessWithExitCode cmd [u] ""+ case r of+ Right (ExitSuccess,_,_) -> return $ Right ()+ Right (ExitFailure _,_,_) -> trylaunchers rest+ Left (_ :: IOException) -> trylaunchers rest+ trylaunchers [] = return $ Left launchers+ launchers | os == "darwin" = ["open"]+ | otherwise = ["xdg-open", "sensible-browser", "gnome-www-browser", "firefox"] -- | Back up this file with a (incrementing) numbered suffix then -- overwrite it with this new text, or give an error, but only if the text -- is different from the current file contents, and return a flag -- indicating whether we did anything.-writeFileWithBackupIfChanged :: FilePath -> String -> IO Bool+--+-- The given text should have unix line endings (\n); the existing+-- file content will be normalised to unix line endings before+-- comparing the two. If the file is overwritten, the new file will+-- have the current system's native line endings (\n on unix, \r\n on+-- windows). This could be different from the file's previous line+-- endings, if working with a DOS file on unix or vice-versa.+--+writeFileWithBackupIfChanged :: FilePath -> T.Text -> IO Bool writeFileWithBackupIfChanged f t = do- s <- readFile f+ s <- readFilePortably f if t == s then return False- else backUpFile f >> writeFile f t >> return True+ else backUpFile f >> T.writeFile f t >> return True -- | Back up this file with a (incrementing) numbered suffix, then -- overwrite it with this new text, or give an error. writeFileWithBackup :: FilePath -> String -> IO () writeFileWithBackup f t = backUpFile f >> writeFile f t -readFileStrictly :: FilePath -> IO String-readFileStrictly f = readFile f >>= \s -> Control.Exception.evaluate (length s) >> return s- -- | Back up this file with a (incrementing) numbered suffix, or give an error. backUpFile :: FilePath -> IO () backUpFile fp = do fs <- safeGetDirectoryContents $ takeDirectory $ fp let (d,f) = splitFileName fp- versions = catMaybes $ map (f `backupNumber`) fs+ versions = mapMaybe (f `backupNumber`) fs next = maximum (0:versions) + 1 f' = printf "%s.%d" f next copyFile fp (d </> f')@@ -157,7 +478,71 @@ safeGetDirectoryContents fp = getDirectoryContents fp -- | Does the second file represent a backup of the first, and if so which version is it ?+-- XXX nasty regex types intruding, add a simpler api to Hledger.Utils.Regex backupNumber :: FilePath -> FilePath -> Maybe Int-backupNumber f g = case regexMatch ("^" ++ f ++ "\\.([0-9]+)$") g of- Just (_, ((_,suffix):_)) -> readMay suffix+backupNumber f g = case g =~ ("^" ++ f ++ "\\.([0-9]+)$") of+ (_::FilePath, _::FilePath, _::FilePath, [ext::FilePath]) -> readMay ext _ -> Nothing++-- Identify the closest match for this description in past/future transactions,+-- considering both similarity and proximity to today's date.+-- If the options specify a query, only matched transactions are considered.+journalSimilarTransaction :: CliOpts -> Journal -> T.Text -> Maybe Transaction+journalSimilarTransaction cliopts j desc =+ fmap fourth4 $ headMay $ journalTransactionsSimilarTo j today desc q 0 1+ where+ today = cliopts ^. rsDay+ q = queryFromFlags $ _rsReportOpts $ reportspec_ cliopts++-- | Render a 'PostingsReport' or 'AccountTransactionsReport' as Text,+-- determining the appropriate starting widths and increasing as necessary.+postingsOrTransactionsReportAsText+ :: Bool -> CliOpts -> (Int -> Int -> (a, [WideBuilder], [WideBuilder]) -> TB.Builder)+ -> (a -> MixedAmount) -> (a -> MixedAmount) -> [a] -> TB.Builder+postingsOrTransactionsReportAsText alignAll opts itemAsText itemamt itembal report =+ mconcat . snd $ mapAccumL renderItem (startWidth amt, startWidth bal) itemsWithAmounts+ where+ minWidth = 12+ chunkSize = 1000++ renderItem (amtWidth, balWidth) item@(_, amt1, bal1) = ((amtWidth', balWidth'), itemBuilder)+ where+ itemBuilder = itemAsText amtWidth' balWidth' item+ amtWidth' = if alignAll then amtWidth else maximumStrict $ amtWidth : map wbWidth amt1+ balWidth' = if alignAll then balWidth else maximumStrict $ balWidth : map wbWidth bal1++ startWidth f = maximum $ minWidth : map wbWidth (concatMap f startAlign)+ where+ startAlign = (if alignAll then id else take chunkSize) itemsWithAmounts++ itemsWithAmounts = map (\x -> (x, showAmt $ itemamt x, showAmt $ itembal x)) report+ showAmt = showMixedAmountLinesB oneLineNoCostFmt{displayColour=opts^.color__}+ amt = second3+ bal = third3++tests_Cli_Utils = testGroup "Utils" [++ -- testGroup "journalApplyValue" [+ -- -- Print the time required to convert one of the sample journals' amounts to value.+ -- -- Pretty clunky, but working.+ -- -- XXX sample.journal has no price records, but is always present.+ -- -- Change to eg examples/5000x1000x10.journal to make this useful.+ -- testCase "time" $ do+ -- ej <- io $ readJournalFile definputopts "examples/3000x1000x10.journal"+ -- case ej of+ -- Left e -> crash $ T.pack e+ -- Right j -> do+ -- (t,_) <- io $ timeItT $ do+ -- -- Enable -V, and ensure the valuation date is later than+ -- -- all prices for consistent timing.+ -- let ropts = defreportopts{+ -- value_=True,+ -- period_=PeriodTo $ fromGregorian 3000 01 01+ -- }+ -- j' <- journalApplyValue ropts j+ -- sum (journalAmounts j') `seq` return ()+ -- io $ printf "[%.3fs] " t+ -- ok+ -- ]++ ]
Hledger/Cli/Version.hs view
@@ -1,83 +1,290 @@-{-# LANGUAGE CPP #-}+{-# LANGUAGE CPP #-} {--Version-related utilities. See the Makefile for details of our version-numbering policy.+Version number-related utilities. See also the Makefile. -} module Hledger.Cli.Version (- version- ,progversionstr- ,binaryfilename+ PackageVersionString,+ Version,+ nullversion,+ toVersion,+ showVersion,+ isReleaseVersion,+ HledgerVersionString,+ HledgerBinaryInfo(..),+ nullbinaryinfo,+ ProgramName,+ GitHash,+ ArchName,+ parseHledgerVersion,+ packageversion,+ packagemajorversion,+ docVersion,+ webManualUrl,+ versionStringWith, ) where-import Data.List++import GitHash (GitInfo, giHash, giCommitDate) -- giDirty import System.Info (os, arch)-import Text.Printf+import Data.Char (toLower)+import Data.List (intercalate)+import Data.List.NonEmpty (NonEmpty ((:|)), nonEmpty, toList)+import Data.List.Split (splitOn)+import Data.Maybe+import Text.Read (readMaybe) -import Hledger.Utils+import Hledger.Utils (ghcDebugSupportedInLib, splitAtElement, rstrip)+import Data.Time (Day)+import Text.Megaparsec+import Data.Void (Void)+import Text.Megaparsec.Char+import Text.Megaparsec.Char.Lexer qualified as L+import Hledger.Data.Dates (parsedate)+import Data.Bifunctor+import Data.List.NonEmpty qualified as NE --- version and PATCHLEVEL are set by the make process+-- | A Cabal/Hackage-compatible package version string: one or more dot-separated integers.+type PackageVersionString = String -version :: String-version = "0.16.1"+-- | The number parts parsed from a PackageVersionString.+type Version = NonEmpty Int -patchlevel :: String-#ifdef PATCHLEVEL-patchlevel = "." ++ show (PATCHLEVEL :: Int) -- must be numeric !+nullversion = NE.fromList [0]++showVersion :: Version -> String+showVersion = intercalate "." . map show . toList++-- | Parse a valid Cabal/Hackage-compatible package version.+toVersion :: PackageVersionString -> Maybe Version+toVersion s =+ let parts = map readMaybe $ splitOn "." s :: [Maybe Int]+ in+ if null parts || any isNothing parts+ then Nothing+ else nonEmpty $ catMaybes parts++isReleaseVersion :: Version -> Bool+isReleaseVersion v = NE.last v < 98 -- .99 and possibly .98 are dev++-- | A hledger version string, as shown by hledger --version.+-- This can vary; some examples:+--+-- * dev builds: hledger 1.42.99-g2288f5193-20250422, mac-aarch64+--+-- * release builds: hledger 1.42.1, mac-aarch64+--+-- * older versions: hledger 1.21+type HledgerVersionString = String++-- | The program name from a hledger version string: hledger, hledger-ui, hledger-web..+type ProgramName = String++-- | The operating system name from a hledger version string.+-- This the value of @System.Info.os@ modified for readability:+-- mac, windows, linux, linux-android, freebsd, netbsd, openbsd..+type OsName = String++-- | The machine architecture from a hledger version string.+-- This is the value of @System.Info.arch@, eg:+-- aarch64, alpha, arm, hppa, hppa1_1, i386, ia64, loongarch32, loongarch64, m68k,+-- mips, mipseb, mipsel, nios2, powerpc, powerpc64, powerpc64le, riscv32, riscv64,+-- rs6000, s390, s390x, sh4, sparc, sparc64, vax, x86_64..+type ArchName = String++-- | The git hash from a hledger version string, excluding the g prefix.+type GitHash = String++-- | The name and package version of a hledger binary,+-- and the build's git hash, the release date, and the binary's +-- intended operating machine and machine architecture, if we can detect these.+-- Also, a copy of the --version output from which it was parsed.+data HledgerBinaryInfo = HledgerBinaryInfo {+ hbinVersionOutput :: String+ , hbinProgramName :: ProgramName+ , hbinPackageVersion :: Version + , hbinPackageVersionStr :: String+ , hbinGitHash :: Maybe GitHash+ , hbinReleaseDate :: Maybe Day+ , hbinOs :: Maybe OsName+ , hbinArch :: Maybe ArchName+} deriving (Show, Eq)++nullbinaryinfo = HledgerBinaryInfo {+ hbinVersionOutput = ""+ , hbinProgramName = ""+ , hbinPackageVersion = nullversion+ , hbinPackageVersionStr = ""+ , hbinGitHash = Nothing+ , hbinReleaseDate = Nothing+ , hbinOs = Nothing+ , hbinArch = Nothing+}++type Parser = Parsec Void String++-- | Parse hledger's --version output.+--+-- >>> isRight $ parseHledgerVersion "hledger 1.21"+-- True+-- >>> isRight $ parseHledgerVersion "hledger 1.42.1, mac-aarch64"+-- True+-- >>> isRight $ parseHledgerVersion "hledger 1.42.99-g2288f5193-20250422, mac-aarch64"+-- True+--+parseHledgerVersion :: HledgerVersionString -> Either String HledgerBinaryInfo+parseHledgerVersion s = + case parse hledgerversionp "" s of+ Left err -> Left $ errorBundlePretty err+ Right v -> Right v{hbinVersionOutput=rstrip s}++-- Parser for hledger --version output: a program name beginning with "hledger" and a package version;+-- possibly followed by a git hash and release date;+-- possibly followed by the binary's intended operating system and architecture+-- (see HledgerVersionString and versionStringWith).+-- The hbinVersionOutput field is left blank here; parseHledgerVersion sets it.+hledgerversionp :: Parser HledgerBinaryInfo+hledgerversionp = do+ progName <- (<>) <$> string "hledger" <*> many (letterChar <|> char '-')+ some $ char ' '+ pkgversion <- packageversionp+ mgithash <- optional $ try $ string "-g" *> some hexDigitChar+ mreldate <- optional $ do+ string "-"+ datestr <- (:) <$> digitChar <*> some (digitChar <|> char '-')+ maybe (fail "invalid date") pure $ parsedate $ datestr+ -- Oh oh. hledger --version prints OS-ARCH, but it turns out OS can contain hyphens (eg linux-android).+ -- Based on the "common values" in System.Info docs, it seems ARCH typically does not contain hyphens;+ -- we'll assume that here, and split at the rightmost hyphen.+ mosarch <- optional $ do+ string ","+ some (char ' ')+ some (letterChar <|> digitChar <|> char '-' <|> char '_')+ let+ (march, mos) = case mosarch of+ Nothing -> (Nothing, Nothing)+ Just osarch -> bimap (Just . reverse) (Just . reverse) $ second (drop 1) $ break (== '-') $ reverse osarch+ many spaceChar+ eof+ return $ HledgerBinaryInfo+ { hbinVersionOutput = ""+ , hbinProgramName = progName+ , hbinPackageVersion = pkgversion+ , hbinPackageVersionStr = showVersion pkgversion+ , hbinGitHash = mgithash+ , hbinReleaseDate = mreldate+ , hbinOs = mos+ , hbinArch = march+ }++-- | Parser for Cabal package version numbers, one or more dot-separated integers. Eg "1.42.1".+packageversionp :: Parser Version+packageversionp = do+ firstNum <- L.decimal+ rest <- many (char '.' *> L.decimal)+ return $ firstNum :| rest++-- | The VERSION string defined with -D in this package's package.yaml/.cabal file +-- (by Shake setversion), if any. Normally a dotted number string with 1-3 components.+packageversion :: PackageVersionString+packageversion =+#ifdef VERSION+ VERSION #else-patchlevel = ""+ "" #endif -buildversion :: String-buildversion = version ++ patchlevel :: String---- | Given a program name, return a human-readable version string. For--- development builds, at least non-cabal builds, the patch level (ie the--- number of patches applied since last release tag) will also be--- included.-progversionstr :: String -> String-progversionstr progname = progname ++ "-" ++ versionstr ++ configmsg- where- versionstr = prettify $ splitAtElement '.' buildversion- where- prettify (major:minor:bugfix:patches:[]) =- printf "%s.%s%s%s" major minor bugfix' patches'- where- bugfix'- | bugfix `elem` ["0"{-,"98","99"-}] = ""- | otherwise = '.' : bugfix- patches'- | patches/="0" = "+"++patches- | otherwise = ""- prettify s = intercalate "." s+-- | Just the first 1-2 components of packageversion.+packagemajorversion :: PackageVersionString+packagemajorversion = intercalate "." $ take 2 $ splitAtElement '.' packageversion - configmsg | null buildflags = ""- | otherwise = " with " ++ intercalate ", " buildflags+-- | The hledger.org path segment for this build's online manuals:+-- the major.minor version for a release build, or "dev" for a dev build+-- (one whose package version is newer than the latest release, ie ends in .98/.99).+docVersion :: String+docVersion = case toVersion packageversion of+ Just v | isReleaseVersion v -> packagemajorversion+ _ -> "dev" - buildflags = []+-- | The URL of the given hledger tool's manual on hledger.org, for this build's+-- version (see 'docVersion'), optionally at a section anchor derived from a+-- heading (lower-cased, with spaces replaced by hyphens).+-- The program name should be hledger, hledger-ui or hledger-web.+webManualUrl :: ProgramName -> Maybe String -> String+webManualUrl prog mheading =+ "https://hledger.org/" <> docVersion <> "/" <> prog <> ".html"+ <> maybe "" (("#"<>) . headingAnchor) mheading+ where headingAnchor = map (\c -> if c==' ' then '-' else toLower c) --- | Given a program name, return a precise platform-specific executable--- name suitable for naming downloadable binaries. Can raise an error if--- the version and patch level was not defined correctly at build time.-binaryfilename :: String -> String-binaryfilename progname = prettify $ splitAtElement '.' buildversion- where- prettify (major:minor:bugfix:patches:[]) =- printf "%s-%s.%s%s%s-%s-%s%s" progname major minor bugfix' patches' os' arch suffix- where- bugfix'- | bugfix `elem` ["0"{-,"98","99"-}] = ""- | otherwise = '.' : bugfix- patches'- | patches/="0" = '+' : patches- | otherwise = ""- (os',suffix)- | os == "darwin" = ("mac","")- | os == "mingw32" = ("windows",".exe")- | otherwise = (os,"")- prettify (major:minor:bugfix:[]) = prettify [major,minor,bugfix,"0"]- prettify (major:minor:[]) = prettify [major,minor,"0","0"]- prettify (major:[]) = prettify [major,"0","0","0"]- prettify [] = error' "VERSION is empty, please fix"- prettify _ = error' "VERSION has too many components, please fix"+-- | Given possible git state info from the build directory (or a git error, which is ignored),+-- and the debug build flag, executable name and package version for the package being built,+-- make the best version string we can. Here is the logic:+-- +-- * Program name, OS and architecture are always shown.+-- * The package version is always shown.+-- * If there is git info at build time, the latest commit hash and commit date are shown,+-- and (TODO, requires githash to use -uno for giDirty):+-- if the working copy has uncommitted changes a + sign is appended.+-- * (TODO, requires adding --match support to githash:+-- If there are tags matching THISPKG-[0-9]*, the latest one is used to calculate patch level+-- (number of commits since tag), and if non-zero, it and the branch name are shown.)+-- * If the debug build flag was enabled for the package being built, and for hledger-lib (both are needed),+-- "ghc-debug support" is shown.+--+-- Some example outputs:+--+-- * A homebrew binary, not built in git repo: hledger-ui 1.24, mac-aarch64+-- * A CI release build, built in git repo at release tag: hledger-ui 1.24.1-g455b35293-20211210, mac-x86_64+-- * (TODO) A dev build, built in git repo: hledger-ui 1.24.1+1-g4abd8ef10-20211210 (1.24-branch), mac-x86_64+--+-- This function requires git log to show the default (rfc2822-style) date format,+-- so that must not be overridden by a log.date git config variable.+--+-- The GitInfo if any, fetched by template haskell, is passed down from+-- a top-level module, reducing wasteful recompilation.+-- The status of the debug build flag is also passed down, since it is+-- specific to each hledger package.+--+-- This is used indirectly by at least hledger, hledger-ui, and hledger-web,+-- so output should be suitable for all of those.+--+versionStringWith :: Either String GitInfo -> Bool -> ProgramName -> PackageVersionString -> HledgerVersionString+versionStringWith egitinfo ghcDebugSupportedInThisPackage progname packagever =+ concat $+ [ progname , " " , version , ", " , os' , "-" , arch ]+ ++ [ " with ghc-debug support" | ghcDebugSupportedInThisPackage && ghcDebugSupportedInLib ]+ where+ os' | os == "darwin" = "mac"+ | os == "mingw32" = "windows"+ | otherwise = os+ version = case egitinfo of+ Left _err -> packagever+ Right gitinfo -> + case words $ giCommitDate gitinfo of+ -- git log's date format is normally --date=default ("similar to --date=rfc2822")+ _weekday:mon:day:_localtime:year:_offset:_ ->+ intercalate "-" $ [packagever, hash, date]+ -- ++ ["+" | giDirty gitinfo]+ -- XXX giDirty is wrong when repo shows untracked files by default, skip it for now+ where+ hash = 'g' : take 9 (giHash gitinfo) -- like git describe+ date = concat [year,mm,dd]+ where + mm = fromMaybe mon $ lookup mon $ [+ ("Jan","01")+ ,("Feb","02")+ ,("Mar","03")+ ,("Apr","04")+ ,("May","05")+ ,("Jun","06")+ ,("Jul","07")+ ,("Aug","08")+ ,("Sep","09")+ ,("Oct","10")+ ,("Nov","11")+ ,("Dec","12")+ ]+ dd = (if length day < 2 then ('0':) else id) day+ -- but could be overridden by a log.date config variable in repo or user git config+ _ -> packageversion
+ Hledger/Cli/Xirr.hs view
@@ -0,0 +1,61 @@+{-|++Calculation of the internal rate of return of some dated cash flows, shared by the @roi@ and @holdings@ commands.++-}++module Hledger.Cli.Xirr (+ IrrError(..)+ , xirr+) where++import Data.Time.Calendar (Day, diffDays)+import Numeric.RootFinding (RiddersParam(..), Root(..), Tolerance(..), ridders)++import Hledger (Quantity)++-- | Why an internal rate of return could not be computed.+data IrrError+ = IrrNothingPutIn -- ^ money only came out (or is still in at the end), and none was put in: the rate is infinite+ | IrrAllOnOneDay Day -- ^ all the cash flows fall on this day, so no time passes, but they don't add up to zero+ | IrrNotBracketed -- ^ no solution between -100% and the largest rate searched (1000000%)+ | IrrSearchFailed -- ^ the search for a solution did not converge+ deriving (Eq, Show)++-- | The annualised internal rate of return of some dated cash flows, as a percentage, like Excel's XIRR.+-- What is put in is negative; what is taken out, or is still held at the end, is positive.+-- Each flow is compounded from its date to the reference day (usually the date of the last one).+--+-- Some cases have no solution, or one the search can't find:+--+-- - no cash flows: 0%+-- - money is put in, but nothing comes out or is left: -100% (all of it was lost)+-- - money comes out or is left, but nothing is put in: an infinite rate, so an error+-- - all on one day: 0% if they add up to zero (nothing was gained or lost), otherwise an error, as no time passes for+-- the gain or loss to happen in.+--+-- So on one day, a total loss is -100% but a partial loss is an error. That's because a total loss solves+-- (1+r)^t = 0, which gives -100% however long the money was in. A partial loss (eg (1+r)^t = 0.5) depends on t, and has+-- no solution when no time passes.+-- (Also, cash flows which net to zero are not passed in, so a total loss's date is not known here.)+xirr :: Day -> [(Day, Quantity)] -> Either IrrError Double+xirr referenceDay cf0 = case cf of+ [] -> Right 0+ _ | all ((< 0) . snd) cf -> Right (-100)+ | all ((> 0) . snd) cf -> Left IrrNothingPutIn+ (d, _) : _ | all ((== d) . fst) cf ->+ -- (valued amounts can leave a tiny remainder, so allow for that)+ if abs (sum qs) <= maximum (map abs qs) / 10^(10::Int) then Right 0 else Left (IrrAllOnOneDay d)+ where qs = map snd cf+ _ -> case ridders (RiddersParam 100 (AbsTol 0.00001)) (0.000000000001, 10000) npv of+ Root rate -> Right $ (rate - 1) * 100+ NotBracketed -> Left IrrNotBracketed+ SearchFailed -> Left IrrSearchFailed+ where+ cf = filter ((/= 0) . snd) cf0+ -- the cash flows' net value on the reference day, at this rate (1 + the annual rate of return)+ npv rate = sum [ q * rate ** years | (years, q) <- cfyears ]+ -- each cash flow's time before the reference day in years, and amount, converted once+ -- (the search evaluates npv many times, and converting Decimals is slow)+ cfyears :: [(Double, Double)]+ cfyears = [ (fromIntegral (diffDays referenceDay t) / 365.25, realToFrac q) | (t, q) <- cf ]
LICENSE view
@@ -1,7 +1,7 @@ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 - Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. @@ -645,7 +645,7 @@ GNU General Public License for more details. You should have received a copy of the GNU General Public License- along with this program. If not, see <http://www.gnu.org/licenses/>.+ along with this program. If not, see <https://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. @@ -664,11 +664,11 @@ You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see-<http://www.gnu.org/licenses/>.+<https://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read-<http://www.gnu.org/philosophy/why-not-lgpl.html>.+<https://www.gnu.org/licenses/why-not-lgpl.html>.
+ README.md view
@@ -0,0 +1,9 @@+# hledger++The command-line interface for the hledger accounting system.+Its basic function is to read a plain text file describing+financial transactions and produce useful reports.++See also:+the [project README](https://hledger.org/README.html)+and [home page](https://hledger.org).
+ app/hledger-cli.hs view
@@ -0,0 +1,17 @@+-- the hledger command-line executable; see Hledger/Cli.hs++module Main (main)+where+import Control.Monad (when)+import System.IO (hClose, hIsSeekable, stdout)+import Hledger.Cli qualified (main)++-- Have to write this explicitly for GHC 9.0.1a for some reason:+main :: IO ()+main = do+ Hledger.Cli.main+ -- When output is redirected to a file, close it explicitly rather than leaving that to process exit.+ -- On some network filesystems (seen with Linux CIFS), the implicit close at exit+ -- of a multithreaded program can be interrupted, losing the unflushed part of the output.+ tofile <- hIsSeekable stdout+ when tofile $ hClose stdout
+ bench/bench.hs view
@@ -0,0 +1,59 @@+-- bench+-- By default, show approximate times for some standard hledger operations on a sample journal.+-- With --criterion, show accurate times (slow).++import Criterion.Main (defaultMainWith, defaultConfig, bench, nfIO)+-- import QuickBench (defaultMain)+import System.Directory (getCurrentDirectory)+import System.Environment (getArgs, withArgs)+import System.TimeIt (timeItT)+import Text.Printf+import Hledger.Cli hiding (main)++-- sample journal file to use for benchmarks+inputfile = "bench/10000x1000x10.journal"++outputfile = "/dev/null" -- hide output of benchmarked commands (XXX unixism)+-- outputfile = "-" -- show output of benchmarked commands++main = do+ -- withArgs ["--quickbench"] $ do+ -- withArgs ["--criterion"] $ do+ args <- getArgs+ if "--criterion" `elem` args+ then+ withArgs [] benchWithCriterion+ else+-- if "--quickbench" `elem` args+-- then+-- benchWithQuickbench+-- else+ benchWithTimeit++benchWithTimeit = do+ getCurrentDirectory >>= printf "Benchmarking hledger in %s with timeit\n"+ let opts = defcliopts{output_file_=Just outputfile}+ (t0,j) <- timeit ("read "++inputfile) $ readJournalFile' inputfile -- PARTIAL:+ (t1,_) <- timeit ("print") $ print' opts j+ (t2,_) <- timeit ("register") $ register opts j+ (t3,_) <- timeit ("balance") $ balance opts j+ printf "Total: %0.2fs\n" (sum [t0,t1,t2,t3])++timeit :: String -> IO a -> IO (Double, a)+timeit name action = do+ printf "%s%s" name (replicate (40 - length name) ' ')+ (t,a) <- timeItT action+ printf "[%.2fs]\n" t+ return (t,a)++benchWithCriterion = do+ getCurrentDirectory >>= printf "Benchmarking hledger in %s with criterion\n"+ let opts = defcliopts{output_file_=Just "/dev/null"}+ j <- readJournalFile' inputfile -- PARTIAL:+ Criterion.Main.defaultMainWith defaultConfig $ [+ bench ("read "++inputfile) $ nfIO $ const <$> readJournalFile' inputfile, -- PARTIAL:+ bench ("print") $ nfIO $ print' opts j,+ bench ("register") $ nfIO $ register opts j,+ bench ("balance") $ nfIO $ balance opts j,+ bench ("stats") $ nfIO $ stats opts j+ ]
+ embeddedfiles/file-layouts/default/accounts.journal view
@@ -0,0 +1,43 @@+; Account declarations+; https://hledger.org/hledger.html#account-directive+; https://hledger.org/hledger.html#strict-checks++; Top-level accounts and their https://hledger.org/hledger.html#account-types.+; The order of declarations also sets https://hledger.org/hledger.html#account-display-order.+; Lower case, unspaced account names are easiest to type, but use capitals/spaces if you prefer.+; https://hledger.org/hledger.html#account-names++account assets ; type:A+account liabilities ; type:L+account equity ; type:E+account revenues ; type:R+account expenses ; type:X++; Subaccounts/subcategories.++account assets:bank:checking+account assets:cash+account assets:receivable++account liabilities:bank:credit card+account liabilities:payable++account equity:start+account equity:conversion++account revenues:gifts+account revenues:salary+account revenues:consulting+account revenues:gains++account expenses:food+account expenses:gifts+account expenses:home+account expenses:misc+account expenses:online services+account expenses:personal care+account expenses:phone+account expenses:recreation+account expenses:transport+account expenses:travel+account expenses:utilities
+ embeddedfiles/file-layouts/default/commodities.journal view
@@ -0,0 +1,28 @@+; Commodity declarations - these set amount display styles and provide extra error checking.+; https://hledger.org/hledger.html#commodity-directive+; https://hledger.org/hledger.html#strict-checks++; Fiat currencies++commodity $1000.00+commodity 1000.00 EUR+;commodity 1 000 000,00 EUR ; https://hledger.org/hledger.html#commodity-display-style can be customised++; Investment commodities+; Note commodity declarations must have a decimal mark (a period or comma), +; even if no decimal digits follow it.++commodity 1. AAPL ; lots:++; Cryptocurrencies++commodity 1.000000 ADA ; lots:+commodity 1.00000000 BTC ; lots:+commodity 1.00000000 ETH ; lots:++; Other++; D declares a default commodity (and display style) to apply to bare numbers.+; This one can be useful if you include timedot files: it adds the h (hour)+; symbol, which is also the one used by timeclock files. +;D 1.0h
+ embeddedfiles/file-layouts/default/data/archive/README.md view
@@ -0,0 +1,1 @@+CSV downloads will be archived here if the `archive` rule is used.
+ embeddedfiles/file-layouts/default/data/bankofireland-checking.csv view
@@ -0,0 +1,3 @@+Date,Details,Debit,Credit,Balance+07/01/2026,LODGMENT 529898,,10.0,131.21+07/01/2026,PAYMENT,5,,126
+ embeddedfiles/file-layouts/default/data/getdata view
@@ -0,0 +1,34 @@+#!/usr/bin/env bash+# getdata is a helper for hledger's `get` command (data phase). You can also run it yourself.+# It is intended to download statements (CSV, OFX, etc.) from banks, brokerages,+# and other financial providers into the current directory, ready for hledger to+# read via CSV rules or convert with the `import` command.+#+# It is run by `hledger get` with the journal's `data/` directory as the+# current working directory, so any files it creates land there.+#+# This shipped version is a stub. Copy it into your journal's `data/` directory+# and customise it for your accounts and tools.+#+# See also:+# https://hledger.org/import-csv.html+# https://hledger.org/csv.html++set -euo pipefail++cat >&2 <<'EOF'+getdata: this is the sample stub script.+It does not fetch anything yet. Customise this script to download CSV or other data files+from your bank, brokerage, or other financial providers, into the working directory,+for later processing by your rules files.+EOF++# Whether you can automate data fetching depends on your institutions and appetite for scripting.+# Here are two easy ways to automate data fetching, using other scripts from the hledger repo's bin directory:+#+# simplefinjson >simplefin.json # fetch recent transactions from SimpleFIN (see also simplefinsetup)+# paypaljson >paypal.json # fetch recent transactions from PayPal+#+# For an example of rules files converting these, see+# https://github.com/hledgerorg/hledger/blob/main/examples/csv/banking/unify-checking.rules+# https://github.com/hledgerorg/hledger/blob/main/examples/csv/other/paypal-simplefin.rules
+ embeddedfiles/file-layouts/default/main.journal view
@@ -0,0 +1,33 @@+; The main data file. Specify this with hledger's -f option or $LEDGER_FILE.+; Syntax: https://hledger.org/hledger.html#journal++; Declarations, helpful for reports and error checking,+; kept in their own files for easier maintenance.++include accounts.journal+include commodities.journal+include payees.journal+++; Opening balances. +; Pick a start date for this journal, some assets and liabilities to be tracked,+; and record their balances at the start of this day.++2026-01-01 opening balances+ assets:bank:checking $1000+ assets:cash $100+ liabilities:bank:credit card $-50.12+ equity:start++; Transactions. +; Keeping them all here is simplest; or you can keep them in subfiles and include those.+; Keeping them in date order allows extra error checking (hledger check ordereddates).++2026-01-02 received wages+ revenues:salary+ assets:bank:checking $1000++2026-01-03 Whole Foods | bought groceries+ assets:cash+ expenses:food $50+
+ embeddedfiles/file-layouts/default/payees.journal view
@@ -0,0 +1,15 @@+; Payee and/or description declarations - these provide+; auto-completions and can help detect errors, or act as a reference+; for standardising your transaction descriptions.+; You can also check payees/descriptions strictly, though most people don't.+; https://hledger.org/hledger.html#description-1+; https://hledger.org/hledger.html#payee-directive+; https://hledger.org/hledger.html#other-checks+++payee opening balances+payee closing balances++;payee Joe++;payee Whole Foods
+ embeddedfiles/file-layouts/default/prices/getprices view
@@ -0,0 +1,144 @@+#!/usr/bin/env bash+# getprices is a helper for hledger's `get` command (prices phase). You can also run it yourself.+# It is a simple, customisable front end for price-fetching tools like pricehist.+# It attempts to hide the variability between tools, price sources, and commodities,+# and allow for customisation, without hardcoding too much into hledger.+#+# Requires:+# https://github.com/chrisberkhout/pricehist+#+# See also:+# https://hledger.org/prices.html+# https://github.com/BittyTax/BittyTax/?tab=readme-ov-file#price-tool++usage() {+ cat <<EOF+getprices [-v] BASECUR COMM START [END]++Fetch daily historical prices for one commodity over a date range,+as hledger P directives, using pricehist by default.++Arguments:+ BASECUR ISO code of your base currency (eg USD, EUR), prices are quoted in this+ COMM ISO currency code or stock/cryptocurrency ticker (eg EUR, AAPL, BTC)+ START ISO start date (YYYY-MM-DD)+ END ISO end date (YYYY-MM-DD), inclusive (default: today)++Examples:++\$ getprices USD EUR 2026-01-01+\$ getprices USD EUR 2026-01-01 2026-12-31+\$ getprices -v USD BTC 2026-01-01++EOF+}++# Commodities to not fetch prices for, |-separated; customise as needed.+SKIPCOMMS="BAT|TCOIN"++################################################################################++set -uo pipefail++# ISO 4217 currency codes, copied from Hledger.Data.Currency.currencies.+CURRENCIES="+ ALL AFN ARS AWG AUD AZN BSD BBD BYN BZD BMD BOB BAM BWP BGN BRL BND+ KHR CAD KYD CLP CNY COP CRC HRK CUP CZK DKK DOP XCD EGP SVC EUR FKP+ FJD GHS GIP GTQ GGP GYD HNL HKD HUF ISK INR IDR IRR IMP ILS JMD JPY+ JEP KZT KPW KRW KGS LAK LBP LRD MKD MYR MUR MXN MNT MZN NAD NPR ANG+ NZD NIO NGN NOK OMR PKR PAB PYG PEN PHP PLN QAR RON RUB SHP SAR RSD+ SCR SGD SBD SOS ZAR LKR SEK CHF SRD SYP TWD THB TTD TRY TVD UAH GBP+ USD UYU UZS VEF VND YER ZWD+"++# Top 100 cryptocurrency tickers, copied from+# Hledger.Data.Currency.cryptocurrencies (CoinGecko snapshot 2026-04-30).+CRYPTOCURRENCIES="+ BTC ETH USDT XRP BNB USDC SOL TRX FIGR_HELOC DOGE WBT USDS HYPE LEO+ ADA BCH XMR LINK ZEC CC XLM USD1 DAI LTC M AVAX USDE HBAR RAIN SHIB+ SUI PYUSD TON CRO USYC XAUT USDG TAO BUIDL PAXG MNT UNI DOT WLFI SKY+ PI USDF OKB NEAR ASTER PEPE HTX USDD RLUSD AAVE BGB ICP USDY JTRSY+ BFUSD ETC ONDO MORPHO KCS U QNT POL EUTBL ALGO USTB BCAP ATOM ENA+ NEXO KAS RENDER APT GT WLD ARB JST STABLE FIL PUMP FLR PENGU BDX JUP+ OUSG VET XDC USDTB GHO HASH USD0 TRUMP BONK NIGHT DEXE YLDS+"++# Replace newlines with spaces so the lookup pattern below sees each+# code surrounded by whitespace, regardless of how the lists are wrapped.+CURRENCIES=${CURRENCIES//$'\n'/ }+CRYPTOCURRENCIES=${CRYPTOCURRENCIES//$'\n'/ }++isCurrency() {+ [[ "$CURRENCIES" == *" $1 "* ]]+}++isCryptocurrency() {+ [[ "$CRYPTOCURRENCIES" == *" $1 "* ]]+}++# Check for flags+while [ $# -gt 0 ]; do+ case "$1" in+ -h|--help)+ usage+ exit 0+ ;;+ *)+ break+ ;;+ esac+done++if [ $# -lt 3 ] || [ $# -gt 4 ]; then+ usage+ exit 1+fi++BASECUR=$1+COMM=$2+START=$3+END=${4:-$(date +%Y-%m-%d)}++# Skip if COMM is the base currency or one of the commodities to skip.+if [[ "$COMM" == "$BASECUR" || "$COMM" =~ ^($SKIPCOMMS)$ ]]; then+ exit 0+fi+++# Select an appropriate price provider and pair format.+# Customise as needed.++if isCurrency "$COMM"; then+ SOURCE="alphavantage"+ PAIR="$COMM/$BASECUR"++elif isCryptocurrency "$COMM"; then+ SOURCE="coinmarketcap"+ PAIR="$COMM/$BASECUR"++# other cases+elif [[ "$COMM" =~ ^(OMG)$ ]]; then+ SOURCE="coinmarketcap"+ PAIR="$COMM/$BASECUR"++# default+else+ SOURCE="yahoo"+ PAIR="$COMM"++fi++# Run pricehist to fetch prices in the date range, as P directives, and print them.+TMPFILE=$(mktemp)+trap 'rm -f "$TMPFILE"' EXIT+CMD="pricehist fetch -o ledger --fmt-time '' -s $START -e $END $SOURCE $PAIR | sed -e 's|[-/]$BASECUR||'"++# some providers work better with a delay+# echo "sleeping for 1" >&2+sleep 0.5++echo "$CMD" >&2+if ! eval "$CMD" 2>"$TMPFILE"; then+ sed -E 's/^(CRITICAL )?/error: /' "$TMPFILE" >&2+ exit 1+fi
+ embeddedfiles/file-layouts/default/rules/bankofireland-checking.csv.rules view
@@ -0,0 +1,25 @@+# bankofireland-checking.csv.rules++# skip the header line+skip++# name the csv fields, and assign some of them as journal entry fields+fields date, description, amount-out, amount-in, balance++# We generate balance assertions by assigning to "balance"+# above, but you may sometimes need to remove these because:+#+# - the CSV balance differs from the true balance, +# by up to 0.0000000000005 in my experience+#+# - it is sometimes calculated based on non-chronological ordering,+# eg when multiple transactions clear on the same day++# date is in UK/Ireland format+date-format %d/%m/%Y++# set the currency+currency EUR++# set the base account for all txns+account1 assets:bank:boi:checking
+ embeddedfiles/file-layouts/simple/main.journal view
@@ -0,0 +1,79 @@+; Everything in one file.+; Syntax: https://hledger.org/hledger.html#journal++; Optional declarations - uncomment these to make reports and https://hledger.org/hledger.html#check work better.+;+; ; COMMODITIES+; ; https://hledger.org/hledger.html#commodity-directive+;+; commodity $1000.00+; commodity 1000.00 EUR+; ;commodity 1 000 000,00 EUR ; https://hledger.org/hledger.html#commodity-display-style can be customised+; ; A lots: tag enables lots and capital gains tracking.+; commodity 1. AAPL ; lots:+; commodity 1.000000 ADA ; lots:+; commodity 1.00000000 BTC ; lots:+;+; ; ACCOUNTS+; ; https://hledger.org/hledger.html#account-directive+; ; The order of declarations also sets https://hledger.org/hledger.html#account-display-order.+; ; Lower case, unspaced account names are easiest to type, but use capitals/spaces if you prefer.+; ; https://hledger.org/hledger.html#account-names+;+; ; Top-level accounts and their https://hledger.org/hledger.html#account-types.+; account assets ; type:A+; account liabilities ; type:L+; account equity ; type:E+; account revenues ; type:R+; account expenses ; type:X+;+; ; Subaccounts/subcategories.+; account assets:bank:checking+; account assets:cash+; account assets:receivable+;+; account liabilities:bank:credit card+; account liabilities:payable+;+; account equity:start+; account equity:conversion+;+; account revenues:gifts+; account revenues:salary+; account revenues:consulting+; account revenues:gains+;+; account expenses:food+; account expenses:gifts+; account expenses:home+; account expenses:misc+; account expenses:online services+; account expenses:personal care+; account expenses:phone+; account expenses:recreation+; account expenses:transport+; account expenses:travel+; account expenses:utilities+++; Opening balances. +; Pick a start date for this journal, name some asset and liability accounts+; that you'll keep track of, and record their balances at the start of this day.++2026-01-01 opening balances+ assets:bank:checking $1000+ assets:cash $100+ liabilities:bank:credit card $-50.12+ equity:start++; Transactions. +; Keeping them in date order allows extra error checking (hledger check ordereddates).++2026-01-02 received wages+ revenues:salary+ assets:bank:checking $1000++2026-01-03 Whole Foods | bought groceries+ assets:cash+ expenses:food $50+
+ embeddedfiles/file-layouts/years/2026.journal view
@@ -0,0 +1,37 @@+; This year's journal. Use this file day to day: specify it with hledger's -f option or $LEDGER_FILE.+; For reports across several years, use all.journal.+; To start a new year, make a new YEAR.journal like this one, with that year's opening balances+; (https://hledger.org/hledger.html#close can generate them).+; Syntax: https://hledger.org/hledger.html#journal++; Declarations, helpful for reports and error checking,+; shared by all years and kept in their own files for easier maintenance.++include accounts.journal+include commodities.journal+include payees.journal+++; Opening balances.+; Record the balances of the assets and liabilities to be tracked, at the start of the year+; (or at a later start date, in your first year).+; The clopen tag helps hledger close generate next year's opening balances.++2026-01-01 opening balances+ ; clopen:2026+ assets:bank:checking $1000+ assets:cash $100+ liabilities:bank:credit card $-50.12+ equity:start++; Transactions.+; Keeping them in date order allows extra error checking (hledger check ordereddates).++2026-01-02 received wages+ revenues:salary+ assets:bank:checking $1000++2026-01-03 Whole Foods | bought groceries+ assets:cash+ expenses:food $50+
+ embeddedfiles/file-layouts/years/all.journal view
@@ -0,0 +1,5 @@+; All years' journals, for reports across several years.+; For day to day use, use this year's journal.+; Syntax: https://hledger.org/hledger.html#journal++include 2*.journal
+ embeddedfiles/hledger-accounts.md view
@@ -0,0 +1,36 @@+# hledger accounts++> List account names.+> More information: <https://hledger.org/hledger.html#accounts>.++- Show all accounts used or declared in the default journal file:++`hledger accounts`++- Show accounts used by transactions:++`hledger accounts --used`++- Show accounts declared with account directives:++`hledger accounts --declared`++- Add new account directives, for accounts used but not declared, to the journal:++`hledger accounts --undeclared --directives >> {{2024-accounts.journal}}`++- Show accounts with `asset` in their name, and their declared/inferred types:++`hledger accounts asset --types`++- Show accounts of the `Asset` type:++`hledger accounts type:A`++- Show the first two levels of the accounts hierarchy:++`hledger accounts --tree --depth 2`++- Short form of the above:++`hledger acc -t -2`
+ embeddedfiles/hledger-add.md view
@@ -0,0 +1,24 @@+# hledger add++> Record new transactions with interactive prompting in the console.+> More information: <https://hledger.org/hledger.html#add>.++- Record new transactions, saving to the default journal file:++`hledger add`++- Add transactions to `2024.journal`, but also load `2023.journal` for completions:++`hledger add --file {{path/to/2024.journal}} --file {{path/to/2023.journal}}`++- Provide answers for the first four prompts:++`hledger add {{today}} '{{best buy}}' {{expenses:supplies}} '{{$20}}'`++- Show `add`'s options and documentation with `$PAGER`:++`hledger add --help`++- Show `add`'s documentation with `info` or `man` if available:++`hledger help add`
+ embeddedfiles/hledger-aregister.md view
@@ -0,0 +1,20 @@+# hledger aregister++> Show the transactions and running balances in one account, with one entry per transaction.+> More information: <https://hledger.org/hledger.html#aregister>.++- Show transactions and running balance in the `assets:bank:checking` account:++`hledger aregister assets:bank:checking`++- Show transactions and running balance in the first account named `*savings*`:++`hledger aregister savings`++- Show the checking account's cleared transactions, with a specified width:++`hledger aregister checking --cleared --width {{120}}`++- Show the checking register, including transactions from forecast rules:++`hledger aregister checking --forecast`
+ embeddedfiles/hledger-balance.md view
@@ -0,0 +1,37 @@+# hledger balance++> A flexible, general purpose "summing" report that shows accounts with some kind of numeric data.+> This can be balance changes per period, end balances, budget performance, unrealised capital gains, etc.+> More information: <https://hledger.org/hledger.html#balance>.++- Show the balance change in all accounts from all postings over all time:++`hledger balance`++- Show the balance change in accounts named `*expenses*`, as a tree, summarising the top two levels only:++`hledger balance {{expenses}} --tree --depth {{2}}`++- Show expenses each month, and their totals and averages, sorted by total; and their monthly budget goals:++`hledger balance {{expenses}} --monthly --row-total --average --sort-amount --budget`++- Similar to the above, shorter form, matching accounts by `Expense` type, as a two level tree without squashing boring accounts:++`hledger bal type:{{X}} -MTAS --budget -t -{{2}} --no-elide`++- Show end balances (including from postings before the start date), quarterly in 2024, in accounts named `*assets*` or `*liabilities*`:++`hledger balance --historical --period '{{quarterly in 2024}}' {{assets}} {{liabilities}}`++- Similar to the above, shorter form; also show zero balances, sort by total and summarise to three levels:++`hledger bal -HQ date:{{2024}} type:{{AL}} -ES -{{3}}`++- Show investment assets' market value in base currency at the end of each quarter:++`hledger bal -HVQ {{assets:investments}}`++- Show unrealised capital gains/losses from market price changes in each quarter, for non-cryptocurrency investment assets:++`hledger bal --gain -Q {{assets:investments}} not:{{cryptocurrency}}`
+ embeddedfiles/hledger-balancesheet.md view
@@ -0,0 +1,33 @@+# hledger balancesheet++> Show the end balances in asset and liability accounts.+> Amounts are shown with normal positive sign, as in conventional financial statements.+> More information: <https://hledger.org/hledger.html#balancesheet>.++- Show the current balances in `Asset` and `Liability` accounts, excluding zeros:++`hledger balancesheet`++- Show just the liquid assets (`Cash` account type):++`hledger balancesheet type:C`++- Include accounts with zero balances, and show the account hierarchy:++`hledger balancesheet --empty --tree`++- Show the balances at the end of each month:++`hledger balancesheet --monthly`++- Show the balances' market value in home currency at the end of each month:++`hledger balancesheet --monthly -V`++- Show quarterly balances, with just the top two levels of account hierarchy:++`hledger balancesheet --quarterly --tree --depth 2`++- Short form of the above, and generate HTML output in `bs.html`:++`hledger bs -Qt -2 -o bs.html`
+ embeddedfiles/hledger-import.md view
@@ -0,0 +1,28 @@+# hledger import++> Import new transactions from one or more data files to the main journal.+> More information: <https://hledger.org/hledger.html#import>.++- Import new transactions from `bank.csv`, using `bank.csv.rules` to convert:++`hledger import {{path/to/bank.csv}}`++- Show what would be imported from these two files, without doing anything:++`hledger import {{path/to/bank1.csv}} {{path/to/bank2.csv}} --dry-run`++- Import new transactions from all CSV files, using the same rules for all:++`hledger import --rules {{common.rules}} *.csv`++- Show conversion errors or results while editing `bank.csv.rules`:++`watchexec -- hledger -f {{path/to/bank.csv}} print`++- Mark `bank.csv`'s current data as seen, as if already imported:++`hledger import --catchup {{path/to/bank.csv}}`++- Mark `bank.csv` as all new, as if not yet imported:++`rm -f .latest.bank.csv`
+ embeddedfiles/hledger-incomestatement.md view
@@ -0,0 +1,21 @@+# hledger incomestatement++> Show revenue inflows and expense outflows during the report period.+> Amounts are shown with normal positive sign, as in conventional financial statements.+> More information: <https://hledger.org/hledger.html#incomestatement>.++- Show revenues and expenses (changes in `Revenue` and `Expense` accounts):++`hledger incomestatement`++- Show revenues and expenses each month:++`hledger incomestatement --monthly`++- Show monthly revenues/expenses/totals, largest first, summarised to 2 levels:++`hledger incomestatement --monthly --row-total --average --sort --depth 2`++- Short form of the above, and generate HTML output in `is.html`:++`hledger is -MTAS -2 -o is.html`
+ embeddedfiles/hledger-print.md view
@@ -0,0 +1,32 @@+# hledger print++> Show full journal entries, representing transactions.+> More information: <https://hledger.org/hledger.html#print>.++- Show all transactions in the default journal file:++`hledger print`++- Show transactions, with any implied amounts or costs made explicit:++`hledger print --explicit --infer-costs`++- Show transactions from two specified files, with amounts converted to cost:++`hledger print --file {{path/to/2023.journal}} --file {{path/to/2024.journal}} --cost`++- Show `$` transactions in `*food*` but not `*groceries*` accounts this month:++`hledger print cur:\\$ food not:groceries date:thismonth`++- Show transactions of amount 50 or more, with `whole foods` in their description:++`hledger print amt:'>50' desc:'whole foods'`++- Show cleared transactions, with `EUR` amounts rounded and with decimal commas:++`hledger print --cleared --commodity '1000, EUR' --round hard`++- Write transactions from `foo.journal` as a CSV file:++`hledger print --file {{path/to/foo.journal}} --output-file {{path/to/output_file.csv}}`
+ embeddedfiles/hledger-ui.1 view
@@ -0,0 +1,529 @@++.TH "HLEDGER\-UI" "1" "December 2026" "hledger-ui-2.0 " "hledger User Manuals"++++.SH NAME+hledger\-ui \- terminal interface (TUI) for \f[CR]hledger\f[R], a+robust, friendly plain text accounting app.+.SH SYNOPSIS+\f[CR]hledger\-ui [OPTS] [QUERYARGS]\f[R]+.PD 0+.P+.PD+or+.PD 0+.P+.PD+\f[CR]hledger ui [OPTS] [QUERYARGS]\f[R]+.SH DESCRIPTION+This manual is for hledger\(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+tracking money, time, or any other commodity, using double\-entry+accounting and a simple, editable file format.+hledger is inspired by and largely compatible with ledger(1), and+largely interconvertible with beancount(1).+.PP+hledger\-ui is hledger\(aqs 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\(aqs command\-line interface, and sometimes+quicker and more convenient than the web interface.+.PP+Like hledger, it reads from (and appends to) a journal file specified by+the \f[CR]LEDGER_FILE\f[R] environment variable (defaulting to+\f[CR]$HOME/.hledger.journal\f[R]); or you can specify files with+\f[CR]\-f\f[R] options.+It can also read timeclock files, timedot files, or any CSV/SSV/TSV file+with a date field.+(See hledger(1) \-> Input for details.)+.PP+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+transactions, by pressing the F key (or starting with \-\-forecast) to+enable \(dqforecast mode\(dq.+.SH OPTIONS+Any arguments are interpreted as a hledger query which filters the data.+hledger\-ui provides the following options:+.IP+.EX+Flags:+ \-w \-\-watch watch for data and date changes and reload+ automatically (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+ \-\-bs start in the balance sheet accounts screen+ \-\-is start in the income statement accounts screen+ \-\-all start in the all accounts screen+ \-\-register=ACCTREGEX start in the (first matched) account\(aqs register+ \-\-change show period balances (changes) at startup instead+ of historical balances+ \-l \-\-flat show accounts as a flat list (default)+ \-t \-\-tree show accounts as a tree+.EE+.PP+hledger\-ui also supports many of hledger\(aqs general options:+.IP+.EX+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.+ \-\-alias=A=B|/RGX/=RPL transform account names from A to B, or by+ replacing regular expression matches+ \-\-auto generate extra postings by applying auto posting+ rules (\(dq=\(dq) to all transactions+ \-\-forecast[=PERIOD] Generate extra transactions from periodic rules+ (\(dq\(ti\(dq), from after the latest ordinary transaction+ until 6 months from now. Or, during the specified+ PERIOD (the equals is required). Auto posting rules+ will also be applied to these transactions. In+ hledger\-ui, also make future\-dated transactions+ visible at startup.+ \-\-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)++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 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)+ \-\-date2 match/use secondary dates instead (deprecated)+ \-U \-\-unmarked include only unmarked postings/transactions+ \-P \-\-pending include only pending postings/transactions+ \-C \-\-cleared include only cleared postings/transactions+ (\-U/\-P/\-C can be combined)+ \-R \-\-real include only non\-virtual postings+ \-E \-\-empty Show zero items, which are normally hidden.+ In hledger\-ui & hledger\-web, do the opposite.+ \-\-depth=DEPTHEXP if a number (or \-NUM): show only top NUM levels+ of accounts. If REGEXP=NUM, only apply limiting to+ accounts matching the regular expression.+ \-B \-\-cost 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? 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:+ \-? 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+a \f[CR]hledger\-ui.log\f[R] file in the current directory.+.PP+If you use the bash shell, you can auto\-complete flags by pressing TAB+in the command line.+If this is not working see Install > Shell completions.+.SH MOUSE+In most modern terminals, you can navigate through the screens with a+mouse or touchpad:+.IP \(bu 2+Use mouse wheel or trackpad to scroll up and down+.IP \(bu 2+Click on list items to go deeper+.IP \(bu 2+Click on the left margin (column 0) to go back.+.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.+\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.+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]+move up and down through lists.+\f[CR]J\f[R]/\f[CR]K\f[R] jump down/up 10 items at a time.+Emacs\-style+(\f[CR]CTRL\-p\f[R]/\f[CR]CTRL\-n\f[R]/\f[CR]CTRL\-f\f[R]/\f[CR]CTRL\-b\f[R])+and VI\-style (\f[CR]k\f[R],\f[CR]j\f[R],\f[CR]l\f[R],\f[CR]h\f[R])+movement keys are also supported.+.PP+(Tip: movement speed is limited by your keyboard repeat rate, to move+faster you may want to adjust it.+On a mac, the Karabiner app is one way to do that.)+.PP+\f[CR]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.+There are also keys for quickly adjusting some common filters like+account depth and transaction status (see below).+\f[CR]BACKSPACE\f[R] or \f[CR]DELETE\f[R] removes all filters, showing+all transactions.+.PP+As mentioned above, by default hledger\-ui hides future transactions \-+both ordinary transactions recorded in the journal, and periodic+transactions generated by rule.+\f[CR]F\f[R] toggles forecast mode, in which future/forecasted+transactions are shown.+.PP+Pressing \f[CR]SHIFT\-DOWN\f[R] narrows the report period, and pressing+\f[CR]SHIFT\-UP\f[R] expands it again.+When narrowed, the current report period is displayed in the header+line, pressing \f[CR]SHIFT\-LEFT\f[R] or \f[CR]SHIFT\-RIGHT\f[R] moves+to the previous or next period, and pressing \f[CR]T\f[R] sets the+period to \(dqtoday\(dq.+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.)+.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: 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 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.+This allows some basic data entry.+.PP+\f[CR]A\f[R] is like \f[CR]a\f[R], but runs the hledger\-iadd tool,+which provides a terminal interface.+This key will be available if \f[CR]hledger\-iadd\f[R] is installed in+\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], 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).+.PP+\f[CR]V\f[R] toggles value mode, showing amounts converted to their+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+(\f[CR]\-\-value=end\f[R]) on or off.+The valuation date will be the report end date if specified, otherwise+today.+.IP "2." 3+If you started hledger\-ui with some other valuation (such as+\f[CR]\-\-value=then,EUR\f[R]), the \f[CR]V\f[R] key toggles that off or+on.+.PP+Cost/value tips: \- When showing end value, you can change the report+end date without restarting, by pressing \f[CR]/\f[R] and adding a query+like \f[CR]date:..YYYY\-MM\-DD\f[R].+\- Either cost mode, or value mode, can be active, but not both at once.+Cost mode takes precedence.+\- There\(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+\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:+\f[CR]UP\f[R]/\f[CR]DOWN\f[R] to select, \f[CR]RIGHT\f[R] to move to the+selected screen, \f[CR]LEFT\f[R] to return to the previous screen.+Or you can use \f[CR]ESC\f[R] to return directly to the top menu screen.+.PP+You can also use a command line flag to 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+various types.+Note some of these may not show anything until you have configured+account types.+.SS Cash accounts screen+This screen shows \(dqcash\(dq (ie, liquid asset) accounts (like+\f[CR]hledger balancesheet type:c\f[R]).+It always shows balances (historical ending balances on the date shown+in the title line).+.SS Balance sheet accounts screen+This screen shows asset, liability and equity accounts (like+\f[CR]hledger balancesheetequity\f[R]).+It always shows balances.+.SS Income statement accounts screen+This screen shows revenue and expense accounts (like+\f[CR]hledger incomestatement\f[R]).+It always shows changes (balance changes in the period shown in the+title line).+.SS All accounts screen+This screen shows all accounts in your journal (unless filtered by a+query; like \f[CR]hledger balance\f[R]).+It shows balances by default; you can toggle showing changes with the+\f[CR]H\f[R] key.+.SS Register screen+This screen shows the transactions affecting a particular account.+Each line represents one transaction, and shows:+.IP \(bu 2+the other account(s) involved, in abbreviated form.+(If there are both real and virtual postings, it shows only the accounts+affected by real postings.)+.IP \(bu 2+the overall change to the current account\(aqs balance; positive for an+inflow to this account, negative for an outflow.+.IP \(bu 2+the running total after the transaction.+With the \f[CR]H\f[R] key you can toggle between+.RS 2+.IP \(bu 2+the period total, which is from just the transactions displayed+.IP \(bu 2+or the historical total, which includes any undisplayed transactions+before the start of the report period (and matching the filter query if+any).+This will be the running historical balance (what you would see on a+bank\(aqs website, eg) if not disturbed by a query.+.RE+.PP+Note, this screen combines each transaction\(aqs in\-period postings to+a single line item, dated with the earliest in\-period transaction or+posting date (like hledger\(aqs \f[CR]aregister\f[R]).+So custom posting dates can cause the running balance to be temporarily+inaccurate.+(See hledger manual > aregister and posting dates.)+.PP+Transactions affecting this account\(aqs subaccounts will be included in+the register if the accounts screen is in tree mode, or if it\(aqs in+list mode but this account has subaccounts which are not shown due to a+depth limit.+In other words, the register always shows the transactions contributing+to the balance shown on the accounts screen.+Tree mode/list mode can be toggled with \f[CR]t\f[R] here also.+.PP+\f[CR]U\f[R] toggles filtering by unmarked status, showing or hiding+unmarked transactions.+Similarly, \f[CR]P\f[R] toggles pending transactions, and \f[CR]C\f[R]+toggles cleared transactions.+(By default, transactions with all statuses are shown; if you activate+one or two status filters, only those transactions are shown; and if you+activate all three, the filter is removed.)+.PP+\f[CR]R\f[R] toggles real mode, in which virtual postings are ignored.+.PP+\f[CR]z\f[R] toggles nonzero mode, in which only transactions posting a+nonzero change are shown (hledger\-ui shows zero items by default,+unlike command\-line hledger).+.PP+Press \f[CR]RIGHT\f[R] to view the selected transaction in detail.+.SS Transaction screen+This screen shows a single transaction, as a general journal entry,+similar to hledger\(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.+Simple transactions have two postings, but there can be more (or in+certain cases, fewer).+.PP+\f[CR]UP\f[R] and \f[CR]DOWN\f[R] will step through all transactions+listed in the previous account register screen.+In the title bar, the numbers in parentheses show your position within+that account register.+They will vary depending on which account register you came from+(remember most transactions appear in multiple account registers).+The #N number preceding them is the transaction\(aqs position within the+complete unfiltered journal, which is a more stable id (at least until+the next reload).+.PP+On this screen (and the register screen), the \f[CR]E\f[R] key will open+your text editor with the cursor positioned at the current transaction+if possible.+.SS Error screen+This screen will appear if there is a problem, such as a parse error,+when you press g to reload.+Once you have fixed the problem, press g again to reload and resume+normal operation.+(Or, you can press escape to cancel the reload attempt.)+.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+hledger\-ui immediately shows the effect of any file changes, reloading+automatically.+(This is enabled by default since 1.99.5.)+.PP+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 a terminal window, eg:+.IP+.EX+$ hledger\-ui \-\-register checking \-C+.EE+.PP+As you mark things cleared in the editor, you can see the effect+immediately without having to context switch.+This leaves more mental bandwidth for your accounting.+Of course you can still interact with hledger\-ui when needed, eg to+toggle cleared mode, or to explore the history.+.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+(https://hledger.org/support).+.PP+Some known issues:+.PP+If reloading large files on a slow computer, there could be a noticeable+pause, during which the UI is unresponsive.+++.SH AUTHORS+Simon Michael <simon@joyful.com> and contributors.+.br+See http://hledger.org/CREDITS.html++.SH COPYRIGHT+Copyright 2007-2023 Simon Michael and contributors.++.SH LICENSE+Released under GNU GPL v3 or later.++.SH SEE ALSO+hledger(1), hledger\-ui(1), hledger\-web(1), ledger(1)
+ embeddedfiles/hledger-ui.info view
@@ -0,0 +1,626 @@+This is hledger-ui.info, produced by makeinfo version 7.3 from stdin.++INFO-DIR-SECTION User Applications+START-INFO-DIR-ENTRY+* hledger-ui: (hledger-ui). Terminal UI for the hledger accounting tool.+END-INFO-DIR-ENTRY+++File: hledger-ui.info, Node: Top, Next: OPTIONS, Up: (dir)++hledger-ui(1)+*************++hledger-ui - terminal interface (TUI) for 'hledger', a robust, friendly+plain text accounting app.++ 'hledger-ui [OPTS] [QUERYARGS]'+or+'hledger ui [OPTS] [QUERYARGS]'++ This manual is for hledger's terminal interface, version 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 tracking money, time, or any other commodity, using double-entry+accounting and a simple, editable file format. hledger is inspired by+and largely compatible with ledger(1), and largely interconvertible with+beancount(1).++ hledger-ui is hledger's terminal interface, providing an efficient+full-window text UI for viewing accounts and transactions, and some+limited data entry capability. It is easier than hledger's command-line+interface, and sometimes quicker and more convenient than the web+interface.++ Like hledger, it reads from (and appends to) a journal file specified+by the 'LEDGER_FILE' environment variable (defaulting to+'$HOME/.hledger.journal'); or you can specify files with '-f' options.+It can also read timeclock files, timedot files, or any CSV/SSV/TSV file+with a date field. (See hledger(1) -> Input for details.)++ 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".++* Menu:++* OPTIONS::+* MOUSE::+* KEYS::+* SCREENS::+* WATCH MODE::+* ENVIRONMENT::+* BUGS::+++File: hledger-ui.info, Node: OPTIONS, Next: MOUSE, Prev: Top, Up: Top++1 OPTIONS+*********++Any arguments are interpreted as a hledger query which filters the data.+hledger-ui provides the following options:++Flags:+ -w --watch watch for data and date changes and reload+ automatically (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+ --bs start in the balance sheet accounts screen+ --is start in the income statement accounts screen+ --all start in the all accounts screen+ --register=ACCTREGEX start in the (first matched) account's register+ --change show period balances (changes) at startup instead+ of historical balances+ -l --flat show accounts as a flat list (default)+ -t --tree show accounts as a tree++ hledger-ui also supports many of hledger's general options:++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.+ --alias=A=B|/RGX/=RPL transform account names from A to B, or by+ replacing regular expression matches+ --auto generate extra postings by applying auto posting+ rules ("=") to all transactions+ --forecast[=PERIOD] Generate extra transactions from periodic rules+ ("~"), from after the latest ordinary transaction+ until 6 months from now. Or, during the specified+ PERIOD (the equals is required). Auto posting rules+ will also be applied to these transactions. In+ hledger-ui, also make future-dated transactions+ visible at startup.+ --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)++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 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)+ --date2 match/use secondary dates instead (deprecated)+ -U --unmarked include only unmarked postings/transactions+ -P --pending include only pending postings/transactions+ -C --cleared include only cleared postings/transactions+ (-U/-P/-C can be combined)+ -R --real include only non-virtual postings+ -E --empty Show zero items, which are normally hidden.+ In hledger-ui & hledger-web, do the opposite.+ --depth=DEPTHEXP if a number (or -NUM): show only top NUM levels+ of accounts. If REGEXP=NUM, only apply limiting to+ accounts matching the regular expression.+ -B --cost 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? 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:+ -? 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.++ If you use the bash shell, you can auto-complete flags by pressing+TAB in the command line. If this is not working see Install > Shell+completions.+++File: hledger-ui.info, Node: MOUSE, Next: KEYS, Prev: OPTIONS, Up: Top++2 MOUSE+*******++In most modern terminals, you can navigate through the screens with a+mouse or touchpad:++ * Use mouse wheel or trackpad to scroll up and down+ * Click on list items to go deeper+ * Click on the left margin (column 0) to go back.++ 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. '?' 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.++ The following keys work on most screens. Additional screen-specific+keys are described under SCREENS below.++* 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.)++ '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.++ As mentioned above, by default hledger-ui hides future transactions -+both ordinary transactions recorded in the journal, and periodic+transactions generated by rule. 'F' toggles forecast mode, in which+future/forecasted transactions are shown.++ Pressing 'SHIFT-DOWN' narrows the report period, and pressing+'SHIFT-UP' expands it again. When narrowed, the current report period+is displayed in the header line, pressing 'SHIFT-LEFT' or 'SHIFT-RIGHT'+moves to the previous or next period, and pressing 'T' sets the period+to "today". If you are 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: 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'.)+++File: hledger-ui.info, Node: Other keys, Prev: Filtering keys, Up: KEYS++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+pause.)++ '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'.++ '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).++ 'V' toggles value mode, showing amounts converted to their market+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+ specified, otherwise today.++ 2. If you started hledger-ui with some other valuation (such as+ '--value=then,EUR'), the 'V' key toggles that off or on.++ Cost/value tips: - When showing end value, you can change the report+end date without restarting, by pressing '/' and adding a query like+'date:..YYYY-MM-DD'. - Either cost mode, or value mode, can be active,+but not both at once. Cost mode takes precedence. - There's not yet+any visual indicator that cost or value mode is active, other than the+amount values.++ '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.++ '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++4 SCREENS+*********++At startup, hledger-ui shows a menu screen by default. From here you+can navigate to other screens using the cursor keys: 'UP'/'DOWN' to+select, 'RIGHT' to move to the selected screen, 'LEFT' to return to the+previous screen. Or you can use 'ESC' to return directly to the top+menu screen.++ You can also use a command line flag to 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::+* Cash accounts screen::+* Balance sheet accounts screen::+* Income statement accounts screen::+* All accounts screen::+* Register screen::+* Transaction screen::+* Error screen::+++File: hledger-ui.info, Node: Menu screen, Next: Cash accounts screen, Up: SCREENS++4.1 Menu screen+===============++This is the top-most screen. From here you can navigate to several+screens listing accounts of various types. Note some of these may not+show anything until you have configured account types.+++File: hledger-ui.info, Node: Cash accounts screen, Next: Balance sheet accounts screen, Prev: Menu screen, Up: SCREENS++4.2 Cash accounts screen+========================++This screen shows "cash" (ie, liquid asset) accounts (like 'hledger+balancesheet type:c'). It always shows balances (historical ending+balances on the date shown in the title line).+++File: hledger-ui.info, Node: Balance sheet accounts screen, Next: Income statement accounts screen, Prev: Cash accounts screen, Up: SCREENS++4.3 Balance sheet accounts screen+=================================++This screen shows asset, liability and equity accounts (like 'hledger+balancesheetequity'). It always shows balances.+++File: hledger-ui.info, Node: Income statement accounts screen, Next: All accounts screen, Prev: Balance sheet accounts screen, Up: SCREENS++4.4 Income statement accounts screen+====================================++This screen shows revenue and expense accounts (like 'hledger+incomestatement'). It always shows changes (balance changes in the+period shown in the title line).+++File: hledger-ui.info, Node: All accounts screen, Next: Register screen, Prev: Income statement accounts screen, Up: SCREENS++4.5 All accounts screen+=======================++This screen shows all accounts in your journal (unless filtered by a+query; like 'hledger balance'). It shows balances by default; you can+toggle showing changes with the 'H' key.+++File: hledger-ui.info, Node: Register screen, Next: Transaction screen, Prev: All accounts screen, Up: SCREENS++4.6 Register screen+===================++This screen shows the transactions affecting a particular account. Each+line represents one transaction, and shows:++ * the other account(s) involved, in abbreviated form. (If there are+ both real and virtual postings, it shows only the accounts affected+ by real postings.)++ * the overall change to the current account's balance; positive for+ an inflow to this account, negative for an outflow.++ * the running total after the transaction. With the 'H' key you can+ toggle between++ * the period total, which is from just the transactions+ displayed+ * or the historical total, which includes any undisplayed+ transactions before the start of the report period (and+ matching the filter query if any). This will be the running+ historical balance (what you would see on a bank's website,+ eg) if not disturbed by a query.++ Note, this screen combines each transaction's in-period postings to a+single line item, dated with the earliest in-period transaction or+posting date (like hledger's 'aregister'). So custom posting dates can+cause the running balance to be temporarily inaccurate. (See hledger+manual > aregister and posting dates.)++ Transactions affecting this account's subaccounts will be included in+the register if the accounts screen is in tree mode, or if it's in list+mode but this account has subaccounts which are not shown due to a depth+limit. In other words, the register always shows the transactions+contributing to the balance shown on the accounts screen. Tree+mode/list mode can be toggled with 't' here also.++ 'U' toggles filtering by unmarked status, showing or hiding unmarked+transactions. Similarly, 'P' toggles pending transactions, and 'C'+toggles cleared transactions. (By default, transactions with all+statuses are shown; if you activate one or two status filters, only+those transactions are shown; and if you activate all three, the filter+is removed.)++ 'R' toggles real mode, in which virtual postings are ignored.++ 'z' toggles nonzero mode, in which only transactions posting a+nonzero change are shown (hledger-ui shows zero items by default, unlike+command-line hledger).++ Press 'RIGHT' to view the selected transaction in detail.+++File: hledger-ui.info, Node: Transaction screen, Next: Error screen, Prev: Register screen, Up: SCREENS++4.7 Transaction screen+======================++This screen shows a single transaction, as a general journal entry,+similar to hledger's print command and journal format.++ The transaction's date(s) and any cleared flag, transaction code,+description, comments, along with all of its account postings are shown.+Simple transactions have two postings, but there can be more (or in+certain cases, fewer).++ 'UP' and 'DOWN' will step through all transactions listed in the+previous account register screen. In the title bar, the numbers in+parentheses show your position within that account register. They will+vary depending on which account register you came from (remember most+transactions appear in multiple account registers). The #N number+preceding them is the transaction's position within the complete+unfiltered journal, which is a more stable id (at least until the next+reload).++ On this screen (and the register screen), the 'E' key will open your+text editor with the cursor positioned at the current transaction if+possible.+++File: hledger-ui.info, Node: Error screen, Prev: Transaction screen, Up: SCREENS++4.8 Error screen+================++This screen will appear if there is a problem, such as a parse error,+when you press g to reload. Once you have fixed the problem, press g+again to reload and resume normal operation. (Or, you can press escape+to cancel the reload attempt.)++ 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+************++hledger-ui immediately shows the effect of any file changes, reloading+automatically. (This is enabled by default since 1.99.5.)++ 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.++ 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.+++File: hledger-ui.info, Node: ENVIRONMENT, Next: BUGS, Prev: WATCH MODE, Up: Top++6 ENVIRONMENT+*************++*LEDGER_FILE* The main journal file to use when not specified with+'-f/--file'. Default: '$HOME/.hledger.journal'.++ *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++7 BUGS+******++We welcome bug reports in the hledger issue tracker+(https://bugs.hledger.org), or on the hledger chat or mail list+(https://hledger.org/support).++ Some known issues:++ 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: 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+++Local Variables:+coding: utf-8+End:
+ embeddedfiles/hledger-ui.md view
@@ -0,0 +1,32 @@+# hledger-ui++> A terminal interface (TUI) for `hledger`, a robust, friendly plain text accounting app.+> More information: <https://hledger.org/hledger-ui.html>.++- Start in the main menu screen, reading from the default journal file:++`hledger-ui`++- Start with a different color theme:++`hledger-ui --theme {{terminal|greenterm|dark}}`++- Start in the balance sheet accounts screen, showing hierarchy down to level 3:++`hledger-ui --bs --tree --depth 3`++- Start in this account's screen, showing cleared transactions, and reload on change:++`hledger-ui --register {{assets:bank:checking}} --cleared --watch`++- Read two journal files, and show amounts as current value when known:++`hledger-ui --file {{path/to/2024.journal}} --file {{path/to/2024-prices.journal}} --value now`++- Show the manual in Info format, if possible:++`hledger-ui --info`++- Display help:++`hledger-ui --help`
+ embeddedfiles/hledger-ui.txt view
@@ -0,0 +1,477 @@++HLEDGER-UI(1) hledger User Manuals HLEDGER-UI(1)++NAME+ hledger-ui - terminal interface (TUI) for hledger, a robust, friendly plain+ text accounting app.++SYNOPSIS+ hledger-ui [OPTS] [QUERYARGS]+ or+ hledger ui [OPTS] [QUERYARGS]++DESCRIPTION+ This manual is for hledger's terminal interface, version 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+ tracking money, time, or any other commodity, using double-entry accounting+ and a simple, editable file format. hledger is inspired by and largely+ compatible with ledger(1), and largely interconvertible with beancount(1).++ hledger-ui is hledger's terminal interface, providing an efficient+ full-window text UI for viewing accounts and transactions, and some limited+ data entry capability. It is easier than hledger's command-line interface,+ and sometimes quicker and more convenient than the web interface.++ Like hledger, it reads from (and appends to) a journal file specified by+ the LEDGER_FILE environment variable (defaulting to $HOME/.hledger.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+ 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 enable "forecast+ mode".++OPTIONS+ Any arguments are interpreted as a hledger query which filters the data.+ hledger-ui provides the following options:++ Flags:+ -w --watch watch for data and date changes and reload+ automatically (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+ --bs start in the balance sheet accounts screen+ --is start in the income statement accounts screen+ --all start in the all accounts screen+ --register=ACCTREGEX start in the (first matched) account's register+ --change show period balances (changes) at startup instead+ of historical balances+ -l --flat show accounts as a flat list (default)+ -t --tree show accounts as a tree++ hledger-ui also supports many of hledger's general options:++ 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.+ --alias=A=B|/RGX/=RPL transform account names from A to B, or by+ replacing regular expression matches+ --auto generate extra postings by applying auto posting+ rules ("=") to all transactions+ --forecast[=PERIOD] Generate extra transactions from periodic rules+ ("~"), from after the latest ordinary transaction+ until 6 months from now. Or, during the specified+ PERIOD (the equals is required). Auto posting rules+ will also be applied to these transactions. In+ hledger-ui, also make future-dated transactions+ visible at startup.+ --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)++ 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 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)+ --date2 match/use secondary dates instead (deprecated)+ -U --unmarked include only unmarked postings/transactions+ -P --pending include only pending postings/transactions+ -C --cleared include only cleared postings/transactions+ (-U/-P/-C can be combined)+ -R --real include only non-virtual postings+ -E --empty Show zero items, which are normally hidden.+ In hledger-ui & hledger-web, do the opposite.+ --depth=DEPTHEXP if a number (or -NUM): show only top NUM levels+ of accounts. If REGEXP=NUM, only apply limiting to+ accounts matching the regular expression.+ -B --cost 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? 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:+ -? 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.++ 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+ In most modern terminals, you can navigate through the screens with a mouse+ or touchpad:++ * Use mouse wheel or trackpad to scroll up and down++ * Click on list items to go deeper++ * Click on the left margin (column 0) to go back.++ 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. ? 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.++ The following keys work on most screens. Additional screen-specific keys+ are described under SCREENS below.++ 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.)++ 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).++ 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 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: 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 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 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,+ 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).++ V toggles value mode, showing amounts converted to their market 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 specified, otherwise+ today.++ 2. If you started hledger-ui with some other valuation (such as+ --value=then,EUR), the V key toggles that off or on.++ Cost/value tips: - When showing end value, you can change the report end+ date without restarting, by pressing / and adding a query like+ date:..YYYY-MM-DD. - Either cost mode, or value mode, can be active, but+ not both at once. Cost mode takes precedence. - There's not yet any vi-+ sual indicator that cost or value mode is active, other than the amount+ values.++ 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.++ 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+ you can use ESC to return directly to the top menu screen.++ 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-+ thing until you have configured account types.++ Cash accounts screen+ This screen shows "cash" (ie, liquid asset) accounts (like hledger bal-+ ancesheet type:c). It always shows balances (historical ending balances on+ the date shown in the title line).++ Balance sheet accounts screen+ This screen shows asset, liability and equity accounts (like hledger bal-+ ancesheetequity). It always shows balances.++ Income statement accounts screen+ This screen shows revenue and expense accounts (like hledger incomestate-+ ment). It always shows changes (balance changes in the period shown in the+ title line).++ All accounts screen+ This screen shows all accounts in your journal (unless filtered by a query;+ like hledger balance). It shows balances by default; you can toggle show-+ ing changes with the H key.++ Register screen+ This screen shows the transactions affecting a particular account. Each+ line represents one transaction, and shows:++ * the other account(s) involved, in abbreviated form. (If there are both+ real and virtual postings, it shows only the accounts affected by real+ postings.)++ * the overall change to the current account's balance; positive for an in-+ flow to this account, negative for an outflow.++ * the running total after the transaction. With the H key you can toggle+ between++ * the period total, which is from just the transactions displayed++ * or the historical total, which includes any undisplayed transactions+ before the start of the report period (and matching the filter query if+ any). This will be the running historical balance (what you would see+ on a bank's website, eg) if not disturbed by a query.++ Note, this screen combines each transaction's in-period postings to a sin-+ gle line item, dated with the earliest in-period transaction or posting+ date (like hledger's aregister). So custom posting dates can cause the+ running balance to be temporarily inaccurate. (See hledger manual > areg-+ ister and posting dates.)++ Transactions affecting this account's subaccounts will be included in the+ register if the accounts screen is in tree mode, or if it's in list mode+ but this account has subaccounts which are not shown due to a depth limit.+ In other words, the register always shows the transactions contributing to+ the balance shown on the accounts screen. Tree mode/list mode can be tog-+ gled with t here also.++ U toggles filtering by unmarked status, showing or hiding unmarked transac-+ tions. Similarly, P toggles pending transactions, and C toggles cleared+ transactions. (By default, transactions with all statuses are shown; if+ you activate one or two status filters, only those transactions are shown;+ and if you activate all three, the filter is removed.)++ R toggles real mode, in which virtual postings are ignored.++ z toggles nonzero mode, in which only transactions posting a nonzero change+ are shown (hledger-ui shows zero items by default, unlike command-line+ hledger).++ Press RIGHT to view the selected transaction in detail.++ Transaction screen+ This screen shows a single transaction, as a general journal entry, similar+ 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+ transactions have two postings, but there can be more (or in certain cases,+ fewer).++ UP and DOWN will step through all transactions listed in the previous ac-+ count register screen. In the title bar, the numbers in parentheses show+ your position within that account register. They will vary depending on+ which account register you came from (remember most transactions appear in+ multiple account registers). The #N number preceding them is the transac-+ tion's position within the complete unfiltered journal, which is a more+ stable id (at least until the next reload).++ On this screen (and the register screen), the E key will open your text ed-+ itor with the cursor positioned at the current transaction if possible.++ Error screen+ This screen will appear if there is a problem, such as a parse error, when+ you press g to reload. Once you have fixed the problem, press g again to+ reload and resume normal operation. (Or, you can press escape to cancel+ the reload attempt.)++ 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+ hledger-ui immediately shows the effect of any file changes, reloading au-+ tomatically. (This is enabled by default since 1.99.5.)++ 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.++ 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.++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://hledger.org/support).++ Some known issues:++ If reloading large files on a slow computer, there could be a noticeable+ pause, during which the UI is unresponsive.++++AUTHORS+ Simon Michael <simon@joyful.com> and contributors.+ See http://hledger.org/CREDITS.html+++COPYRIGHT+ Copyright 2007-2023 Simon Michael and contributors.+++LICENSE+ Released under GNU GPL v3 or later.+++SEE ALSO+ hledger(1), hledger-ui(1), hledger-web(1), ledger(1)++hledger-ui-2.0 December 2026 HLEDGER-UI(1)
+ embeddedfiles/hledger-web.1 view
@@ -0,0 +1,1045 @@++.TH "HLEDGER\-WEB" "1" "December 2026" "hledger-web-2.0 " "hledger User Manuals"++++.SH NAME+hledger\-web \- web interface and API for \f[CR]hledger\f[R], a robust,+friendly plain text accounting app.+.SH SYNOPSIS+\f[CR]hledger\-web [OPTS] [QUERY]\f[R]+.PD 0+.P+.PD+or+.PD 0+.P+.PD+\f[CR]hledger web [OPTS] [QUERY]\f[R]+.SH DESCRIPTION+This manual is for hledger\(aqs web 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+tracking money, time, or any other commodity, using double\-entry+accounting and a simple, editable file format.+hledger is inspired by and largely compatible with ledger(1), and+largely interconvertible with beancount(1).+.PP+hledger\-web is hledger\(aqs web interface.+In a web browser, it shows the journal, account registers, and the main+financial reports with their charts, and lets you search them, add+transactions, and (if allowed) edit the journal files.+It shows more at once than the hledger CLI or hledger\-ui (eg the+accounts beside a register, or a report\(aqs chart above its table), and+every view has its own url, so it can be bookmarked or shared.+.PP+hledger\-web also lets you share a journal with multiple users, or even+the public web.+There is no user authentication, so if you need that you should put it+behind a suitable web proxy (see Permissions).+.PP+Like hledger, it reads from (and appends to) a journal file specified by+the \f[CR]LEDGER_FILE\f[R] environment variable (defaulting to+\f[CR]$HOME/.hledger.journal\f[R]); or you can specify files with+\f[CR]\-f\f[R] options.+It can also read timeclock files, timedot files, or any CSV/SSV/TSV file+with a date field.+(See hledger(1) \-> Input for details.)+.PP+hledger\-web can be run in three modes:+.IP \(bu 2+\f[CR]\-\-serve\-browse\f[R] mode (the default): the app serves the web+UI and JSON API, and opens your default web browser to show the app if+possible, and exits automatically once no browser window has shown it+for fifteen minutes.+.IP \(bu 2+\f[CR]\-\-serve\f[R]: the app just serves the web UI and JSON API.+.IP \(bu 2+\f[CR]\-\-serve\-api\f[R]: the app just serves the JSON API.+.PP+In all cases hledger\-web runs as a foreground process, logging requests+to stdout.+.SH OPTIONS+hledger\-web provides the following command line options:+.IP+.EX+Flags:+ \-\-serve\-browse server mode: serve the web UI and JSON API,+ and open a browser, and exit if inactive for 15m+ (default)+ \-\-serve server mode: just serve the web UI and JSON+ API+ \-\-serve\-api server mode: just serve the JSON API+ \-\-allow=view|add|edit set the user\(aqs access level for changing data+ (default: \(gaadd\(ga on a local\-only address, \(gaview\(ga+ otherwise). It also accepts \(gasandstorm\(ga for that+ platform (reading from the+ \(gaX\-Sandstorm\-Permissions\(ga request header).+ \-\-cors=ORIGIN allow cross\-origin requests from the specified+ origin; setting ORIGIN to \(dq*\(dq allows requests+ from any origin+ \-\-host=IPADDR listen on this IP address (default: 127.0.0.1)+ \-\-port=PORT listen on this TCP port (default: 5000); 0+ means a free port chosen by the OS+ \-\-socket=SOCKET listen on the given unix socket instead of an+ IP address and port (only on unix)+ \-\-base\-url=BASEURL set the base url (default: http://IPADDR:PORT)+ \-\-chart[=KIND,net,SCALE] set the charts\(aq defaults, as the commands\(aq+ \-\-chart does. KIND: lay out the statements\(aq+ charts with each period\(aqs sections in one bar,+ above and below zero (diverging, the default),+ or side by side (grouped). net: show the net+ total lines by default (the N key toggles them,+ and the browser remembers that). SCALE: the+ amount that fills the charts (eg 1000 or 1000+ USD; one per commodity), for comparable charts.+ \-\-lang=LANG show the web UI in this language (en, de, es,+ ru, zh); or with auto, use each viewer\(aqs browser+ language if available, otherwise the server\(aqs.+ (Default: the browser\(aqs language if available,+ otherwise en.)+.EE+.PP+By default hledger\-web listens only on IP address \f[CR]127.0.0.1\f[R],+which can be accessed only from the local machine.+.PP+To allow access from elsewhere, use \f[CR]\-\-host\f[R] to specify an+externally accessible address configured on this machine.+The special address \f[CR]0.0.0.0\f[R] causes it to listen on all of+this machine\(aqs addresses.+.PP+Similarly, you can use \f[CR]\-\-port\f[R] to listen on a TCP port other+than 5000.+This is useful if you want to run multiple hledger\-web instances on a+machine.+\f[CR]\-\-port 0\f[R] makes the operating system choose a free port,+which is reported in the startup message and in the default base url,+and is where the browser is opened in \f[CR]\-\-serve\-browse\f[R] mode.+This can be useful eg when scripting.+.PP+When \f[CR]\-\-socket\f[R] is used, hledger\-web creates and+communicates via a socket file instead of a TCP port.+This can be more secure, respects unix file permissions, and makes+certain use cases easier, such as running per\-user instances behind an+nginx reverse proxy.+(Eg:+\f[CR]proxy_pass http://unix:/tmp/hledger/${remote_user}.socket;\f[R].)+.PP+You can use \f[CR]\-\-base\-url\f[R] to change the protocol, hostname,+port and path that appear in hledger\-web\(aqs hyperlinks.+This is useful eg when integrating hledger\-web within a larger website.+The default is \f[CR]http://HOST:PORT/\f[R] using the server\(aqs+configured host address and TCP port (or \f[CR]http://HOST\f[R] if PORT+is 80).+Note this affects url generation but not route parsing.+.PP+hledger\-web also supports many of hledger\(aqs general options:+.IP+.EX+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.+ \-\-alias=A=B|/RGX/=RPL transform account names from A to B, or by+ replacing regular expression matches+ \-\-auto generate extra postings by applying auto posting+ rules (\(dq=\(dq) to all transactions+ \-\-forecast[=PERIOD] Generate extra transactions from periodic rules+ (\(dq\(ti\(dq), from after the latest ordinary transaction+ until 6 months from now. Or, during the specified+ PERIOD (the equals is required). Auto posting rules+ will also be applied to these transactions. In+ hledger\-ui, also make future\-dated transactions+ visible at startup.+ \-\-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)++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 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)+ \-\-date2 match/use secondary dates instead (deprecated)+ \-U \-\-unmarked include only unmarked postings/transactions+ \-P \-\-pending include only pending postings/transactions+ \-C \-\-cleared include only cleared postings/transactions+ (\-U/\-P/\-C can be combined)+ \-R \-\-real include only non\-virtual postings+ \-E \-\-empty Show zero items, which are normally hidden.+ In hledger\-ui & hledger\-web, do the opposite.+ \-\-depth=DEPTHEXP if a number (or \-NUM): show only top NUM levels+ of accounts. If REGEXP=NUM, only apply limiting to+ accounts matching the regular expression.+ \-B \-\-cost 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? 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:+ \-? 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+ \-\-test[=PATTERN] run built\-in tests (those matching PATTERN) and+ exit+ \-\-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)+.EE+.PP+Some of these can be adjusted while hledger\-web is running, in the web+UI\(aqs Options panel.+.PP+hledger\-web shows accounts with zero balances by default (like+\f[CR]hledger\-ui\f[R], and unlike \f[CR]hledger\f[R]);+\f[CR]\-E/\-\-empty\f[R] starts it with them hidden instead.+In the web UI, the Zero balances option or the \f[CR]z\f[R] key shows or+hides them.+(The holdings page differs: its closed positions are hidden by default,+as in the \f[CR]holdings\f[R] command; \f[CR]\-E\f[R] starts it with+them shown, and \f[CR]z\f[R] there shows or hides them.)+.PP+Report options and a query given at startup set the view hledger\-web+opens with, by putting them in its url (see URL parameters).+Eg \f[CR]hledger\-web \-V \-M\f[R] opens+\f[CR]/balancesheet?interval=monthly&value=end\f[R], and+\f[CR]hledger\-web \-\-cleared \-3 assets\f[R] opens+\f[CR]/balancesheet?q=assets status:*&depth=3\f[R].+They are only a starting point: they can be changed in the web UI, and+they don\(aqt affect other urls or the JSON API.+Report options that hledger\-web has no equivalent for are ignored.+.PP+Note, a startup query doesn\(aqt restrict what hledger\-web serves; to+do that, give it a file holding only the entries to serve (eg one+written by \f[CR]hledger print QUERY\f[R]).+.PP+If you use the bash shell, you can auto\-complete flags by pressing TAB+in the command line.+If this is not working see Install > Shell completions.+.SH WEB UI+hledger\-web\(aqs main views are:+.IP \(bu 2+the \f[B]journal view\f[R], showing journal entries, newest first, with+their postings+.IP \(bu 2+the \f[B]report views\f[R], described below: the balance sheet, income+statement, cashflow statement (and holdings, for journals using lots),+and All accounts report+.IP \(bu 2+a \f[B]register view\f[R] for each account, reached by clicking an+account name, showing the transactions affecting that account (and its+subaccounts), with a running balance and a balance chart.+.PP+Every page has, from the top: links to the journal and the reports, the+search form, the options, and then the view itself.+The options are hidden until you open them (click Options, or press+\f[CR]o\f[R]); while hidden, they list the ones in effect, eg+\(dqMonthly · Depth 2 · Tree\(dq.+.PP+The journal and register show the newest 1000 matching transactions,+with links to older and newer pages.+When the transactions span more than one year, the options include a row+of years, to narrow the view to one year; shift\-click a second year to+select a range of years.+.PP+The register\(aqs chart shows the running balance over the page\(aqs+transactions.+With several commodities, use the legend, or the \f[CR][\f[R] and+\f[CR]]\f[R] keys, to choose the one charted.+Click a point to go to its transaction, or drag across the chart to see+the transactions of those dates.+The register\(aqs Costs option shows the costs recorded with its+amounts.+.PP+The \f[B]sidebar\f[R] lists every account, and optionally their balances+(parent balances include subaccounts).+The search doesn\(aqt change it, except that its dates set the+balances\(aq date.+The balances are hidden at first, since on a large journal they take+much of each page\(aqs time; click the \(dqBalances\(dq heading above+the accounts to show them, or to hide them again.+These are historical balances, as of the end of the report period set by+date:, otherwise the latest (the heading shows the date).+While the balances are hidden, all accounts are listed, even with Zero+balances: Hidden.+It is always a tree, with carets that fold and open each group, whether+the Accounts option is List or Tree.+The − and + above it fold or open a level of the whole tree, without+changing the page; its depth is its own, apart from the page\(aqs depth+limit.+The browser remembers the sidebar\(aqs depth and the groups you open or+close (until the next − or +).+The button at the top left (or the \f[CR]s\f[R] key) shows or hides the+sidebar, and it stays the way you left it from page to page.+On a narrow screen, it slides the sidebar in or out.+.PP+Click an account name to see its register, with the search, or an amount+to see the transactions it is made of.+In the journal and register, click a date to see that day\(aqs journal+entries.+.PP+The \f[B]search form\f[R] filters every view with hledger\(aqs query+syntax, eg \f[CR]expenses date:thismonth\f[R]; the help dialog+summarises the query types.+The search and the options are part of the page\(aqs url (see URL+parameters).+.PP+The \f[B]add form\f[R] (press \f[CR]a\f[R], or click \(dqAdd a+transaction\(dq in the journal view) adds a transaction to the main+journal file, if the access level allows it, and if the journal would+still be readable with it added (see Editing, uploading, downloading).+It autocompletes account names and descriptions from your existing+entries.+.PP+The \f[B]help dialog\f[R] (press \f[CR]?\f[R], or click the question+mark button) lists these keyboard shortcuts, which work when you are not+typing in a field:+.IP \(bu 2+\f[CR]h\f[R] or \f[CR]?\f[R] \- show or hide the help dialog+.IP \(bu 2+\f[CR]g\f[R] \- go to another page: shows a menu of the pages, each with+its key; then \f[CR]j\f[R] journal, \f[CR]b\f[R] balance sheet,+\f[CR]i\f[R] income statement, \f[CR]c\f[R] cashflow statement,+\f[CR]h\f[R] holdings (for journals using lots), \f[CR]a\f[R] all+accounts (escape to cancel)+.IP \(bu 2+\f[CR]n\f[R] / \f[CR]p\f[R] \- go to the next / previous page, in the+\f[CR]g\f[R] menu\(aqs order, wrapping round+.IP \(bu 2+\f[CR]a\f[R] \- add a transaction (escape to cancel)+.IP \(bu 2+\f[CR]s\f[R] \- show or hide the sidebar+.IP \(bu 2+shift with \f[CR]1\f[R]\-\f[CR]9\f[R] \- fold or open the sidebar\(aqs+accounts to that depth, as its − and + do (by the digit keys\(aq place,+whatever the layout; except where shift with one types a character that+is a shortcut itself, eg a digit on AZERTY keyboards, or \f[CR]/\f[R] on+German ones)+.IP \(bu 2+\f[CR]b\f[R] \- show or hide the sidebar\(aqs balances, as its Balances+heading does (while the sidebar shows)+.IP \(bu 2+\f[CR]o\f[R] \- show or hide the report options+.IP \(bu 2+\f[CR]c\f[R] \- show or hide the report\(aqs chart (on pages with one)+.IP \(bu 2+\f[CR][\f[R] / \f[CR]]\f[R] \- chart the previous / next commodity (on+pages whose chart has several, wrapping round)+.IP \(bu 2+\f[CR]N\f[R] \- show or hide the chart\(aqs net total line (on pages+whose chart has one)+.IP \(bu 2+\f[CR]d\f[R] \- show or hide the report\(aqs data, its table (on pages+with a chart)+.IP \(bu 2+\f[CR]f\f[R] \- full window: show only the report\(aqs heading and data,+or everything (\f[CR]s\f[R], \f[CR]o\f[R] and \f[CR]/\f[R] leave it,+showing what they ask for)+.IP \(bu 2+\f[CR]z\f[R] \- show or hide accounts with zero balances (on the+holdings page: closed positions)+.IP \(bu 2+\f[CR]t\f[R] \- show accounts as a tree, or a list+.IP \(bu 2+\f[CR]H\f[R] \- show ending balances, or balance changes+.IP \(bu 2+\f[CR]L\f[R] \- show or hide lot detail+.IP \(bu 2+\f[CR]V\f[R] \- show amounts at market value, or as recorded+.IP \(bu 2+\f[CR]B\f[R] \- show amounts at cost, or as recorded+.IP \(bu 2+\f[CR]R\f[R] \- show only real postings, or all+.IP \(bu 2+\f[CR]U\f[R], \f[CR]P\f[R], \f[CR]C\f[R] \- show only unmarked, pending,+or cleared transactions, or all+.IP \(bu 2+\f[CR]S\f[R] \- sort by amount, or by account+.IP \(bu 2+\f[CR]T\f[R], \f[CR]A\f[R] \- add or remove the row total and average+columns (multi\-period reports)+.IP \(bu 2+\f[CR]D\f[R], \f[CR]W\f[R], \f[CR]M\f[R], \f[CR]Q\f[R], \f[CR]Y\f[R] \-+set the report interval (daily, weekly, monthly, quarterly, yearly);+pressed again, remove it+.IP \(bu 2+\f[CR]0\f[R]\-\f[CR]9\f[R], \f[CR]\-\f[R], \f[CR]+\f[R] \- set or adjust+the account depth limit (\f[CR]\-\f[R] and \f[CR]+\f[R] step between 0+and the deepest)+.IP \(bu 2+\f[CR]/\f[R] \- focus the search form, ready to add a term (escape to+leave it)+.IP \(bu 2+\f[CR]Delete\f[R] or \f[CR]Backspace\f[R] \- clear the search, as its+clear button does+.PP+The pages are light or dark, following your OS or browser\(aqs color+scheme setting, and switch when it changes.+.PP+Editing, uploading and downloading journal files is described below.+.SH PERMISSIONS+You can restrict who can access hledger\-web by+.IP \(bu 2+setting the IP address it listens on (see \f[CR]\-\-host\f[R] above).+By default it listens on 127.0.0.1, accessible to users on the local+machine only.+.IP \(bu 2+or by putting it behind an authenticating proxy, such as caddy or apache+.IP \(bu 2+or by putting it behind a firewall.+.PP+And you can restrict what the users reaching it can do, by specifying+the \f[CR]\-\-allow=ACCESSLEVEL\f[R] option at startup.+ACCESSLEVEL is one of:+.IP \(bu 2+\f[CR]view\f[R] \- allows viewing the journal file(s)+.IP \(bu 2+\f[CR]add\f[R] \- also allows adding new transactions to the main+journal file+.IP \(bu 2+\f[CR]edit\f[R] \- also allows editing, uploading or downloading the+journal file(s)+.IP \(bu 2+\f[CR]sandstorm\f[R] \- (for the hledger\-web Sandstorm app:) allows+whichever of \f[CR]view\f[R], \f[CR]add\f[R], or \f[CR]edit\f[R] are+specified in the \f[CR]X\-Sandstorm\-Permissions\f[R] HTTP header+.PP+The default access level is \f[CR]add\f[R] when listening on a+local\-only address (\f[CR]127.0.0.1\f[R], \f[CR]::1\f[R],+\f[CR]localhost\f[R], or a unix socket), and \f[CR]view\f[R] otherwise.+To allow more than the default access, start it with an explicit+\f[CR]\-\-allow=add\f[R] or \f[CR]\-\-allow=edit\f[R] option.+.SH EDITING, UPLOADING, DOWNLOADING+If you start hledger\-web with \f[CR]\-\-allow=edit\f[R], you\(aqll see+a new \(dqspanner\(dq button to the right of the search form.+Clicking this will let you edit, upload, or download the journal file or+any files it includes.+.PP+Note, unlike any other hledger command, in this mode you (or any+visitor) can alter or wipe the data files.+Before saving an edited or uploaded file, hledger\-web saves a numbered+backup of it (eg \f[CR]main.journal.1\f[R], then+\f[CR]main.journal.2\f[R]); if the backup can\(aqt be written, the file+is not changed.+(Adding a transaction appends it to the main journal file without making+a backup.)+hledger\-web is not aware of version control systems, currently; if you+use one, you\(aqll have to arrange to commit the changes yourself.+.PP+Changes which would leave the journal unreadable are refused, and the+file is not changed.+This applies to edits, uploads and added transactions.+Each change is checked as the next read of the journal will check it, in+the context of all the journal\(aqs files and with the options+hledger\-web was started with: so transactions must balance, balance+assertions must pass (unless started with \f[CR]\-I\f[R]), lots must be+valid, and with \f[CR]\-\-strict\f[R], the strict checks must pass too.+.SH REPORTS+Besides the journal and the account registers, hledger\-web shows these+reports.+The sidebar and the links at the top of every page lead to each of them,+and so does the \f[CR]g\f[R] key followed by the first letter of the+report\(aqs name:+.IP \(bu 2+\f[B]Balance sheet\f[R] (\f[CR]b\f[R], \f[CR]/balancesheet\f[R]):+assets, liabilities and net worth, like the balancesheet command.+Its Equity option adds an equity section, like balancesheetequity.+.IP \(bu 2+\f[B]Income statement\f[R] (\f[CR]i\f[R], \f[CR]/incomestatement\f[R]):+revenues, expenses and net income, like incomestatement.+.IP \(bu 2+\f[B]Cashflow\f[R] (\f[CR]c\f[R], \f[CR]/cashflow\f[R]): changes in cash+accounts, like cashflow.+.IP \(bu 2+\f[B]Holdings\f[R] (\f[CR]h\f[R], \f[CR]/holdings\f[R]): investments and+their performance, like holdings.+Shown only for journals that use lots; see below.+.IP \(bu 2+\f[B]All accounts\f[R] (\f[CR]a\f[R], \f[CR]/balance\f[R]): all+accounts, or those you search for, like balance.+.PP+Each report shows a chart and then a table (by default; both can be+toggled).+Click any amount to see the transactions it is made of.+.SS Options+A report\(aqs options (click Options, or press \f[CR]o\f[R]) change what+it shows.+These are similar to hledger\(aqs command\-line options and+hledger\-ui\(aqs keys.+The main ones, with their keyboard shortcuts:+.IP \(bu 2+\f[B]Interval\f[R] (\f[CR]D\f[R], \f[CR]W\f[R], \f[CR]M\f[R],+\f[CR]Q\f[R], \f[CR]Y\f[R]): one column for the whole period, or one per+day, week, month, quarter or year (see Report intervals).+Until you choose one, the reports pick an interval to suit the period+shown (except holdings, whose interval is its own; see Holdings):+monthly for up to two years, quarterly for up to six, yearly beyond.+Click a column\(aqs heading to see the report for just its dates.+.IP \(bu 2+\f[B]Show\f[R] (\f[CR]H\f[R]): balance changes in each period, or ending+balances (which include everything before the period).+The balance sheet shows ending balances by default and the other reports+show changes, as their commands do; the report\(aqs heading says which+it is showing.+.IP \(bu 2+\f[B]Depth\f[R] (\f[CR]0\f[R]\-\f[CR]9\f[R], \f[CR]\-\f[R],+\f[CR]+\f[R]): how many levels of accounts to show (see Depth).+Depth 0 shows only the totals.+Until you choose one, the depth is 1, the top\-level accounts.+The − and + beside the table\(aqs Account heading step it too.+In tree mode they fold or open a level of the whole tree.+(The sidebar has a depth of its own; see above.)+.IP \(bu 2+\f[B]Accounts\f[R] (\f[CR]t\f[R]): a list, or a tree with subtotals; the+List and Tree links beside the table\(aqs Account heading switch too.+In a tree, the accounts below the depth limit are folded, and their+carets open them in place (at depth 0, all of them, under each+section\(aqs total).+.IP \(bu 2+\f[B]Amounts\f[R] (\f[CR]B\f[R], \f[CR]V\f[R]): as recorded, at cost, or+at market value at the end of each period (see Cost reporting and Value+reporting).+.IP \(bu 2+\f[B]Zero balances\f[R] (\f[CR]z\f[R]): hide or show accounts whose+balance is zero.+(On the holdings page, \f[CR]z\f[R] toggles Closed positions instead;+use this option\(aqs links there.)+.IP \(bu 2+\f[B]Equity\f[R] (balance sheet only): hide or show the equity section.+The browser remembers this choice for each hledger\-web server.+.IP \(bu 2+\f[B]Status\f[R] (\f[CR]U\f[R], \f[CR]P\f[R], \f[CR]C\f[R]),+\f[B]Postings\f[R] (\f[CR]R\f[R]), account types, and commodities: show+only transactions with that status, only real postings, or only some+account types or commodities.+These rows edit the search, adding a term like \f[CR]status:*\f[R] or+\f[CR]type:A\f[R].+Shift\-click selects several types or commodities.+.PP+The options you choose stay in effect as you move to other pages, except+Show, which each report sets to its own default.+On the journal and register, the report options are shown muted, but are+kept.+.PP+The search form filters reports as it does the other pages, and its+\f[CR]date:\f[R] terms set the report\(aqs dates.+An interval or depth typed in the search, like \f[CR]date:monthly\f[R]+or \f[CR]depth:2\f[R], moves into the options when the page reloads.+A depth limit for some accounts only, like \f[CR]depth:assets=3\f[R],+stays in the search.+.PP+The options are also URL parameters, so you can bookmark a report with+them.+.PP+(For more detail, see the hledger manual, eg CONCEPTS.)+.SS Charts+A report\(aqs chart is the one its command draws with+\f[CR]\-\-chart\f[R]: eg a bar per account, or with an interval, each+account over time, and for the statements, each section and the net+total.+In tree mode it shows the accounts down to the depth limit.+With several commodities, use the legend, or the \f[CR][\f[R] and+\f[CR]]\f[R] keys, to choose the one charted.+The Balance page\(aqs and statements\(aq charts stack each period\(aqs+accounts (or sections) in one bar, above and below zero; the Chart row+in Options (or \f[CR]\-\-chart=grouped\f[R] at startup) shows a bar per+account type (or section), side by side, instead (on the Balance page+with no interval, for the whole period, as+\f[CR]balance \-\-chart=grouped\f[R] does).+\f[CR]\-\-chart\f[R] at startup takes the same value as the commands\(aq+\f[CR]\-\-chart\f[R]; its SCALE amounts fix the scales of the report and+register charts, so that they can be compared.+Hover over a bar or a line (or on a touch screen, tap it) to see its+period (or date, or account), its series and its amount.+Charts are drawn as wide as the page shows them, and redrawn when that+changes, eg when you hide or show the sidebar or resize the window.+.PP+The \f[CR]c\f[R] key hides or shows the chart, and \f[CR]d\f[R] the+table (the report\(aqs data).+You can also click the Chart and Data buttons at their top right+corners, whose carets show whether they are shown.+The \f[CR]N\f[R] key shows or hides the net total line (or marks), eg a+statement\(aqs net, or holdings\(aq value or net gain; this is hidden at+first, leaving the bars it totals (or with \f[CR]\-\-chart=net\f[R] at+startup, shown at first).+The browser remembers this for each hledger\-web server, and once you+have chosen with \f[CR]N\f[R], your choice wins over+\f[CR]\-\-chart=net\f[R].+.SS From a report to its transactions+Click an amount to see its account\(aqs register for that period: the+transactions the amount is made of.+An ending balance\(aqs register starts with the balance brought forward,+so its final running balance is that amount.+A section\(aqs total shows the register of all the section\(aqs+accounts.+An amount shown at cost or market value leads to a register showing its+amounts the same way.+.PP+Some things can make the register look different from the report:+.IP \(bu 2+The statements show liabilities, equity and revenues as positive+amounts, as their commands do, so their registers show the same amounts+negated.+The amount\(aqs tooltip says so.+.IP \(bu 2+When a posting has a date of its own, the report counts it on that date,+but the register lists its whole transaction, on the transaction\(aqs+date.+.SS Holdings+The holdings report shows one row for each commodity held in each+account, with its cost basis, value and gains.+Its chart has a bar for each one, showing its cost basis and unrealised+gain or loss.+Its own options can show:+.IP \(bu 2+each lot separately (\f[B]Lots\f[R], \f[CR]L\f[R]),+.IP \(bu 2+fully disposed positions and their realised gains (\f[B]Closed+positions\f[R], \f[CR]z\f[R]),+.IP \(bu 2+all values in the market valuation commodity (\f[B]Values\f[R]).+.PP+Closed positions are hidden by default, as in the \f[CR]holdings\f[R]+command, but the totals\(aq RGain and XIRR always include them; a note+below the table says how many are hidden, with a link to show them.+.PP+Its depth limit doesn\(aqt fold accounts: as on the command line, it+merges the deeper accounts\(aq positions, by commodity, into the+accounts at the limit.+.PP+With an \f[B]Interval\f[R] chosen (it picks none by itself), it shows+how your holdings changed, like holdings with a report interval: a row+for each period\(aqs end, with the totals of all the holdings then, and+a bar for each in the chart.+Each row\(aqs date links to the holdings on that date.+This page\(aqs interval is its own, since it makes a different report+here: choosing one doesn\(aqt change the other reports\(aq interval, nor+theirs this page\(aqs, and an interval given at startup (eg+\f[CR]\-M\f[R]) is theirs.+Its \f[B]Gains\f[R] option chooses what the gain columns cover: each+period, the time since the report\(aqs start date, or the time since+acquisition (the default).+With the first two, the chart shows those gains: realised, and+unrealised (hatched).+\f[CR]H\f[R] toggles between gains since acquisition and gains in each+period.+.PP+On journals that use lots, every page also has a Lots option, showing+lot subaccounts and per\-lot postings.+.SH URL PARAMETERS+A page\(aqs url includes its search and options, so a bookmark or a+shared link shows the same view.+You can also write these urls yourself, eg+\f[CR]/balancesheet?interval=monthly&depth=2\f[R] or+\f[CR]/register?account=assets:bank\f[R].+These are the parameters, most corresponding to hledger options:+.IP \(bu 2+\f[CR]q\f[R] \- the search+.IP \(bu 2+\f[CR]account\f[R] \- the account whose register to show (with its+subaccounts, unless \f[CR]subs=0\f[R])+.IP \(bu 2+\f[CR]page\f[R] \- which page of transactions to show, in the journal+and register (1 is the newest)+.IP \(bu 2+\f[CR]interval\f[R] \- \f[CR]daily\f[R], \f[CR]weekly\f[R],+\f[CR]monthly\f[R], \f[CR]quarterly\f[R] or \f[CR]yearly\f[R] (like+\f[CR]\-D\f[R], \f[CR]\-W\f[R], \f[CR]\-M\f[R], \f[CR]\-Q\f[R],+\f[CR]\-Y\f[R]), or \f[CR]none\f[R] for one column; without it the+reports pick one+.IP \(bu 2+\f[CR]hinterval\f[R] \- the holdings page\(aqs own interval, in the same+words; without it, none+.IP \(bu 2+\f[CR]depth\f[R] \- a number (like \f[CR]\-\-depth\f[R]), or+\f[CR]all\f[R] for no limit; without it, 1+.IP \(bu 2+\f[CR]accum\f[R] \- \f[CR]change\f[R], \f[CR]historical\f[R] or+\f[CR]cumulative\f[R] (like \f[CR]\-\-change\f[R], \f[CR]\-H\f[R],+\f[CR]\-\-cumulative\f[R]); on the holdings page, with an interval, what+the gains cover+.IP \(bu 2+\f[CR]value\f[R] \- \f[CR]none\f[R], \f[CR]cost\f[R], or+\f[CR]then\f[R], \f[CR]end\f[R], \f[CR]now\f[R] or a date, optionally+followed by \f[CR],COMMODITY\f[R] (like \f[CR]\-\-value\f[R])+.IP \(bu 2+\f[CR]infer\f[R] \- \f[CR]1\f[R] to infer market prices from transaction+costs too (like \f[CR]\-\-infer\-market\-prices\f[R])+.IP \(bu 2+\f[CR]empty\f[R] \- \f[CR]1\f[R] to show zero balances, \f[CR]0\f[R] to+hide them (like \f[CR]\-E\f[R])+.IP \(bu 2+\f[CR]list\f[R] \- \f[CR]tree\f[R] or \f[CR]flat\f[R] (like+\f[CR]\-\-tree\f[R], \f[CR]\-\-flat\f[R])+.IP \(bu 2+\f[CR]sort\f[R] \- \f[CR]amount\f[R] (like \f[CR]\-S\f[R])+.IP \(bu 2+\f[CR]total\f[R], \f[CR]avg\f[R], \f[CR]pct\f[R] \- \f[CR]1\f[R] to add+totals, averages, or show percentages (like \f[CR]\-T\f[R],+\f[CR]\-A\f[R], \f[CR]\-%\f[R])+.IP \(bu 2+\f[CR]calc\f[R] \- \f[CR]valuechange\f[R], \f[CR]gain\f[R] or+\f[CR]count\f[R] (like \f[CR]\-\-valuechange\f[R], \f[CR]\-\-gain\f[R],+\f[CR]\-\-count\f[R])+.IP \(bu 2+\f[CR]date2\f[R] \- \f[CR]1\f[R] to use secondary dates (like+\f[CR]\-\-date2\f[R])+.IP \(bu 2+\f[CR]costs\f[R] \- \f[CR]1\f[R] to show costs, in the register+.IP \(bu 2+\f[CR]equity\f[R] \- \f[CR]1\f[R] or \f[CR]0\f[R], on the balance sheet+(the old \f[CR]/balancesheetequity\f[R] address leads to+\f[CR]equity=1\f[R])+.IP \(bu 2+\f[CR]lots\f[R] \- \f[CR]1\f[R] to show lots (like \f[CR]\-\-lots\f[R])+.IP \(bu 2+\f[CR]closed\f[R] \- \f[CR]1\f[R], on the holdings page, to show closed+positions, \f[CR]0\f[R] to hide them+.IP \(bu 2+\f[CR]chart\f[R] \- \f[CR]grouped\f[R], on the Balance and statement+pages, to chart each period\(aqs account types (or sections) side by+side (like \f[CR]\-\-chart=grouped\f[R])+.SH RELOADING+hledger\-web detects changes made to the files by other means (eg if you+edit it directly, outside of hledger\-web), and it will show the new+data when you reload the page or navigate to a new page.+If a change makes a file unparseable, hledger\-web will display an error+message until the file has been fixed.+.PP+(If you are viewing files mounted from another machine, make sure that+both machines have roughly the same idea of what time it is.)+.SH JSON API+In addition to the web UI, hledger\-web also serves a JSON API that can+be used to get data or add new transactions.+If you want the JSON API only, you can use the \f[CR]\-\-serve\-api\f[R]+flag.+Eg:+.IP+.EX+$ hledger\-web \-f examples/sample.journal \-\-serve\-api+\&...+.EE+.PP+You can get JSON data from these routes:+.IP+.EX+/version+/accountnames+/transactions+/prices+/commodities+/accounts+/accounttransactions/ACCOUNTNAME+/openapi.json+.EE+.PP+Eg, all account names in the journal (similar to the accounts command).+(hledger\-web\(aqs JSON does not include newlines, here we use python to+prettify it):+.IP+.EX+$ curl \-s http://127.0.0.1:5000/accountnames | python3 \-m json.tool+[+ \(dqassets\(dq,+ \(dqassets:bank\(dq,+ \(dqassets:bank:checking\(dq,+ \(dqassets:bank:saving\(dq,+ \(dqassets:cash\(dq,+ \(dqexpenses\(dq,+ \(dqexpenses:food\(dq,+ \(dqexpenses:supplies\(dq,+ \(dqincome\(dq,+ \(dqincome:gifts\(dq,+ \(dqincome:salary\(dq,+ \(dqliabilities\(dq,+ \(dqliabilities:debts\(dq+]+.EE+.PP+Or all transactions:+.IP+.EX+$ curl \-s http://127.0.0.1:5000/transactions | python3 \-m json.tool+[+ {+ \(dqtcode\(dq: \(dq\(dq,+ \(dqtcomment\(dq: \(dq\(dq,+ \(dqtdate\(dq: \(dq2008\-01\-01\(dq,+ \(dqtdate2\(dq: null,+ \(dqtdescription\(dq: \(dqincome\(dq,+ \(dqtindex\(dq: 1,+ \(dqtpostings\(dq: [+ {+ \(dqpaccount\(dq: \(dqassets:bank:checking\(dq,+ \(dqpamount\(dq: [+ {+ \(dqacommodity\(dq: \(dq$\(dq,+ \(dqacost\(dq: null,+ \(dqacostbasis\(dq: null,+\&...+.EE+.PP+Most of the JSON corresponds to hledger\(aqs data types; for details of+what the fields mean, see the Hledger.Data.Json haddock docs and click+on the various data types, eg Transaction.+And for a higher level understanding, see the journal docs.+There is also a basic OpenAPI specification, also served at+\f[CR]/openapi.json\f[R].+.PP+Some routes return a report type wrapping the data; eg+\f[CR]/accounttransactions\f[R] returns an AccountTransactionsReport, a+report title and a list of items.+The handlers in Hledger.Web.Handler.MiscR show what each route returns.+.PP+You can add a new transaction to the journal with a PUT request to+\f[CR]/add\f[R], if hledger\-web was started with+\f[CR]\-\-allow=add\f[R] (the default when listening on a local\-only+address).+The payload must be the full, exact JSON representation of a hledger+transaction (partial data won\(aqt do).+The journal must still be readable with the transaction added, with+hledger\-web\(aqs startup options (see Editing, uploading, downloading);+if not, the response has status 400 and the error message, and the+journal is not changed.+You can get sample JSON from hledger\-web\(aqs \f[CR]/transactions\f[R]+or \f[CR]/accounttransactions\f[R], or from hledger\(aqs print command.+Eg, this saves the first transaction of the sample journal to+\f[CR]txn.json\f[R]:+.IP+.EX+$ hledger \-f examples/sample.journal print \-O json | python3 \-c \(aqimport json,sys; json.dump(json.load(sys.stdin)[0], sys.stdout, indent=4)\(aq > txn.json+.EE+.PP+Here\(aqs how it looks (remember, this JSON corresponds to hledger\(aqs+Transaction and related data types):+.IP+.EX+{+ \(dqtcode\(dq: \(dq\(dq,+ \(dqtcomment\(dq: \(dq\(dq,+ \(dqtdate\(dq: \(dq2008\-01\-01\(dq,+ \(dqtdate2\(dq: \f[B]null\f[R],+ \(dqtdescription\(dq: \(dqincome\(dq,+ \(dqtindex\(dq: 1,+ \(dqtpostings\(dq: [+ {+ \(dqpaccount\(dq: \(dqassets:bank:checking\(dq,+ \(dqpamount\(dq: [+ {+ \(dqacommodity\(dq: \(dq$\(dq,+ \(dqacost\(dq: \f[B]null\f[R],+ \(dqacostbasis\(dq: \f[B]null\f[R],+ \(dqaquantity\(dq: {+ \(dqdecimalMantissa\(dq: 1,+ \(dqdecimalPlaces\(dq: 0,+ \(dqfloatingPoint\(dq: 1+ },+ \(dqastyle\(dq: {+ \(dqascommodityside\(dq: \(dqL\(dq,+ \(dqascommodityspaced\(dq: \f[B]false\f[R],+ \(dqasdecimalmark\(dq: \(dq.\(dq,+ \(dqasdigitgroups\(dq: \f[B]null\f[R],+ \(dqasprecision\(dq: 0,+ \(dqasrounding\(dq: \(dqNoRounding\(dq+ }+ }+ ],+ \(dqpbalanceassertion\(dq: \f[B]null\f[R],+ \(dqpcomment\(dq: \(dq\(dq,+ \(dqpdate\(dq: \f[B]null\f[R],+ \(dqpdate2\(dq: \f[B]null\f[R],+ \(dqporiginal\(dq: \f[B]null\f[R],+ \(dqpreal\(dq: \(dqRealPosting\(dq,+ \(dqpstatus\(dq: \(dqUnmarked\(dq,+ \(dqptags\(dq: [],+ \(dqptransaction_\(dq: \(dq1\(dq+ },+ {+ \(dqpaccount\(dq: \(dqincome:salary\(dq,+ \(dqpamount\(dq: [+ {+ \(dqacommodity\(dq: \(dq$\(dq,+ \(dqacost\(dq: \f[B]null\f[R],+ \(dqacostbasis\(dq: \f[B]null\f[R],+ \(dqaquantity\(dq: {+ \(dqdecimalMantissa\(dq: \-1,+ \(dqdecimalPlaces\(dq: 0,+ \(dqfloatingPoint\(dq: \-1+ },+ \(dqastyle\(dq: {+ \(dqascommodityside\(dq: \(dqL\(dq,+ \(dqascommodityspaced\(dq: \f[B]false\f[R],+ \(dqasdecimalmark\(dq: \(dq.\(dq,+ \(dqasdigitgroups\(dq: \f[B]null\f[R],+ \(dqasprecision\(dq: 0,+ \(dqasrounding\(dq: \(dqNoRounding\(dq+ }+ }+ ],+ \(dqpbalanceassertion\(dq: \f[B]null\f[R],+ \(dqpcomment\(dq: \(dq\(dq,+ \(dqpdate\(dq: \f[B]null\f[R],+ \(dqpdate2\(dq: \f[B]null\f[R],+ \(dqporiginal\(dq: \f[B]null\f[R],+ \(dqpreal\(dq: \(dqRealPosting\(dq,+ \(dqpstatus\(dq: \(dqUnmarked\(dq,+ \(dqptags\(dq: [],+ \(dqptransaction_\(dq: \(dq1\(dq+ }+ ],+ \(dqtprecedingcomment\(dq: \(dq\(dq,+ \(dqtsourcepos\(dq: [+ {+ \(dqsourceColumn\(dq: 1,+ \(dqsourceLine\(dq: 31,+ \(dqsourceName\(dq: \(dq/home/user/hledger/examples/sample.journal\(dq+ },+ {+ \(dqsourceColumn\(dq: 1,+ \(dqsourceLine\(dq: 34,+ \(dqsourceName\(dq: \(dq/home/user/hledger/examples/sample.journal\(dq+ }+ ],+ \(dqtstatus\(dq: \(dqUnmarked\(dq,+ \(dqttags\(dq: []+}+.EE+.PP+And here\(aqs how to add it with curl.+This should append a new entry to your journal file:+.IP+.EX+$ curl http://127.0.0.1:5000/add \-X PUT \-H \(aqContent\-Type: application/json\(aq \-\-data\-binary \(attxn.json+.EE+.SH DEBUG OUTPUT+You can add \f[CR]\-\-debug[=N]\f[R] to the command line to log debug+output.+N ranges from 1 (least output, the default) to 9 (maximum output).+Typically you would start with 1 and increase until you are seeing+enough.+Debug output goes to stderr, interleaved with the requests logged on+stdout.+To capture debug output in a log file instead, you can usually redirect+stderr, eg:+.PD 0+.P+.PD+\f[CR]hledger\-web \-\-debug=3 2>hledger\-web.log\f[R].+.SH LANGUAGE+hledger\-web\(aqs pages can be shown in another language when a+translation catalog is available (see Languages in the hledger manual).+.PP+When hledger\-web is started with \f[CR]\-\-lang LANG\f[R], eg+\f[CR]\-\-lang de\f[R], every page is in that language, whatever the+browser asks for.+So you can use hledger\-web in a language other than your browser\(aqs,+or give every user of a shared server the same language.+.PP+Otherwise the language is chosen per request, and the first of these+naming an available translation wins:+.IP "1." 3+a \f[CR]_LANG\f[R] query parameter, eg \f[CR]?_LANG=de\f[R].+This choice is remembered in a \f[CR]_LANG\f[R] cookie.+.IP "2." 3+the \f[CR]_LANG\f[R] cookie+.IP "3." 3+the browser\(aqs \f[CR]Accept\-Language\f[R] header, ie the browser\(aqs+or system\(aqs language settings+.PP+If none does, pages are in English, or with \f[CR]\-\-lang auto\f[R], in+the language of hledger\-web\(aqs environment.+So viewers usually get their browser\(aqs language automatically, if+hledger\-web has it.+Catalogs, including any in the config directory, are loaded when+hledger\-web starts.+.SH ENVIRONMENT+\f[B]LEDGER_FILE\f[R] The main journal file to use when not specified+with \f[CR]\-f/\-\-file\f[R].+Default: \f[CR]$HOME/.hledger.journal\f[R].+.SH BUGS+We welcome bug reports in the hledger issue tracker+(https://bugs.hledger.org), or on the hledger chat or mail list+(https://hledger.org/support).+.PP+Some known issues:+.PP+Without JavaScript (eg in text\-mode browsers), pages can be viewed and+their links followed, but the add form, help dialog, keyboard shortcuts,+sidebar toggle and folding don\(aqt work.+++.SH AUTHORS+Simon Michael <simon@joyful.com> and contributors.+.br+See http://hledger.org/CREDITS.html++.SH COPYRIGHT+Copyright 2007-2023 Simon Michael and contributors.++.SH LICENSE+Released under GNU GPL v3 or later.++.SH SEE ALSO+hledger(1), hledger\-ui(1), hledger\-web(1), ledger(1)
+ embeddedfiles/hledger-web.info view
@@ -0,0 +1,1003 @@+This is hledger-web.info, produced by makeinfo version 7.3 from stdin.++INFO-DIR-SECTION User Applications+START-INFO-DIR-ENTRY+* hledger-web: (hledger-web). Web UI/API for the hledger accounting tool.+END-INFO-DIR-ENTRY+++File: hledger-web.info, Node: Top, Next: OPTIONS, Up: (dir)++hledger-web(1)+**************++hledger-web - web interface and API for 'hledger', a robust, friendly+plain text accounting app.++ 'hledger-web [OPTS] [QUERY]'+or+'hledger web [OPTS] [QUERY]'++ This manual is for hledger's web 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 tracking money, time, or any other commodity, using double-entry+accounting and a simple, editable file format. hledger is inspired by+and largely compatible with ledger(1), and largely interconvertible with+beancount(1).++ hledger-web is hledger's web interface. In a web browser, it shows+the journal, account registers, and the main financial reports with+their charts, and lets you search them, add transactions, and (if+allowed) edit the journal files. It shows more at once than the hledger+CLI or hledger-ui (eg the accounts beside a register, or a report's+chart above its table), and every view has its own url, so it can be+bookmarked or shared.++ hledger-web also lets you share a journal with multiple users, or+even the public web. There is no user authentication, so if you need+that you should put it behind a suitable web proxy (see Permissions).++ Like hledger, it reads from (and appends to) a journal file specified+by the 'LEDGER_FILE' environment variable (defaulting to+'$HOME/.hledger.journal'); or you can specify files with '-f' options.+It can also read timeclock files, timedot files, or any CSV/SSV/TSV file+with a date field. (See hledger(1) -> Input for details.)++ hledger-web can be run in three modes:++ * '--serve-browse' mode (the default): the app serves the web UI and+ JSON API, and opens your default web browser to show the app if+ possible, and exits automatically once no browser window has shown+ it for fifteen minutes.++ * '--serve': the app just serves the web UI and JSON API.++ * '--serve-api': the app just serves the JSON API.++ In all cases hledger-web runs as a foreground process, logging+requests to stdout.++* Menu:++* OPTIONS::+* WEB UI::+* PERMISSIONS::+* EDITING UPLOADING DOWNLOADING::+* REPORTS::+* URL PARAMETERS::+* RELOADING::+* JSON API::+* DEBUG OUTPUT::+* LANGUAGE::+* ENVIRONMENT::+* BUGS::+++File: hledger-web.info, Node: OPTIONS, Next: WEB UI, Prev: Top, Up: Top++1 OPTIONS+*********++hledger-web provides the following command line options:++Flags:+ --serve-browse server mode: serve the web UI and JSON API,+ and open a browser, and exit if inactive for 15m+ (default)+ --serve server mode: just serve the web UI and JSON+ API+ --serve-api server mode: just serve the JSON API+ --allow=view|add|edit set the user's access level for changing data+ (default: `add` on a local-only address, `view`+ otherwise). It also accepts `sandstorm` for that+ platform (reading from the+ `X-Sandstorm-Permissions` request header).+ --cors=ORIGIN allow cross-origin requests from the specified+ origin; setting ORIGIN to "*" allows requests+ from any origin+ --host=IPADDR listen on this IP address (default: 127.0.0.1)+ --port=PORT listen on this TCP port (default: 5000); 0+ means a free port chosen by the OS+ --socket=SOCKET listen on the given unix socket instead of an+ IP address and port (only on unix)+ --base-url=BASEURL set the base url (default: http://IPADDR:PORT)+ --chart[=KIND,net,SCALE] set the charts' defaults, as the commands'+ --chart does. KIND: lay out the statements'+ charts with each period's sections in one bar,+ above and below zero (diverging, the default),+ or side by side (grouped). net: show the net+ total lines by default (the N key toggles them,+ and the browser remembers that). SCALE: the+ amount that fills the charts (eg 1000 or 1000+ USD; one per commodity), for comparable charts.+ --lang=LANG show the web UI in this language (en, de, es,+ ru, zh); or with auto, use each viewer's browser+ language if available, otherwise the server's.+ (Default: the browser's language if available,+ otherwise en.)++ By default hledger-web listens only on IP address '127.0.0.1', which+can be accessed only from the local machine.++ To allow access from elsewhere, use '--host' to specify an externally+accessible address configured on this machine. The special address+'0.0.0.0' causes it to listen on all of this machine's addresses.++ Similarly, you can use '--port' to listen on a TCP port other than+5000. This is useful if you want to run multiple hledger-web instances+on a machine. '--port 0' makes the operating system choose a free port,+which is reported in the startup message and in the default base url,+and is where the browser is opened in '--serve-browse' mode. This can+be useful eg when scripting.++ When '--socket' is used, hledger-web creates and communicates via a+socket file instead of a TCP port. This can be more secure, respects+unix file permissions, and makes certain use cases easier, such as+running per-user instances behind an nginx reverse proxy. (Eg:+'proxy_pass http://unix:/tmp/hledger/${remote_user}.socket;'.)++ You can use '--base-url' to change the protocol, hostname, port and+path that appear in hledger-web's hyperlinks. This is useful eg when+integrating hledger-web within a larger website. The default is+'http://HOST:PORT/' using the server's configured host address and TCP+port (or 'http://HOST' if PORT is 80). Note this affects url generation+but not route parsing.++ hledger-web also supports many of hledger's general options:++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.+ --alias=A=B|/RGX/=RPL transform account names from A to B, or by+ replacing regular expression matches+ --auto generate extra postings by applying auto posting+ rules ("=") to all transactions+ --forecast[=PERIOD] Generate extra transactions from periodic rules+ ("~"), from after the latest ordinary transaction+ until 6 months from now. Or, during the specified+ PERIOD (the equals is required). Auto posting rules+ will also be applied to these transactions. In+ hledger-ui, also make future-dated transactions+ visible at startup.+ --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)++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 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)+ --date2 match/use secondary dates instead (deprecated)+ -U --unmarked include only unmarked postings/transactions+ -P --pending include only pending postings/transactions+ -C --cleared include only cleared postings/transactions+ (-U/-P/-C can be combined)+ -R --real include only non-virtual postings+ -E --empty Show zero items, which are normally hidden.+ In hledger-ui & hledger-web, do the opposite.+ --depth=DEPTHEXP if a number (or -NUM): show only top NUM levels+ of accounts. If REGEXP=NUM, only apply limiting to+ accounts matching the regular expression.+ -B --cost 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? 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:+ -? 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+ --test[=PATTERN] run built-in tests (those matching PATTERN) and+ exit+ --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)++ Some of these can be adjusted while hledger-web is running, in the+web UI's Options panel.++ hledger-web shows accounts with zero balances by default (like+'hledger-ui', and unlike 'hledger'); '-E/--empty' starts it with them+hidden instead. In the web UI, the Zero balances option or the 'z' key+shows or hides them. (The holdings page differs: its closed positions+are hidden by default, as in the 'holdings' command; '-E' starts it with+them shown, and 'z' there shows or hides them.)++ Report options and a query given at startup set the view hledger-web+opens with, by putting them in its url (see URL parameters). Eg+'hledger-web -V -M' opens '/balancesheet?interval=monthly&value=end',+and 'hledger-web --cleared -3 assets' opens '/balancesheet?q=assets+status:*&depth=3'. They are only a starting point: they can be changed+in the web UI, and they don't affect other urls or the JSON API. Report+options that hledger-web has no equivalent for are ignored.++ Note, a startup query doesn't restrict what hledger-web serves; to do+that, give it a file holding only the entries to serve (eg one written+by 'hledger print QUERY').++ If you use the bash shell, you can auto-complete flags by pressing+TAB in the command line. If this is not working see Install > Shell+completions.+++File: hledger-web.info, Node: WEB UI, Next: PERMISSIONS, Prev: OPTIONS, Up: Top++2 WEB UI+********++hledger-web's main views are:++ * the *journal view*, showing journal entries, newest first, with+ their postings+ * the *report views*, described below: the balance sheet, income+ statement, cashflow statement (and holdings, for journals using+ lots), and All accounts report+ * a *register view* for each account, reached by clicking an account+ name, showing the transactions affecting that account (and its+ subaccounts), with a running balance and a balance chart.++ Every page has, from the top: links to the journal and the reports,+the search form, the options, and then the view itself. The options are+hidden until you open them (click Options, or press 'o'); while hidden,+they list the ones in effect, eg "Monthly · Depth 2 · Tree".++ The journal and register show the newest 1000 matching transactions,+with links to older and newer pages. When the transactions span more+than one year, the options include a row of years, to narrow the view to+one year; shift-click a second year to select a range of years.++ The register's chart shows the running balance over the page's+transactions. With several commodities, use the legend, or the '[' and+']' keys, to choose the one charted. Click a point to go to its+transaction, or drag across the chart to see the transactions of those+dates. The register's Costs option shows the costs recorded with its+amounts.++ The *sidebar* lists every account, and optionally their balances+(parent balances include subaccounts). The search doesn't change it,+except that its dates set the balances' date. The balances are hidden+at first, since on a large journal they take much of each page's time;+click the "Balances" heading above the accounts to show them, or to hide+them again. These are historical balances, as of the end of the report+period set by date:, otherwise the latest (the heading shows the date).+While the balances are hidden, all accounts are listed, even with Zero+balances: Hidden. It is always a tree, with carets that fold and open+each group, whether the Accounts option is List or Tree. The − and ++above it fold or open a level of the whole tree, without changing the+page; its depth is its own, apart from the page's depth limit. The+browser remembers the sidebar's depth and the groups you open or close+(until the next − or +). The button at the top left (or the 's' key)+shows or hides the sidebar, and it stays the way you left it from page+to page. On a narrow screen, it slides the sidebar in or out.++ Click an account name to see its register, with the search, or an+amount to see the transactions it is made of. In the journal and+register, click a date to see that day's journal entries.++ The *search form* filters every view with hledger's query syntax, eg+'expenses date:thismonth'; the help dialog summarises the query types.+The search and the options are part of the page's url (see URL+parameters).++ The *add form* (press 'a', or click "Add a transaction" in the+journal view) adds a transaction to the main journal file, if the access+level allows it, and if the journal would still be readable with it+added (see Editing, uploading, downloading). It autocompletes account+names and descriptions from your existing entries.++ The *help dialog* (press '?', or click the question mark button)+lists these keyboard shortcuts, which work when you are not typing in a+field:++ * 'h' or '?' - show or hide the help dialog+ * 'g' - go to another page: shows a menu of the pages, each with its+ key; then 'j' journal, 'b' balance sheet, 'i' income statement, 'c'+ cashflow statement, 'h' holdings (for journals using lots), 'a' all+ accounts (escape to cancel)+ * 'n' / 'p' - go to the next / previous page, in the 'g' menu's+ order, wrapping round+ * 'a' - add a transaction (escape to cancel)+ * 's' - show or hide the sidebar+ * shift with '1'-'9' - fold or open the sidebar's accounts to that+ depth, as its − and + do (by the digit keys' place, whatever the+ layout; except where shift with one types a character that is a+ shortcut itself, eg a digit on AZERTY keyboards, or '/' on German+ ones)+ * 'b' - show or hide the sidebar's balances, as its Balances heading+ does (while the sidebar shows)+ * 'o' - show or hide the report options+ * 'c' - show or hide the report's chart (on pages with one)+ * '[' / ']' - chart the previous / next commodity (on pages whose+ chart has several, wrapping round)+ * 'N' - show or hide the chart's net total line (on pages whose chart+ has one)+ * 'd' - show or hide the report's data, its table (on pages with a+ chart)+ * 'f' - full window: show only the report's heading and data, or+ everything ('s', 'o' and '/' leave it, showing what they ask for)+ * 'z' - show or hide accounts with zero balances (on the holdings+ page: closed positions)+ * 't' - show accounts as a tree, or a list+ * 'H' - show ending balances, or balance changes+ * 'L' - show or hide lot detail+ * 'V' - show amounts at market value, or as recorded+ * 'B' - show amounts at cost, or as recorded+ * 'R' - show only real postings, or all+ * 'U', 'P', 'C' - show only unmarked, pending, or cleared+ transactions, or all+ * 'S' - sort by amount, or by account+ * 'T', 'A' - add or remove the row total and average columns+ (multi-period reports)+ * 'D', 'W', 'M', 'Q', 'Y' - set the report interval (daily, weekly,+ monthly, quarterly, yearly); pressed again, remove it+ * '0'-'9', '-', '+' - set or adjust the account depth limit ('-' and+ '+' step between 0 and the deepest)+ * '/' - focus the search form, ready to add a term (escape to leave+ it)+ * 'Delete' or 'Backspace' - clear the search, as its clear button+ does++ The pages are light or dark, following your OS or browser's color+scheme setting, and switch when it changes.++ Editing, uploading and downloading journal files is described below.+++File: hledger-web.info, Node: PERMISSIONS, Next: EDITING UPLOADING DOWNLOADING, Prev: WEB UI, Up: Top++3 PERMISSIONS+*************++You can restrict who can access hledger-web by++ * setting the IP address it listens on (see '--host' above). By+ default it listens on 127.0.0.1, accessible to users on the local+ machine only.+ * or by putting it behind an authenticating proxy, such as caddy or+ apache+ * or by putting it behind a firewall.++ And you can restrict what the users reaching it can do, by specifying+the '--allow=ACCESSLEVEL' option at startup. ACCESSLEVEL is one of:++ * 'view' - allows viewing the journal file(s)+ * 'add' - also allows adding new transactions to the main journal+ file+ * 'edit' - also allows editing, uploading or downloading the journal+ file(s)+ * 'sandstorm' - (for the hledger-web Sandstorm app:) allows whichever+ of 'view', 'add', or 'edit' are specified in the+ 'X-Sandstorm-Permissions' HTTP header++ The default access level is 'add' when listening on a local-only+address ('127.0.0.1', '::1', 'localhost', or a unix socket), and 'view'+otherwise. To allow more than the default access, start it with an+explicit '--allow=add' or '--allow=edit' option.+++File: hledger-web.info, Node: EDITING UPLOADING DOWNLOADING, Next: REPORTS, Prev: PERMISSIONS, Up: Top++4 EDITING, UPLOADING, DOWNLOADING+*********************************++If you start hledger-web with '--allow=edit', you'll see a new "spanner"+button to the right of the search form. Clicking this will let you+edit, upload, or download the journal file or any files it includes.++ Note, unlike any other hledger command, in this mode you (or any+visitor) can alter or wipe the data files. Before saving an edited or+uploaded file, hledger-web saves a numbered backup of it (eg+'main.journal.1', then 'main.journal.2'); if the backup can't be+written, the file is not changed. (Adding a transaction appends it to+the main journal file without making a backup.) hledger-web is not+aware of version control systems, currently; if you use one, you'll have+to arrange to commit the changes yourself.++ Changes which would leave the journal unreadable are refused, and the+file is not changed. This applies to edits, uploads and added+transactions. Each change is checked as the next read of the journal+will check it, in the context of all the journal's files and with the+options hledger-web was started with: so transactions must balance,+balance assertions must pass (unless started with '-I'), lots must be+valid, and with '--strict', the strict checks must pass too.+++File: hledger-web.info, Node: REPORTS, Next: URL PARAMETERS, Prev: EDITING UPLOADING DOWNLOADING, Up: Top++5 REPORTS+*********++Besides the journal and the account registers, hledger-web shows these+reports. The sidebar and the links at the top of every page lead to+each of them, and so does the 'g' key followed by the first letter of+the report's name:++ * *Balance sheet* ('b', '/balancesheet'): assets, liabilities and net+ worth, like the balancesheet command. Its Equity option adds an+ equity section, like balancesheetequity.+ * *Income statement* ('i', '/incomestatement'): revenues, expenses+ and net income, like incomestatement.+ * *Cashflow* ('c', '/cashflow'): changes in cash accounts, like+ cashflow.+ * *Holdings* ('h', '/holdings'): investments and their performance,+ like holdings. Shown only for journals that use lots; see below.+ * *All accounts* ('a', '/balance'): all accounts, or those you search+ for, like balance.++ Each report shows a chart and then a table (by default; both can be+toggled). Click any amount to see the transactions it is made of.++* Menu:++* Options::+* Charts::+* From a report to its transactions::+* Holdings::+++File: hledger-web.info, Node: Options, Next: Charts, Up: REPORTS++5.1 Options+===========++A report's options (click Options, or press 'o') change what it shows.+These are similar to hledger's command-line options and hledger-ui's+keys. The main ones, with their keyboard shortcuts:++ * *Interval* ('D', 'W', 'M', 'Q', 'Y'): one column for the whole+ period, or one per day, week, month, quarter or year (see Report+ intervals). Until you choose one, the reports pick an interval to+ suit the period shown (except holdings, whose interval is its own;+ see Holdings): monthly for up to two years, quarterly for up to+ six, yearly beyond. Click a column's heading to see the report for+ just its dates.+ * *Show* ('H'): balance changes in each period, or ending balances+ (which include everything before the period). The balance sheet+ shows ending balances by default and the other reports show+ changes, as their commands do; the report's heading says which it+ is showing.+ * *Depth* ('0'-'9', '-', '+'): how many levels of accounts to show+ (see Depth). Depth 0 shows only the totals. Until you choose one,+ the depth is 1, the top-level accounts. The − and + beside the+ table's Account heading step it too. In tree mode they fold or+ open a level of the whole tree. (The sidebar has a depth of its+ own; see above.)+ * *Accounts* ('t'): a list, or a tree with subtotals; the List and+ Tree links beside the table's Account heading switch too. In a+ tree, the accounts below the depth limit are folded, and their+ carets open them in place (at depth 0, all of them, under each+ section's total).+ * *Amounts* ('B', 'V'): as recorded, at cost, or at market value at+ the end of each period (see Cost reporting and Value reporting).+ * *Zero balances* ('z'): hide or show accounts whose balance is zero.+ (On the holdings page, 'z' toggles Closed positions instead; use+ this option's links there.)+ * *Equity* (balance sheet only): hide or show the equity section.+ The browser remembers this choice for each hledger-web server.+ * *Status* ('U', 'P', 'C'), *Postings* ('R'), account types, and+ commodities: show only transactions with that status, only real+ postings, or only some account types or commodities. These rows+ edit the search, adding a term like 'status:*' or 'type:A'.+ Shift-click selects several types or commodities.++ The options you choose stay in effect as you move to other pages,+except Show, which each report sets to its own default. On the journal+and register, the report options are shown muted, but are kept.++ The search form filters reports as it does the other pages, and its+'date:' terms set the report's dates. An interval or depth typed in the+search, like 'date:monthly' or 'depth:2', moves into the options when+the page reloads. A depth limit for some accounts only, like+'depth:assets=3', stays in the search.++ The options are also URL parameters, so you can bookmark a report+with them.++ (For more detail, see the hledger manual, eg CONCEPTS.)+++File: hledger-web.info, Node: Charts, Next: From a report to its transactions, Prev: Options, Up: REPORTS++5.2 Charts+==========++A report's chart is the one its command draws with '--chart': eg a bar+per account, or with an interval, each account over time, and for the+statements, each section and the net total. In tree mode it shows the+accounts down to the depth limit. With several commodities, use the+legend, or the '[' and ']' keys, to choose the one charted. The Balance+page's and statements' charts stack each period's accounts (or sections)+in one bar, above and below zero; the Chart row in Options (or+'--chart=grouped' at startup) shows a bar per account type (or section),+side by side, instead (on the Balance page with no interval, for the+whole period, as 'balance --chart=grouped' does). '--chart' at startup+takes the same value as the commands' '--chart'; its SCALE amounts fix+the scales of the report and register charts, so that they can be+compared. Hover over a bar or a line (or on a touch screen, tap it) to+see its period (or date, or account), its series and its amount. Charts+are drawn as wide as the page shows them, and redrawn when that changes,+eg when you hide or show the sidebar or resize the window.++ The 'c' key hides or shows the chart, and 'd' the table (the report's+data). You can also click the Chart and Data buttons at their top right+corners, whose carets show whether they are shown. The 'N' key shows or+hides the net total line (or marks), eg a statement's net, or holdings'+value or net gain; this is hidden at first, leaving the bars it totals+(or with '--chart=net' at startup, shown at first). The browser+remembers this for each hledger-web server, and once you have chosen+with 'N', your choice wins over '--chart=net'.+++File: hledger-web.info, Node: From a report to its transactions, Next: Holdings, Prev: Charts, Up: REPORTS++5.3 From a report to its transactions+=====================================++Click an amount to see its account's register for that period: the+transactions the amount is made of. An ending balance's register starts+with the balance brought forward, so its final running balance is that+amount. A section's total shows the register of all the section's+accounts. An amount shown at cost or market value leads to a register+showing its amounts the same way.++ Some things can make the register look different from the report:++ * The statements show liabilities, equity and revenues as positive+ amounts, as their commands do, so their registers show the same+ amounts negated. The amount's tooltip says so.+ * When a posting has a date of its own, the report counts it on that+ date, but the register lists its whole transaction, on the+ transaction's date.+++File: hledger-web.info, Node: Holdings, Prev: From a report to its transactions, Up: REPORTS++5.4 Holdings+============++The holdings report shows one row for each commodity held in each+account, with its cost basis, value and gains. Its chart has a bar for+each one, showing its cost basis and unrealised gain or loss. Its own+options can show:++ * each lot separately (*Lots*, 'L'),+ * fully disposed positions and their realised gains (*Closed+ positions*, 'z'),+ * all values in the market valuation commodity (*Values*).++ Closed positions are hidden by default, as in the 'holdings' command,+but the totals' RGain and XIRR always include them; a note below the+table says how many are hidden, with a link to show them.++ Its depth limit doesn't fold accounts: as on the command line, it+merges the deeper accounts' positions, by commodity, into the accounts+at the limit.++ With an *Interval* chosen (it picks none by itself), it shows how+your holdings changed, like holdings with a report interval: a row for+each period's end, with the totals of all the holdings then, and a bar+for each in the chart. Each row's date links to the holdings on that+date. This page's interval is its own, since it makes a different+report here: choosing one doesn't change the other reports' interval,+nor theirs this page's, and an interval given at startup (eg '-M') is+theirs. Its *Gains* option chooses what the gain columns cover: each+period, the time since the report's start date, or the time since+acquisition (the default). With the first two, the chart shows those+gains: realised, and unrealised (hatched). 'H' toggles between gains+since acquisition and gains in each period.++ On journals that use lots, every page also has a Lots option, showing+lot subaccounts and per-lot postings.+++File: hledger-web.info, Node: URL PARAMETERS, Next: RELOADING, Prev: REPORTS, Up: Top++6 URL PARAMETERS+****************++A page's url includes its search and options, so a bookmark or a shared+link shows the same view. You can also write these urls yourself, eg+'/balancesheet?interval=monthly&depth=2' or+'/register?account=assets:bank'. These are the parameters, most+corresponding to hledger options:++ * 'q' - the search+ * 'account' - the account whose register to show (with its+ subaccounts, unless 'subs=0')+ * 'page' - which page of transactions to show, in the journal and+ register (1 is the newest)+ * 'interval' - 'daily', 'weekly', 'monthly', 'quarterly' or 'yearly'+ (like '-D', '-W', '-M', '-Q', '-Y'), or 'none' for one column;+ without it the reports pick one+ * 'hinterval' - the holdings page's own interval, in the same words;+ without it, none+ * 'depth' - a number (like '--depth'), or 'all' for no limit; without+ it, 1+ * 'accum' - 'change', 'historical' or 'cumulative' (like '--change',+ '-H', '--cumulative'); on the holdings page, with an interval, what+ the gains cover+ * 'value' - 'none', 'cost', or 'then', 'end', 'now' or a date,+ optionally followed by ',COMMODITY' (like '--value')+ * 'infer' - '1' to infer market prices from transaction costs too+ (like '--infer-market-prices')+ * 'empty' - '1' to show zero balances, '0' to hide them (like '-E')+ * 'list' - 'tree' or 'flat' (like '--tree', '--flat')+ * 'sort' - 'amount' (like '-S')+ * 'total', 'avg', 'pct' - '1' to add totals, averages, or show+ percentages (like '-T', '-A', '-%')+ * 'calc' - 'valuechange', 'gain' or 'count' (like '--valuechange',+ '--gain', '--count')+ * 'date2' - '1' to use secondary dates (like '--date2')+ * 'costs' - '1' to show costs, in the register+ * 'equity' - '1' or '0', on the balance sheet (the old+ '/balancesheetequity' address leads to 'equity=1')+ * 'lots' - '1' to show lots (like '--lots')+ * 'closed' - '1', on the holdings page, to show closed positions, '0'+ to hide them+ * 'chart' - 'grouped', on the Balance and statement pages, to chart+ each period's account types (or sections) side by side (like+ '--chart=grouped')+++File: hledger-web.info, Node: RELOADING, Next: JSON API, Prev: URL PARAMETERS, Up: Top++7 RELOADING+***********++hledger-web detects changes made to the files by other means (eg if you+edit it directly, outside of hledger-web), and it will show the new data+when you reload the page or navigate to a new page. If a change makes a+file unparseable, hledger-web will display an error message until the+file has been fixed.++ (If you are viewing files mounted from another machine, make sure+that both machines have roughly the same idea of what time it is.)+++File: hledger-web.info, Node: JSON API, Next: DEBUG OUTPUT, Prev: RELOADING, Up: Top++8 JSON API+**********++In addition to the web UI, hledger-web also serves a JSON API that can+be used to get data or add new transactions. If you want the JSON API+only, you can use the '--serve-api' flag. Eg:++$ hledger-web -f examples/sample.journal --serve-api+...++ You can get JSON data from these routes:++/version+/accountnames+/transactions+/prices+/commodities+/accounts+/accounttransactions/ACCOUNTNAME+/openapi.json++ Eg, all account names in the journal (similar to the accounts+command). (hledger-web's JSON does not include newlines, here we use+python to prettify it):++$ curl -s http://127.0.0.1:5000/accountnames | python3 -m json.tool+[+ "assets",+ "assets:bank",+ "assets:bank:checking",+ "assets:bank:saving",+ "assets:cash",+ "expenses",+ "expenses:food",+ "expenses:supplies",+ "income",+ "income:gifts",+ "income:salary",+ "liabilities",+ "liabilities:debts"+]++ Or all transactions:++$ curl -s http://127.0.0.1:5000/transactions | python3 -m json.tool+[+ {+ "tcode": "",+ "tcomment": "",+ "tdate": "2008-01-01",+ "tdate2": null,+ "tdescription": "income",+ "tindex": 1,+ "tpostings": [+ {+ "paccount": "assets:bank:checking",+ "pamount": [+ {+ "acommodity": "$",+ "acost": null,+ "acostbasis": null,+...++ Most of the JSON corresponds to hledger's data types; for details of+what the fields mean, see the Hledger.Data.Json haddock docs and click+on the various data types, eg Transaction. And for a higher level+understanding, see the journal docs. There is also a basic OpenAPI+specification, also served at '/openapi.json'.++ Some routes return a report type wrapping the data; eg+'/accounttransactions' returns an AccountTransactionsReport, a report+title and a list of items. The handlers in Hledger.Web.Handler.MiscR+show what each route returns.++ You can add a new transaction to the journal with a PUT request to+'/add', if hledger-web was started with '--allow=add' (the default when+listening on a local-only address). The payload must be the full, exact+JSON representation of a hledger transaction (partial data won't do).+The journal must still be readable with the transaction added, with+hledger-web's startup options (see Editing, uploading, downloading); if+not, the response has status 400 and the error message, and the journal+is not changed. You can get sample JSON from hledger-web's+'/transactions' or '/accounttransactions', or from hledger's print+command. Eg, this saves the first transaction of the sample journal to+'txn.json':++$ hledger -f examples/sample.journal print -O json | python3 -c 'import json,sys; json.dump(json.load(sys.stdin)[0], sys.stdout, indent=4)' > txn.json++ Here's how it looks (remember, this JSON corresponds to hledger's+Transaction and related data types):++{+ "tcode": "",+ "tcomment": "",+ "tdate": "2008-01-01",+ "tdate2": null,+ "tdescription": "income",+ "tindex": 1,+ "tpostings": [+ {+ "paccount": "assets:bank:checking",+ "pamount": [+ {+ "acommodity": "$",+ "acost": null,+ "acostbasis": null,+ "aquantity": {+ "decimalMantissa": 1,+ "decimalPlaces": 0,+ "floatingPoint": 1+ },+ "astyle": {+ "ascommodityside": "L",+ "ascommodityspaced": false,+ "asdecimalmark": ".",+ "asdigitgroups": null,+ "asprecision": 0,+ "asrounding": "NoRounding"+ }+ }+ ],+ "pbalanceassertion": null,+ "pcomment": "",+ "pdate": null,+ "pdate2": null,+ "poriginal": null,+ "preal": "RealPosting",+ "pstatus": "Unmarked",+ "ptags": [],+ "ptransaction_": "1"+ },+ {+ "paccount": "income:salary",+ "pamount": [+ {+ "acommodity": "$",+ "acost": null,+ "acostbasis": null,+ "aquantity": {+ "decimalMantissa": -1,+ "decimalPlaces": 0,+ "floatingPoint": -1+ },+ "astyle": {+ "ascommodityside": "L",+ "ascommodityspaced": false,+ "asdecimalmark": ".",+ "asdigitgroups": null,+ "asprecision": 0,+ "asrounding": "NoRounding"+ }+ }+ ],+ "pbalanceassertion": null,+ "pcomment": "",+ "pdate": null,+ "pdate2": null,+ "poriginal": null,+ "preal": "RealPosting",+ "pstatus": "Unmarked",+ "ptags": [],+ "ptransaction_": "1"+ }+ ],+ "tprecedingcomment": "",+ "tsourcepos": [+ {+ "sourceColumn": 1,+ "sourceLine": 31,+ "sourceName": "/home/user/hledger/examples/sample.journal"+ },+ {+ "sourceColumn": 1,+ "sourceLine": 34,+ "sourceName": "/home/user/hledger/examples/sample.journal"+ }+ ],+ "tstatus": "Unmarked",+ "ttags": []+}++ And here's how to add it with curl. This should append a new entry+to your journal file:++$ curl http://127.0.0.1:5000/add -X PUT -H 'Content-Type: application/json' --data-binary @txn.json+++File: hledger-web.info, Node: DEBUG OUTPUT, Next: LANGUAGE, Prev: JSON API, Up: Top++9 DEBUG OUTPUT+**************++You can add '--debug[=N]' to the command line to log debug output. N+ranges from 1 (least output, the default) to 9 (maximum output).+Typically you would start with 1 and increase until you are seeing+enough. Debug output goes to stderr, interleaved with the requests+logged on stdout. To capture debug output in a log file instead, you+can usually redirect stderr, eg:+'hledger-web --debug=3 2>hledger-web.log'.+++File: hledger-web.info, Node: LANGUAGE, Next: ENVIRONMENT, Prev: DEBUG OUTPUT, Up: Top++10 LANGUAGE+***********++hledger-web's pages can be shown in another language when a translation+catalog is available (see Languages in the hledger manual).++ When hledger-web is started with '--lang LANG', eg '--lang de', every+page is in that language, whatever the browser asks for. So you can use+hledger-web in a language other than your browser's, or give every user+of a shared server the same language.++ Otherwise the language is chosen per request, and the first of these+naming an available translation wins:++ 1. a '_LANG' query parameter, eg '?_LANG=de'. This choice is+ remembered in a '_LANG' cookie.+ 2. the '_LANG' cookie+ 3. the browser's 'Accept-Language' header, ie the browser's or+ system's language settings++ If none does, pages are in English, or with '--lang auto', in the+language of hledger-web's environment. So viewers usually get their+browser's language automatically, if hledger-web has it. Catalogs,+including any in the config directory, are loaded when hledger-web+starts.+++File: hledger-web.info, Node: ENVIRONMENT, Next: BUGS, Prev: LANGUAGE, Up: Top++11 ENVIRONMENT+**************++*LEDGER_FILE* The main journal file to use when not specified with+'-f/--file'. Default: '$HOME/.hledger.journal'.+++File: hledger-web.info, Node: BUGS, Prev: ENVIRONMENT, Up: Top++12 BUGS+*******++We welcome bug reports in the hledger issue tracker+(https://bugs.hledger.org), or on the hledger chat or mail list+(https://hledger.org/support).++ Some known issues:++ Without JavaScript (eg in text-mode browsers), pages can be viewed+and their links followed, but the add form, help dialog, keyboard+shortcuts, sidebar toggle and folding don't work.+++Tag Table:+Node: Top223+Node: OPTIONS2577+Node: WEB UI15201+Node: PERMISSIONS21325+Node: EDITING UPLOADING DOWNLOADING22579+Node: REPORTS23966+Node: Options25177+Node: Charts28323+Node: From a report to its transactions30122+Node: Holdings31121+Node: URL PARAMETERS32942+Node: RELOADING35215+Node: JSON API35781+Node: DEBUG OUTPUT41753+Node: LANGUAGE42292+Node: ENVIRONMENT43417+Node: BUGS43651++End Tag Table+++Local Variables:+coding: utf-8+End:
+ embeddedfiles/hledger-web.md view
@@ -0,0 +1,32 @@+# hledger-web++> A web interface and API for `hledger`, a robust, friendly plain text accounting app.+> More information: <https://hledger.org/hledger-web.html>.++- Start the web app, and a browser if possible, for local viewing and adding only:++`hledger-web`++- As above but with a specified file, and allow editing of existing data:++`hledger-web --file {{path/to/file.journal}} --allow edit`++- Start just the web app, and accept incoming connections to the specified host and port:++`hledger-web --serve --host {{my.host.name}} --port 8000`++- Start just the web app's JSON API, and allow only read access:++`hledger-web --serve-api --host {{my.host.name}} --allow view`++- Show amounts converted to current market value in your base currency when known:++`hledger-web --value now --infer-market-prices`++- Show the manual in Info format if possible:++`hledger-web --info`++- Display help:++`hledger-web --help`
+ embeddedfiles/hledger-web.txt view
@@ -0,0 +1,920 @@++HLEDGER-WEB(1) hledger User Manuals HLEDGER-WEB(1)++NAME+ hledger-web - web interface and API for hledger, a robust, friendly plain+ text accounting app.++SYNOPSIS+ hledger-web [OPTS] [QUERY]+ or+ hledger web [OPTS] [QUERY]++DESCRIPTION+ This manual is for hledger's web 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+ tracking money, time, or any other commodity, using double-entry accounting+ and a simple, editable file format. hledger is inspired by and largely+ compatible with ledger(1), and largely interconvertible with beancount(1).++ hledger-web is hledger's web interface. In a web browser, it shows the+ journal, account registers, and the main financial reports with their+ charts, and lets you search them, add transactions, and (if allowed) edit+ the journal files. It shows more at once than the hledger CLI or+ hledger-ui (eg the accounts beside a register, or a report's chart above+ its table), and every view has its own url, so it can be bookmarked or+ shared.++ hledger-web also lets you share a journal with multiple users, or even the+ public web. There is no user authentication, so if you need that you+ should put it behind a suitable web proxy (see Permissions).++ 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+ hledger(1) -> Input for details.)++ hledger-web can be run in three modes:++ * --serve-browse mode (the default): the app serves the web UI and JSON+ API, and opens your default web browser to show the app if possible, and+ exits automatically once no browser window has shown it for fifteen min-+ utes.++ * --serve: the app just serves the web UI and JSON API.++ * --serve-api: the app just serves the JSON API.++ In all cases hledger-web runs as a foreground process, logging requests to+ stdout.++OPTIONS+ hledger-web provides the following command line options:++ Flags:+ --serve-browse server mode: serve the web UI and JSON API,+ and open a browser, and exit if inactive for 15m+ (default)+ --serve server mode: just serve the web UI and JSON+ API+ --serve-api server mode: just serve the JSON API+ --allow=view|add|edit set the user's access level for changing data+ (default: `add` on a local-only address, `view`+ otherwise). It also accepts `sandstorm` for that+ platform (reading from the+ `X-Sandstorm-Permissions` request header).+ --cors=ORIGIN allow cross-origin requests from the specified+ origin; setting ORIGIN to "*" allows requests+ from any origin+ --host=IPADDR listen on this IP address (default: 127.0.0.1)+ --port=PORT listen on this TCP port (default: 5000); 0+ means a free port chosen by the OS+ --socket=SOCKET listen on the given unix socket instead of an+ IP address and port (only on unix)+ --base-url=BASEURL set the base url (default: http://IPADDR:PORT)+ --chart[=KIND,net,SCALE] set the charts' defaults, as the commands'+ --chart does. KIND: lay out the statements'+ charts with each period's sections in one bar,+ above and below zero (diverging, the default),+ or side by side (grouped). net: show the net+ total lines by default (the N key toggles them,+ and the browser remembers that). SCALE: the+ amount that fills the charts (eg 1000 or 1000+ USD; one per commodity), for comparable charts.+ --lang=LANG show the web UI in this language (en, de, es,+ ru, zh); or with auto, use each viewer's browser+ language if available, otherwise the server's.+ (Default: the browser's language if available,+ otherwise en.)++ By default hledger-web listens only on IP address 127.0.0.1, which can be+ accessed only from the local machine.++ To allow access from elsewhere, use --host to specify an externally acces-+ sible address configured on this machine. The special address 0.0.0.0+ causes it to listen on all of this machine's addresses.++ Similarly, you can use --port to listen on a TCP port other than 5000.+ This is useful if you want to run multiple hledger-web instances on a ma-+ chine. --port 0 makes the operating system choose a free port, which is+ reported in the startup message and in the default base url, and is where+ the browser is opened in --serve-browse mode. This can be useful eg when+ scripting.++ When --socket is used, hledger-web creates and communicates via a socket+ file instead of a TCP port. This can be more secure, respects unix file+ permissions, and makes certain use cases easier, such as running per-user+ instances behind an nginx reverse proxy. (Eg: proxy_pass+ http://unix:/tmp/hledger/${remote_user}.socket;.)++ You can use --base-url to change the protocol, hostname, port and path that+ appear in hledger-web's hyperlinks. This is useful eg when integrating+ hledger-web within a larger website. The default is http://HOST:PORT/ us-+ ing the server's configured host address and TCP port (or http://HOST if+ PORT is 80). Note this affects url generation but not route parsing.++ hledger-web also supports many of hledger's general options:++ 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.+ --alias=A=B|/RGX/=RPL transform account names from A to B, or by+ replacing regular expression matches+ --auto generate extra postings by applying auto posting+ rules ("=") to all transactions+ --forecast[=PERIOD] Generate extra transactions from periodic rules+ ("~"), from after the latest ordinary transaction+ until 6 months from now. Or, during the specified+ PERIOD (the equals is required). Auto posting rules+ will also be applied to these transactions. In+ hledger-ui, also make future-dated transactions+ visible at startup.+ --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)++ 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 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)+ --date2 match/use secondary dates instead (deprecated)+ -U --unmarked include only unmarked postings/transactions+ -P --pending include only pending postings/transactions+ -C --cleared include only cleared postings/transactions+ (-U/-P/-C can be combined)+ -R --real include only non-virtual postings+ -E --empty Show zero items, which are normally hidden.+ In hledger-ui & hledger-web, do the opposite.+ --depth=DEPTHEXP if a number (or -NUM): show only top NUM levels+ of accounts. If REGEXP=NUM, only apply limiting to+ accounts matching the regular expression.+ -B --cost 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? 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:+ -? 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+ --test[=PATTERN] run built-in tests (those matching PATTERN) and+ exit+ --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)++ Some of these can be adjusted while hledger-web is running, in the web UI's+ Options panel.++ hledger-web shows accounts with zero balances by default (like hledger-ui,+ and unlike hledger); -E/--empty starts it with them hidden instead. In the+ web UI, the Zero balances option or the z key shows or hides them. (The+ holdings page differs: its closed positions are hidden by default, as in+ the holdings command; -E starts it with them shown, and z there shows or+ hides them.)++ Report options and a query given at startup set the view hledger-web opens+ with, by putting them in its url (see URL parameters). Eg hledger-web -V+ -M opens /balancesheet?interval=monthly&value=end, and hledger-web+ --cleared -3 assets opens /balancesheet?q=assets status:*&depth=3. They+ are only a starting point: they can be changed in the web UI, and they+ don't affect other urls or the JSON API. Report options that hledger-web+ has no equivalent for are ignored.++ Note, a startup query doesn't restrict what hledger-web serves; to do that,+ give it a file holding only the entries to serve (eg one written by hledger+ print QUERY).++ 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.++WEB UI+ hledger-web's main views are:++ * the journal view, showing journal entries, newest first, with their post-+ ings++ * the report views, described below: the balance sheet, income statement,+ cashflow statement (and holdings, for journals using lots), and All ac-+ counts report++ * a register view for each account, reached by clicking an account name,+ showing the transactions affecting that account (and its subaccounts),+ with a running balance and a balance chart.++ Every page has, from the top: links to the journal and the reports, the+ search form, the options, and then the view itself. The options are hidden+ until you open them (click Options, or press o); while hidden, they list+ the ones in effect, eg "Monthly A Depth 2 A Tree".++ The journal and register show the newest 1000 matching transactions, with+ links to older and newer pages. When the transactions span more than one+ year, the options include a row of years, to narrow the view to one year;+ shift-click a second year to select a range of years.++ The register's chart shows the running balance over the page's transac-+ tions. With several commodities, use the legend, or the [ and ] keys, to+ choose the one charted. Click a point to go to its transaction, or drag+ across the chart to see the transactions of those dates. The register's+ Costs option shows the costs recorded with its amounts.++ The sidebar lists every account, and optionally their balances (parent bal-+ ances include subaccounts). The search doesn't change it, except that its+ dates set the balances' date. The balances are hidden at first, since on a+ large journal they take much of each page's time; click the "Balances"+ heading above the accounts to show them, or to hide them again. These are+ historical balances, as of the end of the report period set by date:, oth-+ erwise the latest (the heading shows the date). While the balances are+ hidden, all accounts are listed, even with Zero balances: Hidden. It is+ always a tree, with carets that fold and open each group, whether the Ac-+ counts option is List or Tree. The a and + above it fold or open a level+ of the whole tree, without changing the page; its depth is its own, apart+ from the page's depth limit. The browser remembers the sidebar's depth and+ the groups you open or close (until the next a or +). The button at the+ top left (or the s key) shows or hides the sidebar, and it stays the way+ you left it from page to page. On a narrow screen, it slides the sidebar+ in or out.++ Click an account name to see its register, with the search, or an amount to+ see the transactions it is made of. In the journal and register, click a+ date to see that day's journal entries.++ The search form filters every view with hledger's query syntax, eg expenses+ date:thismonth; the help dialog summarises the query types. The search and+ the options are part of the page's url (see URL parameters).++ The add form (press a, or click "Add a transaction" in the journal view)+ adds a transaction to the main journal file, if the access level allows it,+ and if the journal would still be readable with it added (see Editing, up-+ loading, downloading). It autocompletes account names and descriptions+ from your existing entries.++ The help dialog (press ?, or click the question mark button) lists these+ keyboard shortcuts, which work when you are not typing in a field:++ * h or ? - show or hide the help dialog++ * g - go to another page: shows a menu of the pages, each with its key;+ then j journal, b balance sheet, i income statement, c cashflow state-+ ment, h holdings (for journals using lots), a all accounts (escape to+ cancel)++ * n / p - go to the next / previous page, in the g menu's order, wrapping+ round++ * a - add a transaction (escape to cancel)++ * s - show or hide the sidebar++ * shift with 1-9 - fold or open the sidebar's accounts to that depth, as+ its a and + do (by the digit keys' place, whatever the layout; except+ where shift with one types a character that is a shortcut itself, eg a+ digit on AZERTY keyboards, or / on German ones)++ * b - show or hide the sidebar's balances, as its Balances heading does+ (while the sidebar shows)++ * o - show or hide the report options++ * c - show or hide the report's chart (on pages with one)++ * [ / ] - chart the previous / next commodity (on pages whose chart has+ several, wrapping round)++ * N - show or hide the chart's net total line (on pages whose chart has+ one)++ * d - show or hide the report's data, its table (on pages with a chart)++ * f - full window: show only the report's heading and data, or everything+ (s, o and / leave it, showing what they ask for)++ * z - show or hide accounts with zero balances (on the holdings page:+ closed positions)++ * t - show accounts as a tree, or a list++ * H - show ending balances, or balance changes++ * L - show or hide lot detail++ * V - show amounts at market value, or as recorded++ * B - show amounts at cost, or as recorded++ * R - show only real postings, or all++ * U, P, C - show only unmarked, pending, or cleared transactions, or all++ * S - sort by amount, or by account++ * T, A - add or remove the row total and average columns (multi-period re-+ ports)++ * D, W, M, Q, Y - set the report interval (daily, weekly, monthly, quar-+ terly, yearly); pressed again, remove it++ * 0-9, -, + - set or adjust the account depth limit (- and + step between 0+ and the deepest)++ * / - focus the search form, ready to add a term (escape to leave it)++ * Delete or Backspace - clear the search, as its clear button does++ The pages are light or dark, following your OS or browser's color scheme+ setting, and switch when it changes.++ Editing, uploading and downloading journal files is described below.++PERMISSIONS+ You can restrict who can access hledger-web by++ * setting the IP address it listens on (see --host above). By default it+ listens on 127.0.0.1, accessible to users on the local machine only.++ * or by putting it behind an authenticating proxy, such as caddy or apache++ * or by putting it behind a firewall.++ And you can restrict what the users reaching it can do, by specifying the+ --allow=ACCESSLEVEL option at startup. ACCESSLEVEL is one of:++ * view - allows viewing the journal file(s)++ * add - also allows adding new transactions to the main journal file++ * edit - also allows editing, uploading or downloading the journal file(s)++ * sandstorm - (for the hledger-web Sandstorm app:) allows whichever of+ view, add, or edit are specified in the X-Sandstorm-Permissions HTTP+ header++ The default access level is add when listening on a local-only address+ (127.0.0.1, ::1, localhost, or a unix socket), and view otherwise. To al-+ low more than the default access, start it with an explicit --allow=add or+ --allow=edit option.++EDITING, UPLOADING, DOWNLOADING+ If you start hledger-web with --allow=edit, you'll see a new "spanner" but-+ ton to the right of the search form. Clicking this will let you edit, up-+ load, or download the journal file or any files it includes.++ Note, unlike any other hledger command, in this mode you (or any visitor)+ can alter or wipe the data files. Before saving an edited or uploaded+ file, hledger-web saves a numbered backup of it (eg main.journal.1, then+ main.journal.2); if the backup can't be written, the file is not changed.+ (Adding a transaction appends it to the main journal file without making a+ backup.) hledger-web is not aware of version control systems, currently;+ if you use one, you'll have to arrange to commit the changes yourself.++ Changes which would leave the journal unreadable are refused, and the file+ is not changed. This applies to edits, uploads and added transactions.+ Each change is checked as the next read of the journal will check it, in+ the context of all the journal's files and with the options hledger-web was+ started with: so transactions must balance, balance assertions must pass+ (unless started with -I), lots must be valid, and with --strict, the strict+ checks must pass too.++REPORTS+ Besides the journal and the account registers, hledger-web shows these re-+ ports. The sidebar and the links at the top of every page lead to each of+ them, and so does the g key followed by the first letter of the report's+ name:++ * Balance sheet (b, /balancesheet): assets, liabilities and net worth, like+ the balancesheet command. Its Equity option adds an equity section, like+ balancesheetequity.++ * Income statement (i, /incomestatement): revenues, expenses and net in-+ come, like incomestatement.++ * Cashflow (c, /cashflow): changes in cash accounts, like cashflow.++ * Holdings (h, /holdings): investments and their performance, like hold-+ ings. Shown only for journals that use lots; see below.++ * All accounts (a, /balance): all accounts, or those you search for, like+ balance.++ Each report shows a chart and then a table (by default; both can be tog-+ gled). Click any amount to see the transactions it is made of.++ Options+ A report's options (click Options, or press o) change what it shows. These+ are similar to hledger's command-line options and hledger-ui's keys. The+ main ones, with their keyboard shortcuts:++ * Interval (D, W, M, Q, Y): one column for the whole period, or one per+ day, week, month, quarter or year (see Report intervals). Until you+ choose one, the reports pick an interval to suit the period shown (except+ holdings, whose interval is its own; see Holdings): monthly for up to two+ years, quarterly for up to six, yearly beyond. Click a column's heading+ to see the report for just its dates.++ * Show (H): balance changes in each period, or ending balances (which in-+ clude everything before the period). The balance sheet shows ending bal-+ ances by default and the other reports show changes, as their commands+ do; the report's heading says which it is showing.++ * Depth (0-9, -, +): how many levels of accounts to show (see Depth).+ Depth 0 shows only the totals. Until you choose one, the depth is 1, the+ top-level accounts. The a and + beside the table's Account heading step+ it too. In tree mode they fold or open a level of the whole tree. (The+ sidebar has a depth of its own; see above.)++ * Accounts (t): a list, or a tree with subtotals; the List and Tree links+ beside the table's Account heading switch too. In a tree, the accounts+ below the depth limit are folded, and their carets open them in place (at+ depth 0, all of them, under each section's total).++ * Amounts (B, V): as recorded, at cost, or at market value at the end of+ each period (see Cost reporting and Value reporting).++ * Zero balances (z): hide or show accounts whose balance is zero. (On the+ holdings page, z toggles Closed positions instead; use this option's+ links there.)++ * Equity (balance sheet only): hide or show the equity section. The+ browser remembers this choice for each hledger-web server.++ * Status (U, P, C), Postings (R), account types, and commodities: show only+ transactions with that status, only real postings, or only some account+ types or commodities. These rows edit the search, adding a term like+ status:* or type:A. Shift-click selects several types or commodities.++ The options you choose stay in effect as you move to other pages, except+ Show, which each report sets to its own default. On the journal and regis-+ ter, the report options are shown muted, but are kept.++ The search form filters reports as it does the other pages, and its date:+ terms set the report's dates. An interval or depth typed in the search,+ like date:monthly or depth:2, moves into the options when the page reloads.+ A depth limit for some accounts only, like depth:assets=3, stays in the+ search.++ The options are also URL parameters, so you can bookmark a report with+ them.++ (For more detail, see the hledger manual, eg CONCEPTS.)++ Charts+ A report's chart is the one its command draws with --chart: eg a bar per+ account, or with an interval, each account over time, and for the state-+ ments, each section and the net total. In tree mode it shows the accounts+ down to the depth limit. With several commodities, use the legend, or the+ [ and ] keys, to choose the one charted. The Balance page's and state-+ ments' charts stack each period's accounts (or sections) in one bar, above+ and below zero; the Chart row in Options (or --chart=grouped at startup)+ shows a bar per account type (or section), side by side, instead (on the+ Balance page with no interval, for the whole period, as balance+ --chart=grouped does). --chart at startup takes the same value as the com-+ mands' --chart; its SCALE amounts fix the scales of the report and register+ charts, so that they can be compared. Hover over a bar or a line (or on a+ touch screen, tap it) to see its period (or date, or account), its series+ and its amount. Charts are drawn as wide as the page shows them, and re-+ drawn when that changes, eg when you hide or show the sidebar or resize the+ window.++ The c key hides or shows the chart, and d the table (the report's data).+ You can also click the Chart and Data buttons at their top right corners,+ whose carets show whether they are shown. The N key shows or hides the net+ total line (or marks), eg a statement's net, or holdings' value or net+ gain; this is hidden at first, leaving the bars it totals (or with+ --chart=net at startup, shown at first). The browser remembers this for+ each hledger-web server, and once you have chosen with N, your choice wins+ over --chart=net.++ From a report to its transactions+ Click an amount to see its account's register for that period: the transac-+ tions the amount is made of. An ending balance's register starts with the+ balance brought forward, so its final running balance is that amount. A+ section's total shows the register of all the section's accounts. An+ amount shown at cost or market value leads to a register showing its+ amounts the same way.++ Some things can make the register look different from the report:++ * The statements show liabilities, equity and revenues as positive amounts,+ as their commands do, so their registers show the same amounts negated.+ The amount's tooltip says so.++ * When a posting has a date of its own, the report counts it on that date,+ but the register lists its whole transaction, on the transaction's date.++ Holdings+ The holdings report shows one row for each commodity held in each account,+ with its cost basis, value and gains. Its chart has a bar for each one,+ showing its cost basis and unrealised gain or loss. Its own options can+ show:++ * each lot separately (Lots, L),++ * fully disposed positions and their realised gains (Closed positions, z),++ * all values in the market valuation commodity (Values).++ Closed positions are hidden by default, as in the holdings command, but the+ totals' RGain and XIRR always include them; a note below the table says how+ many are hidden, with a link to show them.++ Its depth limit doesn't fold accounts: as on the command line, it merges+ the deeper accounts' positions, by commodity, into the accounts at the+ limit.++ With an Interval chosen (it picks none by itself), it shows how your hold-+ ings changed, like holdings with a report interval: a row for each period's+ end, with the totals of all the holdings then, and a bar for each in the+ chart. Each row's date links to the holdings on that date. This page's+ interval is its own, since it makes a different report here: choosing one+ doesn't change the other reports' interval, nor theirs this page's, and an+ interval given at startup (eg -M) is theirs. Its Gains option chooses what+ the gain columns cover: each period, the time since the report's start+ date, or the time since acquisition (the default). With the first two, the+ chart shows those gains: realised, and unrealised (hatched). H toggles be-+ tween gains since acquisition and gains in each period.++ On journals that use lots, every page also has a Lots option, showing lot+ subaccounts and per-lot postings.++URL PARAMETERS+ A page's url includes its search and options, so a bookmark or a shared+ link shows the same view. You can also write these urls yourself, eg /bal-+ ancesheet?interval=monthly&depth=2 or /register?account=assets:bank. These+ are the parameters, most corresponding to hledger options:++ * q - the search++ * account - the account whose register to show (with its subaccounts, un-+ less subs=0)++ * page - which page of transactions to show, in the journal and register (1+ is the newest)++ * interval - daily, weekly, monthly, quarterly or yearly (like -D, -W, -M,+ -Q, -Y), or none for one column; without it the reports pick one++ * hinterval - the holdings page's own interval, in the same words; without+ it, none++ * depth - a number (like --depth), or all for no limit; without it, 1++ * accum - change, historical or cumulative (like --change, -H, --cumula-+ tive); on the holdings page, with an interval, what the gains cover++ * value - none, cost, or then, end, now or a date, optionally followed by+ ,COMMODITY (like --value)++ * infer - 1 to infer market prices from transaction costs too (like --in-+ fer-market-prices)++ * empty - 1 to show zero balances, 0 to hide them (like -E)++ * list - tree or flat (like --tree, --flat)++ * sort - amount (like -S)++ * total, avg, pct - 1 to add totals, averages, or show percentages (like+ -T, -A, -%)++ * calc - valuechange, gain or count (like --valuechange, --gain, --count)++ * date2 - 1 to use secondary dates (like --date2)++ * costs - 1 to show costs, in the register++ * equity - 1 or 0, on the balance sheet (the old /balancesheetequity ad-+ dress leads to equity=1)++ * lots - 1 to show lots (like --lots)++ * closed - 1, on the holdings page, to show closed positions, 0 to hide+ them++ * chart - grouped, on the Balance and statement pages, to chart each pe-+ riod's account types (or sections) side by side (like --chart=grouped)++RELOADING+ hledger-web detects changes made to the files by other means (eg if you+ edit it directly, outside of hledger-web), and it will show the new data+ when you reload the page or navigate to a new page. If a change makes a+ file unparseable, hledger-web will display an error message until the file+ has been fixed.++ (If you are viewing files mounted from another machine, make sure that both+ machines have roughly the same idea of what time it is.)++JSON API+ In addition to the web UI, hledger-web also serves a JSON API that can be+ used to get data or add new transactions. If you want the JSON API only,+ you can use the --serve-api flag. Eg:++ $ hledger-web -f examples/sample.journal --serve-api+ ...++ You can get JSON data from these routes:++ /version+ /accountnames+ /transactions+ /prices+ /commodities+ /accounts+ /accounttransactions/ACCOUNTNAME+ /openapi.json++ Eg, all account names in the journal (similar to the accounts command).+ (hledger-web's JSON does not include newlines, here we use python to pret-+ tify it):++ $ curl -s http://127.0.0.1:5000/accountnames | python3 -m json.tool+ [+ "assets",+ "assets:bank",+ "assets:bank:checking",+ "assets:bank:saving",+ "assets:cash",+ "expenses",+ "expenses:food",+ "expenses:supplies",+ "income",+ "income:gifts",+ "income:salary",+ "liabilities",+ "liabilities:debts"+ ]++ Or all transactions:++ $ curl -s http://127.0.0.1:5000/transactions | python3 -m json.tool+ [+ {+ "tcode": "",+ "tcomment": "",+ "tdate": "2008-01-01",+ "tdate2": null,+ "tdescription": "income",+ "tindex": 1,+ "tpostings": [+ {+ "paccount": "assets:bank:checking",+ "pamount": [+ {+ "acommodity": "$",+ "acost": null,+ "acostbasis": null,+ ...++ Most of the JSON corresponds to hledger's data types; for details of what+ the fields mean, see the Hledger.Data.Json haddock docs and click on the+ various data types, eg Transaction. And for a higher level understanding,+ see the journal docs. There is also a basic OpenAPI specification, also+ served at /openapi.json.++ Some routes return a report type wrapping the data; eg /accounttransactions+ returns an AccountTransactionsReport, a report title and a list of items.+ The handlers in Hledger.Web.Handler.MiscR show what each route returns.++ You can add a new transaction to the journal with a PUT request to /add, if+ hledger-web was started with --allow=add (the default when listening on a+ local-only address). The payload must be the full, exact JSON representa-+ tion of a hledger transaction (partial data won't do). The journal must+ still be readable with the transaction added, with hledger-web's startup+ options (see Editing, uploading, downloading); if not, the response has+ status 400 and the error message, and the journal is not changed. You can+ get sample JSON from hledger-web's /transactions or /accounttransactions,+ or from hledger's print command. Eg, this saves the first transaction of+ the sample journal to txn.json:++ $ hledger -f examples/sample.journal print -O json | python3 -c 'import json,sys; json.dump(json.load(sys.stdin)[0], sys.stdout, indent=4)' > txn.json++ Here's how it looks (remember, this JSON corresponds to hledger's Transac-+ tion and related data types):++ {+ "tcode": "",+ "tcomment": "",+ "tdate": "2008-01-01",+ "tdate2": null,+ "tdescription": "income",+ "tindex": 1,+ "tpostings": [+ {+ "paccount": "assets:bank:checking",+ "pamount": [+ {+ "acommodity": "$",+ "acost": null,+ "acostbasis": null,+ "aquantity": {+ "decimalMantissa": 1,+ "decimalPlaces": 0,+ "floatingPoint": 1+ },+ "astyle": {+ "ascommodityside": "L",+ "ascommodityspaced": false,+ "asdecimalmark": ".",+ "asdigitgroups": null,+ "asprecision": 0,+ "asrounding": "NoRounding"+ }+ }+ ],+ "pbalanceassertion": null,+ "pcomment": "",+ "pdate": null,+ "pdate2": null,+ "poriginal": null,+ "preal": "RealPosting",+ "pstatus": "Unmarked",+ "ptags": [],+ "ptransaction_": "1"+ },+ {+ "paccount": "income:salary",+ "pamount": [+ {+ "acommodity": "$",+ "acost": null,+ "acostbasis": null,+ "aquantity": {+ "decimalMantissa": -1,+ "decimalPlaces": 0,+ "floatingPoint": -1+ },+ "astyle": {+ "ascommodityside": "L",+ "ascommodityspaced": false,+ "asdecimalmark": ".",+ "asdigitgroups": null,+ "asprecision": 0,+ "asrounding": "NoRounding"+ }+ }+ ],+ "pbalanceassertion": null,+ "pcomment": "",+ "pdate": null,+ "pdate2": null,+ "poriginal": null,+ "preal": "RealPosting",+ "pstatus": "Unmarked",+ "ptags": [],+ "ptransaction_": "1"+ }+ ],+ "tprecedingcomment": "",+ "tsourcepos": [+ {+ "sourceColumn": 1,+ "sourceLine": 31,+ "sourceName": "/home/user/hledger/examples/sample.journal"+ },+ {+ "sourceColumn": 1,+ "sourceLine": 34,+ "sourceName": "/home/user/hledger/examples/sample.journal"+ }+ ],+ "tstatus": "Unmarked",+ "ttags": []+ }++ And here's how to add it with curl. This should append a new entry to your+ journal file:++ $ curl http://127.0.0.1:5000/add -X PUT -H 'Content-Type: application/json' --data-binary @txn.json++DEBUG OUTPUT+ You can add --debug[=N] to the command line to log debug output. N ranges+ from 1 (least output, the default) to 9 (maximum output). Typically you+ would start with 1 and increase until you are seeing enough. Debug output+ goes to stderr, interleaved with the requests logged on stdout. To capture+ debug output in a log file instead, you can usually redirect stderr, eg:+ hledger-web --debug=3 2>hledger-web.log.++LANGUAGE+ hledger-web's pages can be shown in another language when a translation+ catalog is available (see Languages in the hledger manual).++ When hledger-web is started with --lang LANG, eg --lang de, every page is+ in that language, whatever the browser asks for. So you can use+ hledger-web in a language other than your browser's, or give every user of+ a shared server the same language.++ Otherwise the language is chosen per request, and the first of these naming+ an available translation wins:++ 1. a _LANG query parameter, eg ?_LANG=de. This choice is remembered in a+ _LANG cookie.++ 2. the _LANG cookie++ 3. the browser's Accept-Language header, ie the browser's or system's lan-+ guage settings++ If none does, pages are in English, or with --lang auto, in the language of+ hledger-web's environment. So viewers usually get their browser's language+ automatically, if hledger-web has it. Catalogs, including any in the con-+ fig directory, are loaded when hledger-web starts.++ENVIRONMENT+ LEDGER_FILE The main journal file to use when not specified with -f/--file.+ Default: $HOME/.hledger.journal.++BUGS+ We welcome bug reports in the hledger issue tracker+ (https://bugs.hledger.org), or on the hledger chat or mail list+ (https://hledger.org/support).++ Some known issues:++ Without JavaScript (eg in text-mode browsers), pages can be viewed and+ their links followed, but the add form, help dialog, keyboard shortcuts,+ sidebar toggle and folding don't work.++++AUTHORS+ Simon Michael <simon@joyful.com> and contributors.+ See http://hledger.org/CREDITS.html+++COPYRIGHT+ Copyright 2007-2023 Simon Michael and contributors.+++LICENSE+ Released under GNU GPL v3 or later.+++SEE ALSO+ hledger(1), hledger-ui(1), hledger-web(1), ledger(1)++hledger-web-2.0 December 2026 HLEDGER-WEB(1)
+ embeddedfiles/hledger.1 view
@@ -0,0 +1,18667 @@+.\"t++.TH "HLEDGER" "1" "December 2026" "hledger-2.0 " "hledger User Manuals"++++.SH NAME+hledger \- a robust, friendly plain text accounting app (command line+version).+.SH SYNOPSIS+\f[CR]hledger\f[R]+.PD 0+.P+.PD+or+.PD 0+.P+.PD+\f[CR]hledger COMMAND [OPTS] [ARGS]\f[R]+.SH DESCRIPTION+hledger is a robust, user\-friendly, cross\-platform set of programs for+tracking money, time, or any other commodity, using double\-entry+accounting and a simple, editable file format.+hledger is inspired by and largely compatible with ledger(1), and+largely interconvertible with beancount(1).+.PP+This manual is for hledger\(aqs command line interface, version 2.0.+It also describes the common options, file formats and concepts used by+all hledger programs.+It might accidentally teach you some bookkeeping/accounting as well!+You don\(aqt need to know everything in here to use hledger+productively, but when you have a question about functionality, this doc+should answer it.+It is detailed, so do skip ahead or skim when needed.+You can read it on hledger.org, or as an info manual or man page on your+system.+You can also open a built\-in copy, at a point of interest, by running+.PD 0+.P+.PD+\f[CR]hledger help [TOPIC]\f[R].+.PP+The main function of the hledger CLI is to read plain text files+describing financial transactions, crunch the numbers, and print a+useful report or chart on the terminal (or save it as HTML, CSV, JSON,+SQL or SVG).+Many reports are available, as subcommands.+hledger will also detect other \f[CR]hledger\-*\f[R] executables as+extra subcommands.+.PP+hledger usually reads from (and appends to) a journal file specified by+the \f[CR]LEDGER_FILE\f[R] environment variable (defaulting to+\f[CR]$HOME/.hledger.journal\f[R]); or you can specify files with+\f[CR]\-f\f[R] options.+It can also read timeclock files, timedot files, or any CSV/SSV/TSV file+with a date field.+.PP+Here is a small journal file, describing some starting balances and two+transactions:+.IP+.EX+2025\-01\-01 * opening balances+ assets:bank:checking $1000 = $1000+ assets:cash $100 = $100+ liabilities:creditcard $\-50 = $\-50+ equity:opening/closing balances++2025\-01\-10 * gift received+ income:gifts $\-20+ assets:cash $20++2025\-01\-12 farmers market+ assets:cash $\-13+ expenses:food $13+.EE+.PP+Transactions are dated movements of money (etc.)+between two or more \f[I]accounts\f[R]: bank accounts, your wallet,+revenue/expense categories, people, etc.+You can choose any account names you wish, using \f[CR]:\f[R] to+indicate subaccounts.+There must be at least two spaces between account name and amount.+Positive amounts are inflow to that account (\f[I]debit\f[R]), negatives+are outflow from it (\f[I]credit\f[R]).+(Some reports show revenue, liability and equity account balances as+negative numbers as a result; this is normal.)+.PP+Some details from this example: the first entry records your real\-world+balances on a starting date, with the equity account absorbing the+difference (its amount is inferred); the \f[CR]= AMOUNT\f[R] parts are+optional balance assertions, for extra error checking; the \f[CR]*\f[R]+after a date is an optional status mark, meaning \(dqcleared\(dq; and+the currency symbols are optional, but a good habit.+.PP+hledger\(cqs add command can help you add transactions, or you can+install other data entry UIs like hledger\-web or hledger\-iadd.+For more extensive/efficient changes, use a text editor: Emacs ++ledger\-mode, VIM + vim\-ledger, or VS Code + hledger\-vscode are some+good choices (see https://hledger.org/editors.html).+.PP+To get started, run \f[CR]hledger add\f[R] and follow the prompts, or+save some entries like the above in \f[CR]$HOME/.hledger.journal\f[R],+then try commands like:+.IP+.EX+$ hledger print \-x+$ hledger aregister assets+$ hledger balance+$ hledger balancesheet+$ hledger incomestatement+$ hledger incomestatement \-M \-\-chart+.EE+.PP+Run \f[CR]hledger\f[R] to list the commands.+.PP+In this manual, we\(aqll cover all of hledger\(aqs functionality in+detail.+For a more gentle step by step introduction, see hledger by example, or+for a faster intro, the 5 minute quick start.+.PP+For tips on configuring a default journal file, reconciling with your+bank, closing a file at end of year, or migrating between hledger 1 and+2, see PART 6: COMMON TASKS.+.SH PART 1: USER INTERFACE+.SH Input+hledger reads one or more data files, each time you run it.+You can specify a file with \f[CR]\-f\f[R], like so+.IP+.EX+$ hledger \-f FILE [\-f FILE2 ...] print+.EE+.PP+Files are most often in hledger\(aqs journal format, with the+\f[CR].journal\f[R] file extension (\f[CR].hledger\f[R] or \f[CR].j\f[R]+also work); these files describe transactions, like an accounting+general journal.+.PP+When no file is specified, hledger looks for \f[CR].hledger.journal\f[R]+in your home directory.+.PP+But most people prefer to keep financial files in a dedicated folder,+perhaps with version control.+Also, starting a new journal file each year is common (it\(aqs not+required, but helps keep things fast and organised).+So we usually configure a different journal file, by setting the+\f[CR]LEDGER_FILE\f[R] environment variable, to something like+\f[CR]\(ti/finance/2023.journal\f[R].+For more about how to do that on your system, see Common tasks > Setting+LEDGER_FILE.+.SS Text encoding+hledger expects non\-ascii input to be decodable with the system+locale\(aqs text encoding.+(For CSV/SSV/TSV files, this can be overridden by the+\f[CR]encoding\f[R] CSV rule.)+.PP+So, trying to read non\-ascii files which have the wrong text encoding,+or when no system locale is configured, will fail.+To fix this, configure your system locale appropriately, and/or convert+the files to your system\(aqs text encoding (using \f[CR]iconv\f[R] on+unix, or powershell or notepad on Windows).+See Install: Text encoding for more tips.+.PP+hledger\(aqs output will use the system locale\(aqs encoding.+.PP+hledger\(aqs docs and example files mostly use UTF\-8 encoding.+.SS Data formats+Usually the data file is in hledger\(aqs journal format, but it can be+in any of the supported file formats, which currently are:+.PP+.TS+tab(@);+lw(13.5n) lw(33.0n) lw(23.5n).+T{+Reader:+T}@T{+Reads:+T}@T{+Automatically used for files with extensions:+T}+_+T{+\f[CR]journal\f[R]+T}@T{+hledger journal files and some Ledger journals, for transactions+T}@T{+\f[CR].journal\f[R] \f[CR].j\f[R] \f[CR].hledger\f[R] \f[CR].ledger\f[R]+T}+T{+\f[CR]timeclock\f[R]+T}@T{+timeclock files, for precise time logging+T}@T{+\f[CR].timeclock\f[R]+T}+T{+\f[CR]timedot\f[R]+T}@T{+timedot files, for approximate time logging+T}@T{+\f[CR].timedot\f[R]+T}+T{+\f[CR]csv\f[R]+T}@T{+Comma\- or other delimiter\-separated values, for data import+T}@T{+\f[CR].csv\f[R]+T}+T{+\f[CR]ssv\f[R]+T}@T{+Semicolon separated values+T}@T{+\f[CR].ssv\f[R]+T}+T{+\f[CR]tsv\f[R]+T}@T{+Tab separated values+T}@T{+\f[CR].tsv\f[R]+T}+T{+\f[CR]rules\f[R]+T}@T{+CSV/SSV/TSV/other separated values, alternate way+T}@T{+\f[CR].rules\f[R]+T}+.TE+.PP+These formats are described in more detail below.+.PP+hledger detects the format automatically based on the file extensions+shown above.+If it can\(aqt recognise the file extension, it assumes+\f[CR]journal\f[R] format.+So for non\-journal files, it\(aqs important to use a recognised file+extension, so as to either read successfully or to show relevant error+messages.+.PP+You can also force a specific reader/format by prefixing the file path+with the format and a colon.+Eg, to read a .dat file containing tab separated values:+.IP+.EX+$ hledger \-f tsv:/some/file.dat stats+.EE+.SS Standard input+The file name \f[CR]\-\f[R] means standard input:+.IP+.EX+$ cat FILE | hledger \-f\- print+.EE+.PP+If reading non\-journal data in this way, you\(aqll need to write the+format as a prefix, like \f[CR]timeclock:\f[R] here:+.IP+.EX+$ echo \(aqi 2009/13/1 08:00:00\(aq | hledger print \-f timeclock:\-+.EE+.SS Multiple files+You can specify multiple \f[CR]\-f\f[R] options, to read multiple files+as one big journal.+When doing this, note that certain features (described below) will be+affected:+.IP \(bu 2+Balance assertions will not see the effect of transactions in previous+files.+(Usually this doesn\(aqt matter as each file will set the corresponding+opening balances.)+.IP \(bu 2+Some directives will not affect previous or subsequent files.+.PP+If needed, you can work around these by using a single parent file which+includes the others (this works with CSV files too), or concatenating+the files into one, eg:+\f[CR]cat a.journal b.journal | hledger \-f\- CMD\f[R].+.SS Strict mode+hledger checks input files for valid data.+By default, the most important errors are detected, while still+accepting easy journal files without a lot of declarations:+.IP \(bu 2+Are the input files parseable, with valid syntax ?+.IP \(bu 2+Are all transactions balanced ?+.IP \(bu 2+Do all balance assertions pass ?+.PP+With the \f[CR]\-s\f[R]/\f[CR]\-\-strict\f[R] flag, additional checks+are performed:+.IP \(bu 2+Are all accounts posted to, declared with an \f[CR]account\f[R]+directive ?+(Account error checking)+.IP \(bu 2+Are all commodities declared with a \f[CR]commodity\f[R] directive ?+(Commodity error checking)+.IP \(bu 2+Are all commodity conversions declared explicitly ?+.PP+You can use the check command to run individual checks \- the ones+listed above and some more.+.SH Commands+hledger provides various subcommands for getting things done.+Most of these commands do not change the journal file; they just read it+and output a report.+A few commands assist with adding data and file management.+Some commands to start with:+.IP \(bu 2+\f[CR]hledger add\f[R] \- add transactions, with interactive prompts+.IP \(bu 2+\f[CR]hledger print\f[R] \- show journal entries+.IP \(bu 2+\f[CR]hledger aregister assets:checking\f[R] (\f[CR]areg\f[R]) \- show+one account\(aqs transactions and running balance+.IP \(bu 2+\f[CR]hledger balancesheet\f[R] (\f[CR]bs\f[R]) \- show assets,+liabilities and net worth+.IP \(bu 2+\f[CR]hledger incomestatement\f[R] (\f[CR]is\f[R]) \- show revenues and+expenses+.PP+To show a summary of commands, run \f[CR]hledger\f[R] with no arguments.+See also PART 2: COMMANDS below.+.PP+To use a particular command, run+\f[CR]hledger CMD [CMDOPTS] [CMDARGS]\f[R],+.IP \(bu 2+CMD is the full command name, or its standard abbreviation shown in the+commands list, or any unambiguous prefix of the name.+.IP \(bu 2+CMDOPTS are command\-specific options, if any.+Command\-specific options must be written after the command name.+Eg: \f[CR]hledger print \-x\f[R].+.IP \(bu 2+CMDARGS are additional arguments to the command, if any.+Most hledger commands accept arguments representing a query, to limit+the data in some way.+Eg: \f[CR]hledger reg assets:checking\f[R].+.PP+To list a command\(aqs options, arguments, and documentation in the+terminal, run \f[CR]hledger CMD \-h\f[R].+Eg: \f[CR]hledger bal \-h\f[R].+.SS Add\-on commands+In addition to the built\-in commands, you can install \f[I]add\-on+commands\f[R], which will also appear in hledger\(aqs commands list.+Some of these can be installed as separate packages; others can be found+in hledger\(aqs bin/ directory, documented at+https://hledger.org/scripts.html.+.PP+Add\-on commands are programs or scripts in your shell\(aqs PATH, whose+name starts with \(dqhledger\-\(dq and ends with no extension or a+recognised extension (\(dq.bat\(dq, \(dq.com\(dq, \(dq.exe\(dq,+\(dq.hs\(dq, \(dq.js\(dq, \(dq.lhs\(dq, \(dq.lua\(dq, \(dq.php\(dq,+\(dq.pl\(dq, \(dq.py\(dq, \(dq.rb\(dq, \(dq.rkt\(dq, or \(dq.sh\(dq),+and (on unix and mac) which has executable permission for the current+user.+.PP+You can run add\-on commands directly: \f[CR]hledger\-ui \-\-watch\f[R].+.PP+Or you can run them with hledger, like built\-in commands:+\f[CR]hledger ui \-\-watch\f[R].+In this case hledger\(aqs config file will be used, so you can set+custom options for the addon there.+(Before hledger 1.50, an \f[CR]\-\-\f[R] argument was needed before+addon options, but not any more.)+.PP+Arguments written after the command name are passed on to the add\-on+unchanged, except for the options specific to the \f[CR]hledger\f[R] CLI+(\f[CR]\-\-conf\f[R], \f[CR]\-\-no\-conf\f[R], \f[CR]\-n\f[R]), which+hledger consumes.+To send one of those to the add\-on instead, write it after a+\f[CR]\-\-\f[R] argument: \f[CR]hledger ui \-\- \-n\f[R].+hledger consumes only that first \f[CR]\-\-\f[R]; later ones are passed+on like any other argument.+.SH Options+Run \f[CR]hledger \-h\f[R] to see general command line help.+Options can be written either before or after the command name.+These options are specific to the \f[CR]hledger\f[R] CLI:+.IP+.EX+Flags:+ \-\-conf=CONFFILE Use extra options defined in this config file. If+ not specified, searches upward and in XDG config+ dir for hledger.conf (or .hledger.conf in $HOME).+ \-n \-\-no\-conf ignore any config file+.EE+.PP+And the following general options are common to most hledger commands:+.IP+.EX+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.+ \-\-alias=A=B|/RGX/=RPL transform account names from A to B, or by+ replacing regular expression matches+ \-\-auto generate extra postings by applying auto posting+ rules (\(dq=\(dq) to all transactions+ \-\-forecast[=PERIOD] Generate extra transactions from periodic rules+ (\(dq\(ti\(dq), from after the latest ordinary transaction+ until 6 months from now. Or, during the specified+ PERIOD (the equals is required). Auto posting rules+ will also be applied to these transactions. In+ hledger\-ui, also make future\-dated transactions+ visible at startup.+ \-\-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)++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 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)+ \-\-date2 match/use secondary dates instead (deprecated)+ \-U \-\-unmarked include only unmarked postings/transactions+ \-P \-\-pending include only pending postings/transactions+ \-C \-\-cleared include only cleared postings/transactions+ (\-U/\-P/\-C can be combined)+ \-R \-\-real include only non\-virtual postings+ \-E \-\-empty Show zero items, which are normally hidden.+ In hledger\-ui & hledger\-web, do the opposite.+ \-\-depth=DEPTHEXP if a number (or \-NUM): show only top NUM levels+ of accounts. If REGEXP=NUM, only apply limiting to+ accounts matching the regular expression.+ \-B \-\-cost 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? 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:+ \-? 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+ \-\-test[=PATTERN] run built\-in tests (those matching PATTERN) and+ exit+ \-\-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+Usually hledger accepts any unambiguous flag prefix, eg you can write+\f[CR]\-\-dry\f[R] instead of \f[CR]\-\-dry\-run\f[R].+.PP+You can combine short flags which don\(aqt take arguments, eg you can+write \f[CR]\-MAST\f[R] instead of \f[CR]\-M \-A \-S \-T\f[R].+Flags requiring an argument can\(aqt be combined in this way+(\f[CR]\-If FILE\f[R] won\(aqt work).+.PP+If the same option appears more than once in a command line, usually the+last (right\-most) wins.+Similarly, if mutually exclusive flags are used together, the+right\-most wins.+(When flags are mutually exclusive, they\(aqll usually have a group+prefix in \-\-help.)+.PP+With most commands, arguments are interpreted as a hledger query which+filters the data.+Some queries can be expressed either with options or with arguments.+.SS Config files+You can configure default command line options and arguments+conveniently in a hledger config file.+Config file options will be inserted near the start of your command+line, so you can override them with command line options.+.PP+You can specify a config file with the \f[CR]\-\-conf\f[R] option.+Otherwise, hledger will search for a default config file, in this order:+.IP \(bu 2+\f[CR]hledger.conf\f[R] in the current directory or above+.IP \(bu 2+\f[CR].hledger.conf\f[R] in your home directory+.IP \(bu 2+\f[CR]hledger.conf\f[R] in your XDG config+(\f[CR]\(ti/.config/hledger/hledger.conf\f[R]).+.PP+Only one config file is used.+Here\(aqs a small example:+.IP+.EX+\f[I]# General options, used with all hledger commands that support them.\f[R]+\-\-pretty++\f[I]# Command\-specific options.\f[R]+\f[B][print]\f[R]+\-\-explicit \-\-infer\-costs+.EE+.PP+And here is a commented starter config file:+https://github.com/hledgerorg/hledger/blob/main/hledger.conf.sample+.PP+You can put not only options, but also arguments in a config file.+.PP+You can ignore all config files by adding the+\f[CR]\-n\f[R]/\f[CR]\-\-no\-conf\f[R] flag to the command line.+This is recommended when using hledger in scripts.+When both \f[CR]\-\-conf\f[R] and \f[CR]\-\-no\-conf\f[R] options are+used, the right\-most wins.+.PP+Note, hledger 1 also reads config files, but some things written for+hledger 2 make it stop with an error: indented lines (including the+continuation lines of a multi\-line command alias), a \f[CR]#\f[R]+inside quotes, quotes around only part of an argument, and options in a+\f[CR][COMMAND]\f[R] section which that command doesn\(aqt have in+hledger 1.+(hledger 1 ignores single\-line command aliases, and unknown options in+the general section.)+In this situation, you can run hledger 1 with \f[CR]\-n\f[R], or give it+a separate config file with \f[CR]\-\-conf\f[R].+.SS Command aliases+In a config file you can also define command aliases: your own custom+commands, which expand to a longer command line (similar to git\(aqs+aliases).+(Since 1.99.4.)+Eg:+.IP+.EX+\f[B][alias]\f[R]+p = print+p1 = transactions+rev10 = balance type\f[B]:\f[R]R \-2 \-X\f[B]$\f[R] \-p \(aqevery 10 years from 2000\(aq+.EE+.PP+With this in your config file, you\(aqll see a \f[CR]rev10\f[R] command+in the \f[CR]hledger help commands\f[R] list, and+\f[CR]hledger rev10\f[R] will run the balance command above.+Options or arguments written at the command line will be added at the+end, usually overriding those in the alias; eg+\f[CR]hledger rev10 \-X €\f[R] will convert to \f[CR]€\f[R] instead of+\f[CR]$\f[R].+Command aliases can also be used in \f[CR]run\f[R] command scripts and+at the \f[CR]repl\f[R] prompt.+.PP+Each line in an \f[CR][alias]\f[R] section should look like+\f[CR]NAME = COMMAND [ARGS..]\f[R].+A command line can be continued on following lines by indenting them+more than the \f[CR]NAME\f[R]; the indented lines are joined to the+command line.+Blank lines and comment lines within it are ignored, so you can space it+out or comment out individual lines.+Eg:+.IP+.EX+\f[B][alias]\f[R]+rev10 = balance+ type\f[B]:\f[R]R+ \-2+ \-X\f[B]$\f[R]+ \-p \(aqevery 10 years from 2000\(aq+ \f[I]# \-\-drop 1\f[R]+.EE+.PP+(hledger 1 can\(aqt read these continuation lines; see Config files.)+.PP+Command aliases override addon commands with the same name, but they+can\(aqt override builtin command names or abbreviations like+\f[CR]balance\f[R] or \f[CR]bal\f[R].+If the same alias name is defined more than once, the last definition+wins.+.PP+An alias\(aqs command can be a hledger builtin command, addon command,+or another alias.+If there\(aqs a \f[CR][COMMAND]\f[R] options section for an alias\(aqs+resolved builtin command, that will also be applied.+.PP+Or if an alias\(aqs command line begins with \f[CR]!\f[R], the rest is+run as a shell command (with any extra command line arguments appended).+Eg:+.IP+.EX+\f[B][alias]\f[R]+git\-commit = \f[B]!\f[R] git commit \-p+jj\-commit = \f[B]!\f[R] jj commit \-i+.EE+.PP+For safety, shell command aliases run only if defined in a trusted+config file: one you gave explicitly with \f[CR]\-\-conf\f[R], or your+user config file (\f[CR]\(ti/.hledger.conf\f[R] or the XDG+\f[CR]hledger.conf\f[R]).+Shell commands in a nearby automatically\-found \f[CR]hledger.conf\f[R],+in the current directory or a parent directory, will not run \- this+prevents a config file from an untrusted downloaded or shared directory+from running arbitrary shell commands.+.SS Config file troubleshooting+A default config file (one which hledger finds and uses automatically,+without a \f[CR]\-\-conf\f[R] option) is convenient, but it can surprise+you, eg by quietly changing report output, or breaking scripts which use+hledger.+Some tips:+.IP "1." 3+Be mindful about what you put in your config file; consider the effect+on all your reports.+.IP "2." 3+If a hledger command isn\(aqt doing what you expect, try it again with+\f[CR]\-n\f[R], to see if a config file is to blame.+.IP "3." 3+Run \f[CR]hledger setup\f[R] to list the currently active config file.+(\f[CR]setup\f[R] is not affected by config files.)+.IP "4." 3+Add \f[CR]\-\-debug\f[R] or \f[CR]\-\-debug=8\f[R] to any command to see+config/command line debug output.+.IP "5." 3+In scripts, and in examples you share with others, add \f[CR]\-n\f[R] so+that a config file can\(aqt change the result.+.IP "6." 3+When you download hledger data from elsewhere, watch out for directories+containing a \f[CR]hledger.conf\f[R] file.+.IP "7." 3+If hledger reports an error in a config file which should be fine, you+might be running an older hledger version.+(Since 1.99.6, config file errors show the hledger version; with older+versions, check which hledger executables are in your PATH.)+.IP "8." 3+A config file with errors doesn\(aqt stop help flags like+\f[CR]\-\-help\f[R] or \f[CR]\-\-version\f[R] from working, unless+they\(aqre used with a command alias defined in that file, in which case+the error is reported.+.SH Environment+These environment variables affect hledger:+.PP+\f[B]HLEDGER_FASTPATH\f[R] hledger parses simple journal entries with a+special fast\-path parser, when possible.+Setting this to \f[CR]off\f[R] disables the fast path, so that all+entries are parsed by the general parser, which could be useful to rule+out a parser bug.+Setting it to \f[CR]check\f[R] parses each entry with both parsers, and+reports an error if they disagree.+(\f[CR]\-\-debug=1\f[R] shows how much of a journal was parsed by the+fast path.)+.PP+\f[B]HLEDGER_LESS\f[R] If \f[CR]less\f[R] is your pager, this variable+specifies the \f[CR]less\f[R] options hledger should use.+(Otherwise, \f[CR]LESS\f[R] + custom options are used.)+.PP+\f[B]LEDGER_FILE\f[R] The default journal file, to be used when no+\f[CR]\-f/\-\-file\f[R] option is provided.+For example, it could be \f[CR]\(ti/finance/main.journal\f[R].+This can also be a glob pattern, eg \f[CR]./2???.journal\f[R].+(If the glob matches multiple files, only the alphanumerically first one+is used.)+If LEDGER_FILE points to a non\-existent file, an error will be raised.+If the value is the empty string, it is ignored.+.PP+If LEDGER_FILE is not set and \f[CR]\-f\f[R] is not provided, the+default journal file is \f[CR]$HOME/.hledger.journal\f[R] (or if a home+directory can\(aqt be detected, \f[CR]./.hledger.journal\f[R]).+.PP+See also Common tasks > Setting LEDGER_FILE.+.PP+\f[B]NO_COLOR\f[R] If this environment variable exists (with any value,+including empty), hledger will not use ANSI color codes in terminal+output, unless overridden by an explicit \f[CR]\-\-color=y\f[R] or+\f[CR]\-\-colour=y\f[R] option.+.PP+\f[B]LANGUAGE\f[R], \f[B]LC_ALL\f[R], \f[B]LC_MESSAGES\f[R],+\f[B]LANG\f[R] When the \f[CR]\-\-lang=auto\f[R] option is used, these+select the language of report titles and headings, following the usual+gettext rules: the effective locale is \f[CR]LC_ALL\f[R], else+\f[CR]LC_MESSAGES\f[R], else \f[CR]LANG\f[R]; if that is \f[CR]C\f[R],+\f[CR]POSIX\f[R] or unset, English is used; otherwise the languages+listed in \f[CR]LANGUAGE\f[R] (colon\-separated) are tried first, then+the effective locale.+See Languages.+.SH PART 2: COMMANDS+.PP+Here are hledger\(aqs standard commands.+You can list these by running \f[CR]hledger help commands\f[R], or as a+more compact list by running \f[CR]hledger\f[R].+If you have installed more add\-on commands, they also will be listed.+.PP+In the following command docs, each command\(aqs specific options are+shown.+Most commands also support the general options described above, though+some of them might have no effect.+(Usually if there\(aqs a sensible way for a general option to affect a+command, it will.)+You can list all of a command\(aqs options by running+\f[CR]hledger CMD \-h\f[R].+.PP+\f[B]User interface commands\f[R]+.IP \(bu 2+help (h) \- show documentation and examples+.IP \(bu 2+repl \- run multiple commands from an interactive prompt+.IP \(bu 2+run \- run multiple commands from a file or command line+.IP \(bu 2+ui \- (if installed) run a terminal UI+.IP \(bu 2+web \- (if installed) run a web UI+.PP+\f[B]Data entry commands\f[R]+.IP \(bu 2+add \- add transactions using terminal prompts+.IP \(bu 2+get \- fetch transaction and price data for import+.IP \(bu 2+import \- add new transactions from other files, eg CSV files+.PP+\f[B]Report commands\f[R]+.IP \(bu 2+accounts (acc) \- account names+.IP \(bu 2+activity \- transaction or posting counts, as a bar chart+.IP \(bu 2+aregister (areg) \- an account\(aqs transactions & running balance+.IP \(bu 2+balance (bal) \- balance changes, end balances, gains, budgets & more+.IP \(bu 2+balancesheet (bs) \- assets, liabilities and net worth+.IP \(bu 2+balancesheetequity (bse) \- assets, liabilities and equity+.IP \(bu 2+cashflow (cf) \- changes in liquid assets+.IP \(bu 2+codes \- transaction codes+.IP \(bu 2+commodities (comm) \- commodity/currency symbols+.IP \(bu 2+descriptions (desc) \- transaction descriptions+.IP \(bu 2+files \- input files used+.IP \(bu 2+holdings \- investment holdings and performance+.IP \(bu 2+incomestatement (is) \- revenues and expenses+.IP \(bu 2+notes \- the note part of transaction descriptions+.IP \(bu 2+payees \- the payee part of transaction descriptions+.IP \(bu 2+prices \- market prices+.IP \(bu 2+print \- transaction entries, or a whole exported journal+.IP \(bu 2+register (reg) \- matched postings & running total, across accounts+.IP \(bu 2+roi \- return on investments+.IP \(bu 2+stats \- journal statistics+.IP \(bu 2+tags \- tag names+.IP \(bu 2+transactions (tx) \- transactions, in compact one\-line format+.PP+\f[B]Maintenance commands\f[R]+.IP \(bu 2+setup \- check your hledger installation+.IP \(bu 2+init \- create starter journal files+.IP \(bu 2+check \- check that your journal is valid+.IP \(bu 2+diff \- compare an account\(aqs transactions in two journals+.PP+\f[B]Data generation commands\f[R]+.IP \(bu 2+close \- generate transactions to zero/restore/assert balances+.IP \(bu 2+rewrite \- generate postings by rule, like print \-\-auto+.PP+Next, these commands are described in detail.+.PP+.SH User interface commands+.SS help+.PP+Show some part of hledger\(aqs documentation.+.IP+.EX+Flags:+ \-i use info when showing the manual+ \-m use man when showing the manual+ \-p use less (or $PAGER) when showing the manual+ \-w use a web browser when showing the manual+ \-l just list the manual topics matching TOPIC+ \-\-builtins with commands: show only builtin commands+ \-\-addons with commands: show only addon commands+ \-\-aliases with commands: show only command aliases+.EE+.PP+The part shown is selected by arguments:+.IP \(bu 2+\f[CR]quickref\f[R] (or no args): a quick reference / overview+.IP \(bu 2+\f[CR]commands\f[R]: all commands, including addons and aliases (or just+one category, with \-\-builtins/\-\-addons/\-\-aliases)+.IP \(bu 2+\f[CR]usage [CMD]\f[R]: command line options help (like \-h/\-\-help)+.IP \(bu 2+\f[CR]examples [CMD]\f[R]: command line examples+.IP \(bu 2+\f[CR]manual [TOPIC]\f[R]: view a topic in the manual, or list them all+.IP \(bu 2+\f[CR]TOPIC\f[R]: (like \f[CR]manual TOPIC\f[R])+.IP \(bu 2+\f[CR]home|install|relnotes|docs|support|sponsor\f[R]: browse+hledger.org pages+.PP+TOPIC is a section heading in the hledger, hledger\-ui or hledger\-web+manual, or part of one, matched case insensitively.+Enclose it in quotes if it contains spaces.+With no TOPIC (\f[CR]hledger help manual\f[R]), all manual topics are+listed, indented to show (most of) their hierarchy.+.PP+The manual will be shown in a default viewer (info, man, pager, web+browser), or you can choose with \-i/\-m/\-p/\-w.+.PP+The manual is built in to your hledger executable, so it can be useful+when offline, or when you prefer the terminal to a web browser, or when+the appropriate hledger manual or viewers are not installed properly on+your system.+.PP+By default it chooses the best viewer found in $PATH, trying in this+order: \f[CR]info\f[R], \f[CR]man\f[R], \f[CR]$PAGER\f[R],+\f[CR]less\f[R], \f[CR]more\f[R], stdout.+(If a TOPIC is specified, \f[CR]$PAGER\f[R] and \f[CR]more\f[R] are not+tried.)+You can force the use of info, man, or a pager with the \f[CR]\-i\f[R],+\f[CR]\-m\f[R], or \f[CR]\-p\f[R] flags.+If no viewer can be found, or if running non\-interactively, it just+prints the manual to stdout.+.PP+Examples:+.IP+.EX+$ hledger help # show the quick reference+$ hledger help \-h # show the help command\(aqs options+$ hledger help commands # list all commands+$ hledger help commands \-\-aliases # list just the command aliases+$ hledger help \(aqtime periods\(aq # show the \(dqTime periods\(dq section in the manual+$ hledger help keys # show the \(dqKEYS\(dq section in the hledger\-ui manual+$ hledger help \-l # list the manual\(aqs topics+$ hledger help \-l journal # list the manual topics matching \(dqjournal\(dq+$ hledger help examples add # show examples for the add command+.EE+.SS repl+Start an interactive prompt for running hledger commands.+Input files are reloaded only when they change, so commands run faster.+.IP+.EX+Flags:+ \-\-no\-watch disable automatic reloading of changed input+ files, config aliases and addon commands+.EE+.PP+\f[CR]hledger repl\f[R] starts a read\-eval\-print loop (REPL) where you+can enter commands interactively.+As with the \f[CR]run\f[R] command, each input file (or each input+file/input options combination) is parsed just once, so commands will+run more quickly than if you ran them individually at the command line.+.PP+The input file(s) specified for the \f[CR]repl\f[R] command will be used+throughout the session; but you can override this temporarily by+specifying new \f[CR]\-f\f[R] options for a command.+.PP+Before running a command, any input files which have changed on disk are+automatically reloaded (including CSV rules files).+Also command aliases are reloaded if the config file has changed, and+addon commands are re\-detected if PATH\(aqs contents have changed.+The \f[CR]\-\-no\-watch\f[R] flag disables all of this reloading, so as+to work with a stable snapshot of the data, or to avoid file/directory+polling on a slow network drive.+.PP+Any other general flags given to \f[CR]repl\f[R] \- input, reporting, or+display flags such as \f[CR]\-I\f[R], \f[CR]\-\-strict\f[R],+\f[CR]\-\-alias\f[R], \f[CR]\-b\f[R]/\f[CR]\-e\f[R],+\f[CR]\-\-depth\f[R], \f[CR]\-\-cost\f[R], \f[CR]\-\-value\f[R],+\f[CR]\-\-color\f[R] \- are also applied to every command you run.+A command can still override them by specifying its own flags.+.PP+The command syntax is the same as with \f[CR]run\f[R]:+.IP \(bu 2+enter one hledger command at a time, without the usual+\f[CR]hledger\f[R] first word+.IP \(bu 2+empty lines and comment text from \f[CR]#\f[R] to end of line are+ignored+.IP \(bu 2+enclose arguments in quotes if they contain spaces.+.PP+Use \f[CR]help\f[R] (or \f[CR]h\f[R]) to show the quick reference, or+\f[CR]help commands\f[R] to list commands.+Addons in PATH and command aliases defined in a config file can also be+used.+Generally \f[CR]repl\f[R] should feel much like using hledger at the+command line.+But \f[CR]repl\f[R] requires full command names or official+abbreviations (it does not recognise ad hoc abbreviations).+.PP+To run a single shell command, type \f[CR]! SHELLCMD\f[R] (eg+\f[CR]! ls\f[R] or \f[CR]! git status\f[R]).+.PP+While it is running, the REPL remembers your command history, and you+can navigate in the usual ways:+.IP \(bu 2+Keypad or Emacs navigation keys to edit the current command line+.IP \(bu 2+UP/DOWN or control\-P/control\-N to step back/forward through history+.IP \(bu 2+control\-R to search for a past command+.IP \(bu 2+TAB to complete file paths.+.PP+You can type control\-C to cancel a long\-running command (but only+once; typing it a second time will exit the REPL).+.PP+In most shells you can type control\-Z to temporarily exit to the shell+(and then \f[CR]fg\f[R] to return to the REPL).+.PP+To exit the REPL, use control\-D or \f[CR]q\f[R] or \f[CR]quit\f[R] or+\f[CR]exit\f[R].+.SS Examples+Start the REPL and enter some commands:+.IP+.EX+$ hledger repl +hledger 1.52+Enter hledger commands. To exit, enter \(aqquit\(aq or \(aqexit\(aq, or send EOF / control\-d.+2025> stats+Main file : .../2025.journal+\&...+2025> stats \-f 2024/2024.journal +Main file : .../2024.journal+\&...+2025> stats+Main file : .../2025.journal+\&...+.EE+.PP+or:+.IP+.EX+$ hledger repl \-f some.journal+hledger 1.52+Enter hledger commands. To exit, enter \(aqquit\(aq or \(aqexit\(aq, or send EOF / control\-d.+some> bs+\&...+some> print \-b \(aqlast week\(aq+\&...+some> bs \-f other.journal+\&...+.EE+.SS run+Run a sequence of hledger commands, provided as files or command line+arguments.+Input files are parsed just once, so the commands run faster.+.IP+.EX+Flags:+ \-O \-\-output\-format=FMT select the output format. Supported formats:+ html.+ \-o \-\-output\-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ \-\-view write output to FILE, or to view.FMT in hledger\(aqs+ cache directory, and open it in the system\(aqs+ default viewer for its format (eg a web browser for+ html). The default format is html.+.EE+.PP+You can use \f[CR]run\f[R] in three ways:+.IP \(bu 2+\f[CR]hledger run \-\- CMD1 \-\- CMD2 \-\- CMD3\f[R] \- read commands+from the command line, separated by \f[CR]\-\-\f[R]+.IP \(bu 2+\f[CR]hledger run SCRIPTFILE1 SCRIPTFILE2\f[R] \- read commands from one+or more files+.IP \(bu 2+\f[CR]cat SCRIPTFILE1 | hledger run\f[R] \- read commands from standard+input.+.PP+\f[CR]run\f[R] first loads the input file(s) specified by+\f[CR]LEDGER_FILE\f[R] or by \f[CR]\-f\f[R] options, in the usual way.+Then it runs each command in turn, each using the same input data.+But if you want a particular command to use different input, you can+specify an \f[CR]\-f\f[R] option within that command.+This will override (not add to) the default input, just for that+command.+.PP+Any other general flags given to \f[CR]run\f[R] \- input, reporting, or+display flags such as \f[CR]\-I\f[R], \f[CR]\-\-strict\f[R],+\f[CR]\-\-alias\f[R], \f[CR]\-b\f[R]/\f[CR]\-e\f[R],+\f[CR]\-\-depth\f[R], \f[CR]\-\-cost\f[R], \f[CR]\-\-value\f[R],+\f[CR]\-\-color\f[R] \- are also applied to every command it runs.+A command can still override them by specifying its own flags.+.PP+Each input file (more precisely, each combination of input file and+input options) is parsed only once.+This means that commands will not see any changes made to these files,+until the next run.+But the commands will run more quickly than if run individually+(typically about twice as fast).+.PP+Command scripts, whether in a file or written on the command line, have+a simple syntax:+.IP \(bu 2+each line may contain a single hledger command and its arguments,+without the usual \f[CR]hledger\f[R] first word+.IP \(bu 2+empty lines are ignored+.IP \(bu 2+text from \f[CR]#\f[R] to end of line is a comment, and ignored+.IP \(bu 2+you can use single or double quotes to quote arguments when needed, as+on the command line+.IP \(bu 2+these extra commands are available: \f[CR]echo TEXT\f[R] prints some+text (interpreting the backslash escapes \f[CR]\(rsn\f[R],+\f[CR]\(rst\f[R], \f[CR]\(rsr\f[R], \f[CR]\(rs\(rs\f[R]), and+\f[CR]exit\f[R] or \f[CR]quit\f[R] ends the run.+.PP+On unix systems you can use \f[CR]#!/usr/bin/env hledger run\f[R] in the+first line of a command file to make it a runnable script.+If that gives an error, use \f[CR]#!/usr/bin/env \-S hledger run\f[R].+.PP+It\(aqs ok to use the \f[CR]run\f[R] command recursively within a+command script.+.PP+With \f[CR]\-O html\f[R], \f[CR]\-o FILE.html\f[R] or+\f[CR]\-\-view\f[R], \f[CR]run\f[R] collects the commands\(aq outputs+into one HTML page instead of printing them: a section for each command,+headed by its command line, which can be folded; and a heading for each+\f[CR]echo\f[R].+Commands which can produce HTML (the balance commands,+\f[CR]register\f[R], \f[CR]aregister\f[R], \f[CR]print\f[R],+\f[CR]holdings\f[R], \f[CR]activity\f[R]) do so, charts included;+others\(aq text output is shown as is.+\f[CR]\-\-view\f[R] then opens the page in your web browser (see Output+destination), which is a convenient way to see several reports, or+charts, at once:+.IP+.EX+$ hledger run \-\-view \-\- echo Overview \-\- is \-M \-\-chart \-\- bs \-Q \-\-chart \-\- reg expenses \-p thismonth+.EE+.PP+Command aliases defined in a config file can also be used in command+scripts.+.PP+You may find some differences in behaviour between \f[CR]run\f[R]+command lines and normal hledger command lines.+\f[CR]run\f[R] is a little stricter; eg it requires full command names+or official abbreviations (as seen in the commands list), and command+options must be written after the command name.+.SS Examples+Run commands from the command line:+.IP+.EX+hledger \-f some.journal run \-\- balance assets \-\-depth 2 \-\- balance liabilities \-f /some/other.journal \-\-depth 3 \-\-transpose \-\- stats+.EE+.PP+This would load \f[CR]some.journal\f[R], run+\f[CR]balance assets \-\-depth 2\f[R] on it, then run+\f[CR]balance liabilities \-\-depth 3 \-\-transpose\f[R] on+\f[CR]/some/other.journal\f[R], and finally run \f[CR]stats\f[R] on+\f[CR]some.journal\f[R]+.PP+Run commands from standard input:+.IP+.EX+(echo \(dqfiles\(dq; echo \(dqstats\(dq) | hledger \-f some.journal run+.EE+.PP+Run commands as a script:+.IP+.EX+$ cat report+#!/usr/bin/env \-S hledger run \-f some.journal++echo \(dqList of accounts in some.journal\(dq+accounts++echo \(dqAssets of some.journal\(dq+balance assets \-\-depth 2++echo \(dqLiabilities from /some/other.journal\(dq+balance liabilities \-f /some/other.journal \-\-depth 3 \-\-transpose++echo \(dqCommands from another.script, applied to another.journal\(dq+run \-f another.journal another.script+.EE+.IP+.EX+$ chmod +x report+$ ./report+List of accounts in some.journal+\&...+.EE+.SS ui+Runs hledger\-ui, a terminal UI (if installed).+.SS web+Runs hledger\-web, a web UI (if installed).+.SH Data entry commands+.SS add+Add new transactions to a journal file, with interactive prompting.+.IP+.EX+Flags:+ \-\-no\-new\-accounts don\(aqt allow creating new accounts+ \-\-layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 \- right\-align amounts, as in hledger 1+ COL \- align decimal marks at column COL+ (default: 53)+.EE+.PP+Many hledger users edit their journals directly with a text editor, or+generate them from CSV.+For more interactive data entry, there is the \f[CR]add\f[R] command,+which prompts interactively on the console for new transactions, and+appends them to the main journal file (which should be in journal+format).+Existing transactions are not changed.+This is one of the few hledger commands that writes to the journal file+(see also \f[CR]import\f[R]).+.PP+To use it, just run \f[CR]hledger add\f[R] and follow the prompts.+You can add as many transactions as you like; when you are finished,+enter \f[CR].\f[R] or press control\-d or control\-c to exit.+.PP+Features:+.IP \(bu 2+add tries to provide useful defaults, using the most similar (by+description) and nearest\-dated transaction (filtered by the query, if+any) as a template.+.IP \(bu 2+You can also set the initial defaults with command line arguments.+.IP \(bu 2+Readline\-style edit keys can be used during data entry.+.IP \(bu 2+The tab key will auto\-complete whenever possible \- accounts,+payees/descriptions, dates (\f[CR]yesterday\f[R], \f[CR]today\f[R],+\f[CR]tomorrow\f[R]).+If the input area is empty, it will insert the default value.+.IP \(bu 2+A parenthesised transaction code may be entered following a date.+.IP \(bu 2+Comments and tags may be entered following a description or amount.+.IP \(bu 2+If you make a mistake, enter \f[CR]<\f[R] at any prompt to go one step+backward.+.IP \(bu 2+Before saving a transaction, add checks that the journal will still be+readable with it added, as the next read with the same options will+check it (eg balance assertions must pass, lots must be valid, and with+\f[CR]\-\-strict\f[R], the strict checks must pass).+If not, it shows the error and goes one step backward, so you can+correct the entry.+(With a large journal this check may take a moment; it runs while you+are deciding whether to save.)+.IP \(bu 2+Input prompts are displayed in a different colour when the terminal+supports it.+.PP+Notes:+.IP \(bu 2+If you enter a number with no commodity symbol, and you have declared a+default commodity with a \f[CR]D\f[R] directive, you might expect+\f[CR]add\f[R] to add this symbol for you.+It does not do this; we assume that if you are using a \f[CR]D\f[R]+directive you prefer not to see the commodity symbol repeated on amounts+in the journal.+.IP \(bu 2+\f[CR]add\f[R] creates entries in journal format; it won\(aqt work with+timeclock or timedot files.+.IP \(bu 2+There is a known issue on Windows if this hledger version is built from+stackage: the prompts will show ANSI junk instead of colours (#2410).+You can avoid this by using official hledger release binaries or by+building it with haskeline >=0.8.4; or by running \f[CR]add\f[R] with+\f[CR]\-\-color=no\f[R], perhaps configured in your config file.+.PP+Examples:+.IP \(bu 2+Record new transactions, saving to the default journal file:+.RS 2+.PP+\f[CR]hledger add\f[R]+.RE+.IP \(bu 2+Add transactions to 2024.journal, but also load 2023.journal for+completions:+.RS 2+.PP+\f[CR]hledger add \-\-file 2024.journal \-\-file 2023.journal\f[R]+.RE+.IP \(bu 2+Provide answers for the first four prompts:+.RS 2+.PP+\f[CR]hledger add today \(aqbest buy\(aq expenses:supplies \(aq$20\(aq\f[R]+.RE+.PP+There is a detailed tutorial at https://hledger.org/add.html.+.SS add and balance assertions+You can add a balance assertion by writing \f[CR]AMOUNT = BALANCE\f[R]+when asked for an amount.+Eg \f[CR]100 = 500\f[R].+.PP+Also, each time you enter a new amount, hledger re\-checks all balance+assertions in the journal and rejects the new amount if it would make+any of them fail.+You can run \f[CR]add\f[R] with \f[CR]\-I\f[R] or+\f[CR]\-\-ignore\-assertions\f[R] to disable balance assertion checking.+.SS add and balance assignments+\f[B]Adding a new balance assignment\f[R]+.PD 0+.P+.PD+When entering a posting amount, you can write a+\f[CR]= BALANCEAMOUNT\f[R] balance assignment (or \f[CR]==\f[R],+\f[CR]=*\f[R], \f[CR]==*\f[R]) instead.+The posting amount required to produce this balance will be calculated+automatically.+\f[I](Since 1.51)\f[R]+.PP+\f[B]Adding a posting dated before an existing balance assignment\f[R]+.PD 0+.P+.PD+\f[CR]add\f[R] won\(aqt let you add a posting dated earlier than an+existing balance assignment in that account.+(Because it calculates balance assignments only once at startup,+converting them to assertions, so adding the new amount causes an+assertion failure.)+To work around this, run \f[CR]add\f[R] with balance assertions ignored:+\f[CR]hledger add \-I\f[R].+.SS get+Fetch new transactions and market prices for the journal, by running+\f[CR]getdata\f[R] and \f[CR]getprices\f[R] helper scripts.+New prices are merged into prices files automatically; new transaction+data is just saved, for later conversion & import by \f[CR]import\f[R].+.IP+.EX+Flags:+ \-\-transactions fetch transactions only+ \-\-prices fetch prices only+ \-\-dry\-run just print the commands that would be run+.EE+.PP+By default, this command fetches both transactions and prices.+.SS Phase 1: transactions data+.IP "1." 3+Creates a \f[CR]data/\f[R] directory next to the main journal file, if+it does not exist.+.IP "2." 3+If the \f[CR]data/getdata\f[R] helper script exists, runs it in the data+directory, so it can save downloaded files (CSV/TSV/JSON/OFX/etc.)+there.+.SS Phase 2: prices+.IP "1." 3+Creates a \f[CR]prices/\f[R] directory next to the main journal file, if+it does not exist.+.IP "2." 3+If the \f[CR]prices/getprices\f[R] helper script exists, hledger first+guesses the journal\(aqs base currency (the commodity most used as the+target in P price directives; or if there are no P directives, the+commodity most used in postings; or if there are no postings,+\(dqUSD\(dq).+Then for each other commodity in the journal, it fetches daily market+prices in the base currency, from that commodity\(aqs earliest+transaction until today, by running+\f[CR]getprices BASECUR COMM START END\f[R].+Each commodity\(aqs prices are merged into+\f[CR]prices/<COMM>.prices\f[R], preserving existing prices.+.PP+Commands being run, and files being updated, are logged to stderr.+With \f[CR]\-\-dry\-run\f[R], you can preview the commands without+running them.+.SS Merging new prices+Complete historical price data can be hard to get, so the prices phase+is careful to preserve older prices.+If prices files already exist, the newly fetched prices will be merged+as follows:+.IP \(bu 2+Prices files will be updated only if they contain nothing but P+directives (or blank lines).+.IP \(bu 2+New prices for dates already seen are discarded.+(So if you want to replace old prices, you must delete them before+running \f[CR]get\f[R].)+.IP \(bu 2+If no new prices remain to be added, the prices file is left as\-is.+.IP \(bu 2+Otherwise, the old prices plus the new prices are saved to the file,+ordered by: date, from commodity, to commodity.+Each price keeps the number format it was written with.+.SS get\(aqs helper scripts+Data downloading varies for everyone, and needs to be easily+customisable, so it is done via helper scripts:+.SS getdata+If you want \f[CR]get\f[R] to download transaction data for you, make+your own \f[CR]getdata\f[R] shell script (or executable program), and+install it in the \f[CR]data\f[R] directory next to your main journal+file.+.PP+It should download zero or more transaction data files into its current+directory.+Anything it prints (on stdout or stderr) is shown on stderr, as progress+output.+These are typically bank/brokerage CSV/TSV/SSV files, but could be+anything that your hledger rules files can read.+The hledger repo\(aqs getdata is a stub you can start from, with+commented examples.+.SS getprices+If you want \f[CR]get\f[R] to download historical market prices (useful+for currency conversions, and value or gains reports), install a+\f[CR]getprices\f[R] script in the \f[CR]prices\f[R] directory next to+your main journal file.+.PP+You can start with the hledger repo\(aqs getprices, customising it if+needed.+This script uses pricehist, so you will need to install that python tool+also (eg with \f[CR]uv tool install pricehist\f[R]).+Some price providers limit the commodity pairs, history, or number of+requests available for free; you can get better data by paying them and+setting up their API keys as environment variables.+.PP+Or, you can make your own \f[CR]getprices\f[R] script.+It should accept 3\-4 arguments:+.IP \(bu 2+ISO code for the base currency+.IP \(bu 2+ISO code for the commodity to be priced+.IP \(bu 2+ISO start date+.IP \(bu 2+optional ISO end date (default: today)+.SS import+Import new transactions from one or more data files to the main journal.+Or with no arguments, import from the rules files in \f[CR]rules/\f[R].+.IP+.EX+Flags:+ \-g \-\-get fetch new data first by running the get command+ \-\-catchup just mark all transactions as already imported+ \-\-dry\-run just show the transactions to be imported+ \-\-layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 \- right\-align amounts, as in hledger 1+ COL \- align decimal marks at column COL+ (default: 53)+.EE+.PP+This command detects new transactions in one or more data files+specified as arguments, and appends them to the main journal.+.PP+You can import from any input file format hledger supports, but+CSV/SSV/TSV files, downloaded from financial institutions, are the most+common import source.+.PP+The import destination is the default journal file, or another specified+in the usual way with \f[CR]$LEDGER_FILE\f[R] or+\f[CR]\-f/\-\-file\f[R].+It should be in journal format.+.PP+Before writing anything, \f[CR]import\f[R] checks that the journal will+still be readable with the new transactions added, as the next read with+the same options will check it (eg balance assertions must pass, lots+must be valid, and with \f[CR]\-\-strict\f[R], the strict checks must+pass).+If not, it shows the error and imports nothing (and updates no+\f[CR].latest\f[R] files).+A dry run does this check too.+.PP+Examples:+.IP+.EX+$ hledger import bank1\-checking.csv bank1\-savings.csv+.EE+.IP+.EX+$ hledger import *.csv+.EE+.SS Default import sources+If \f[CR]import\f[R] is run with no file arguments, it looks in the+journal\(aqs \f[CR]rules/\f[R] directory (next to the main journal file)+and imports from every \f[CR].rules\f[R] file found there, in+alphabetical order.+Files whose name begins with \f[CR].\f[R] or \f[CR]_\f[R] are skipped:+the \f[CR]_\f[R] prefix is for rules files that are either disabled, or+shared/common rules \f[CR]include\f[R]d by other rules files and not+meant to be read directly.+.PP+So a typical setup might be:+.IP+.EX+\(ti/finance/2026.journal+\(ti/finance/rules/bank1\-checking.rules+\(ti/finance/rules/bank1\-savings.rules+\(ti/finance/rules/_common.rules # included by others, not read directly+\(ti/finance/rules/_brokerage.rules # disabled+.EE+.PP+and \f[CR]hledger import\f[R] reads \f[CR]bank1\-checking.rules\f[R]+then \f[CR]bank1\-savings.rules\f[R].+.PP+If the \f[CR]rules/\f[R] directory does not exist or contains no usable+\f[CR].rules\f[R] files, import reports an error.+.SS Fetching new data first+With \f[CR]\-g/\-\-get\f[R], \f[CR]import\f[R] runs the \f[CR]get\f[R]+command first, which runs your \f[CR]data/getdata\f[R] and+\f[CR]prices/getprices\f[R] scripts (if any) to download new transaction+and price data.+The import then proceeds normally, with the new transaction data (if+any) readable by your rules files\(aq \f[CR]source\f[R] rules.+.SS Import dry run+It\(aqs useful to preview the import by running first with+\f[CR]\-\-dry\-run\f[R], to sanity check the range of dates being+imported, and to check the effect of your conversion rules if converting+from CSV.+Eg:+.IP+.EX+$ hledger import bank.csv \-\-dry\-run+.EE+.PP+A dry run archives no data files and updates no \f[CR].latest\f[R]+files.+With \f[CR]\-g\f[R], the \f[CR]get\f[R] command does a dry run too.+But \f[CR]source\f[R] rules\(aq data cleaning and data generating+commands do run, since their output is needed for the preview; so these+should be safe to repeat.+.PP+The dry run output is valid journal format, so hledger can re\-parse it.+If the output is large, you could show just the uncategorised+transactions like so:+.IP+.EX+$ hledger import \-\-dry\-run bank.csv | hledger \-f\- \-I print unknown+.EE+.PP+You could also run this repeatedly to see the effect of edits to your+conversion rules:+.IP+.EX+$ watchexec \-\- \(dqhledger import \-\-dry\-run bank.csv | hledger \-f\- \-I print unknown\(dq+.EE+.PP+Once the conversion and dates look good enough to import to your+journal, perhaps with some manual fixups to follow, you would do the+actual import:+.IP+.EX+$ hledger import bank.csv+.EE+.SS Overlap detection+Reading CSV files is built in to hledger, and not specific to+\f[CR]import\f[R]; so you could also import by doing+\f[CR]hledger \-f bank.csv print >>$LEDGER_FILE\f[R].+.PP+But \f[CR]import\f[R] is easier and provides some advantages.+The main one is that it avoids re\-importing transactions it has seen on+previous runs.+This means you don\(aqt have to worry about overlapping data in+successive downloads of your bank CSV; just download and+\f[CR]import\f[R] as often as you like, and only the new transactions+will be imported each time.+.PP+We don\(aqt call this \(dqdeduplication\(dq, as it\(aqs generally not+possible to reliably detect duplicates in bank CSV.+Instead, \f[CR]import\f[R] remembers the latest date processed+previously in each CSV file (saving it in a hidden file), and skips any+records prior to that date.+This works well for most real\-world CSV, where:+.IP "1." 3+the data file name is stable (does not change) across imports+.IP "2." 3+the item dates are stable across imports+.IP "3." 3+the order of same\-date items is stable across imports+.IP "4." 3+the newest items have the newest dates+.PP+(Occasional violations of 2\-4 are often harmless; you can reduce the+chance of disruption by downloading and importing more often.)+.PP+Overlap detection is automatic, and shouldn\(aqt require much attention+from you, except perhaps at first import (see below).+But here\(aqs how it works:+.IP \(bu 2+For each \f[CR]FILE\f[R] being imported from:+.RS 2+.IP "1." 3+hledger reads a file named \f[CR].latest.FILE\f[R] file in the same+directory, if any.+This file contains the latest record date previously imported from FILE,+in YYYY\-MM\-DD format.+If multiple records with that date were imported, the date is repeated+on N lines.+.IP "2." 3+hledger reads records from FILE.+If a latest date was found in step 1, any records before that date, and+the first N records on that date, are skipped.+.RE+.IP \(bu 2+After a successful import from all FILEs, without error and without+\f[CR]\-\-dry\-run\f[R], hledger updates each FILE\(aqs+\f[CR].latest.FILE\f[R] for next time.+.PP+If this goes wrong, it\(aqs relatively easy to repair:+.IP \(bu 2+You\(aqll notice it before import when you preview with+\f[CR]import \-\-dry\-run\f[R].+.IP \(bu 2+Or after import when you try to reconcile your hledger account balances+with your bank.+.IP \(bu 2+\f[CR]hledger print \-f FILE.csv\f[R] will show all recently downloaded+transactions.+Compare these with your journal.+Copy/paste if needed.+.IP \(bu 2+Update your conversion rules and print again, if needed.+.IP \(bu 2+You can manually update or remove the .latest file, or use+\f[CR]import \-\-catchup FILE\f[R].+.IP \(bu 2+Download and import more often, eg twice a week, at least while you are+learning.+It\(aqs easier to review and troubleshoot when there are fewer+transactions.+.SS First import+The first time you import from a file, when no corresponding .latest+file has been created yet, all of the records will be imported.+.PP+But perhaps you have been entering the data manually, so you know that+all of these transactions are already recorded in the journal.+In this case you can run \f[CR]hledger import \-\-catchup\f[R] once.+This will create a .latest file containing the latest CSV record date,+so that none of those records will be re\-imported.+.PP+Or, if you know that some but not all of the transactions are in the+journal, you can create the .latest file yourself.+Eg, let\(aqs say you previously recorded foobank transactions up to+2024\-10\-31 in the journal.+Then in the directory where you\(aqll be saving \f[CR]foobank.csv\f[R],+you would create a \f[CR].latest.foobank.csv\f[R] file containing+.IP+.EX+2024\-10\-31+.EE+.PP+Or if you had three foobank transactions recorded with that date, you+would repeat the date that many times:+.IP+.EX+2024\-10\-31+2024\-10\-31+2024\-10\-31+.EE+.PP+Then \f[CR]hledger import foobank.csv [\-\-dry\-run]\f[R] will import+only the newer records.+.SS Importing balance assignments+Journal entries added by import will have all posting amounts made+explicit (like \f[CR]print \-x\f[R]).+.PP+This means that any balance assignments in the imported entries would+need to be evaluated.+But this generally isn\(aqt possible, as the main file\(aqs account+balances are not visible during import.+So try to avoid generating balance assignments with your CSV rules, or+importing from a journal that contains balance assignments.+(Balance assignments are best avoided anyway.)+.PP+But if you must use them, eg because your CSV includes only balances:+you can import with \f[CR]print\f[R], which leaves implicit amounts+implicit.+(\f[CR]print\f[R] can also do overlap detection like import, with the+\f[CR]\-\-new\f[R] flag):+.IP+.EX+$ hledger print \-\-new \-f bank.csv >> $LEDGER_FILE+.EE+.PP+(If you think \f[CR]import\f[R] should preserve implicit balances,+please test that and send a pull request.)+.SS Import and commodity styles+Amounts in entries added by import will be formatted according to the+journal\(aqs canonical commodity styles, as declared by+\f[CR]commodity\f[R] directives or inferred from the journal\(aqs+amounts.+.PP+Related: CSV > Amount decimal places.+.SS Import archiving+When importing from a CSV rules file+(\f[CR]hledger import bank.rules\f[R]), you can use the archive rule to+enable automatic archiving of the data file.+.PP+After a successful import, the data file specified by \f[CR]source\f[R]+will be moved (or data generated by a command will be saved) to an+archive directory.+This can be useful for troubleshooting, detecting variations in your+banks\(aq CSV data, regenerating entries with improved rules, etc.+.PP+The archive directory is \f[CR]data/archive/\f[R], next to the main+journal file, auto\-created.+The archive file name will be similar to the rules file, with a date+added: the original data file\(aqs modification date, or today\(aqs date+if the data was command\-generated.+.PP+The \f[CR]archive\f[R] rule also causes \f[CR]import\f[R] to handle+\f[CR]source\f[R] glob patterns differently: when there are multiple+matched files, it will pick the oldest, not the newest.+.SS Import special cases+.SS Multiple journals in the same directory+You might want to keep each journal you are importing to in its own+directory.+That way, each will have its own \f[CR]rules/\f[R], \f[CR]data/\f[R],+and \f[CR]data/archive/\f[R] directories (if those are used).+.PP+Otherwise, imports to the same\-directory journals will potentially use+the same \f[CR]rules/\f[R], \f[CR]data/\f[R] and+\f[CR]data/archive/\f[R] directories (depending on commands and rules+configuration).+This is not necessarily a problem; it might even be desirable in some+cases.+But see below:+.SS Import configurations to avoid+A few unusual workflows which you should generally avoid:+.IP \(bu 2+Don\(aqt import from one input file to different journals.+The imports\(aq overlap detection would overwrite the same+\f[CR].latest.FILE\f[R] state file.+(In effect, the journals would compete for the new records.)+.IP \(bu 2+Don\(aqt import from multiple data files on the same day, reusing the+same rules file for all, with \f[CR]archive\f[R] enabled.+The archived file names in \f[CR]data/archive/\f[R] would clash, causing+some archives to be overwritten.+.IP \(bu 2+Don\(aqt do argument\-less \f[CR]hledger import\f[R] to more than one+journal in the same directory.+That would read from the same files in \f[CR]rules/\f[R], potentially+disrupting both overlap detection and archiving.+.SS Deduplication+Here are two kinds of \(dqdeduplication\(dq which \f[CR]import\f[R] does+not handle (and should not, because these can happen legitimately in+financial data):+.IP \(bu 2+Two or more of the new CSV records are identical, and generate identical+new journal entries.+.IP \(bu 2+A new CSV record generates a journal entry identical to one(s) already+in the journal.+.SS Varying file name+If you have a download whose file name varies, you could rename it to a+fixed name after each download.+Or you could use a CSV \f[CR]source\f[R] rule with a suitable glob+pattern, and import from the .rules file.+.SS Multiple versions+Say you download \f[CR]bank.csv\f[R], import it, but forget to delete it+from your downloads folder.+The next time you download it, your web browser will save it as (eg)+\f[CR]bank (2).csv\f[R].+The source rule\(aqs glob patterns are for just this situation: instead+of specifying \f[CR]source bank.csv\f[R], specify+\f[CR]source bank*.csv\f[R].+Then \f[CR]hledger \-f bank.rules CMD\f[R] or+\f[CR]hledger import bank.rules\f[R] will automatically pick the newest+matched file (\f[CR]bank (2).csv\f[R]).+.PP+Alternately, what if you download, but forget to import or delete, then+download again ?+Now each of \f[CR]bank.csv\f[R] and \f[CR]bank (2).csv\f[R] might+contain data that\(aqs not in the other, and not in your journal.+In this case, it\(aqs best to import each of them in turn, oldest first+(otherwise, overlap detection could cause new records to be skipped).+Enabling import archiving ensures this.+Then \f[CR]hledger import bank.rules; hledger import bank.rules\f[R]+will import and archive first \f[CR]bank.csv\f[R], then+\f[CR]bank (2).csv\f[R].+.PP+.PP+.PP+.PP+.SH Report commands+.SS accounts+(acc)+.PP+List the account names used or declared in the journal.+.IP+.EX+Flags:+ \-u \-\-used list accounts used+ \-d \-\-declared list accounts declared+ \-\-undeclared list accounts used but not declared+ \-\-unused list accounts declared but not used+ \-\-find list the first account matched by the first+ argument (a case\-insensitive infix regexp)+ \-\-directives show as account directives, for use in journals+ \-\-locations also show where accounts were declared, or first+ used+ \-\-types also show account types when known+ \-\-show\-aliases also show account aliases declared with alias:+ tags+ \-l \-\-flat list/tree mode: show accounts as a flat list+ (default)+ \-t \-\-tree list/tree mode: show accounts as a tree+ \-\-drop=N flat mode: omit N leading account name parts+.EE+.PP+This command lists account names \- all of them by default, or just the+ones which have been used in transactions (\f[CR]\-u/\-\-used\f[R]), or+declared with \f[CR]account\f[R] directives+(\f[CR]\-d/\-\-declared\f[R]), or used but not declared+(\f[CR]\-\-undeclared\f[R]), or declared but not used+(\f[CR]\-\-unused\f[R]), or just the first one matched by a pattern+(\f[CR]\-\-find\f[R], returning a non\-zero exit code if it fails).+.PP+You can add query arguments to select a subset of transactions or+accounts.+Note that transaction\-specific query terms like \f[CR]date:\f[R] will+exclude declared\-but\-unused accounts, which don\(aqt have that field.+.PP+With \f[CR]\-\-directives\f[R], it shows valid account directives which+could be pasted into a journal file, including any account aliases as+\f[CR]alias:\f[R] tags.+This is useful together with \f[CR]\-\-undeclared\f[R] when updating+your account declarations to satisfy \f[CR]hledger check accounts\f[R].+.PP+With \f[CR]\-\-locations\f[R], it also shows the file and line number of+each account\(aqs declaration, if any, and the account\(aqs overall+declaration order; these may be useful when troubleshooting account+display order.+For an undeclared account, it shows where the account was first used+(posted to), if anywhere.+.PP+With \f[CR]\-\-types\f[R], it also shows each account\(aqs type, if+it\(aqs known.+(See Declaring accounts > Account types.)+.PP+With \f[CR]\-\-show\-aliases\f[R], it also shows each account\(aqs+aliases, declared with \f[CR]alias:\f[R] tags.+(Aliases from \f[CR]alias\f[R] directives or \f[CR]\-\-alias\f[R]+options are not shown.)+Also, account names in the query will match aliases too, so eg+\f[CR]hledger accounts \-\-show\-aliases chk\f[R] shows the account(s)+with an alias containing \f[CR]chk\f[R].+.PP+It shows a flat list by default.+With \f[CR]\-\-tree\f[R], it uses indentation to show the account+hierarchy.+In flat mode you can add \f[CR]\-\-drop N\f[R] to omit the first few+account name components.+Account names can be depth\-clipped with \f[CR]depth:N\f[R] or+\f[CR]\-\-depth N\f[R] or \f[CR]\-N\f[R].+.PP+Examples:+.IP+.EX+$ hledger accounts+assets:bank:checking+assets:bank:saving+assets:cash+expenses:food+expenses:supplies+income:gifts+income:salary+liabilities:debts+.EE+.IP+.EX+$ hledger accounts \-\-undeclared \-\-directives >> $LEDGER_FILE+$ hledger check accounts+.EE+.SS activity+Show a bar chart of transaction counts per week, or other report+interval.+.IP+.EX+Flags:+ \-O \-\-output\-format=FMT select the output format. Supported formats:+ txt, svg, html, csv, tsv, json.+ \-o \-\-output\-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ \-\-view write output to FILE, or to view.FMT in hledger\(aqs+ cache directory, and open it in the system\(aqs+ default viewer for its format (eg a web browser for+ html). The default format is html.+ \-w \-\-width=N with \-\-chart: draw the chart N characters wide+ (default: the terminal width)+ \-\-txns count transactions, showing just the total+ (default)+ \-\-postings count postings, showing each account\(aqs count+ \-S \-\-sort\-amount with \-\-postings, sort accounts by posting count,+ largest first+ \-T \-\-total show the total count, below the chart+ \-A \-\-average show the average count per period, below the+ chart (and as a line in SVG charts)+.EE+.PP+The activity command shows how many transactions there are in each week+(or with a report interval, each day, month, quarter etc.), as a bar+chart.+Each transaction is one character, unless there are too many to fit,+when the bars are scaled down.+With query arguments, it counts only the transactions which have at+least one matched posting.+.PP+Or with \f[CR]\-\-postings\f[R], it shows how many postings there are in+each period, with each account\(aqs postings stacked in its own colour.+With query arguments, it counts only the matched postings.+This is a shortcut for \f[CR]balance \-\-count \-\-chart\f[R], with a+weekly interval by default, so it can show charts in all the same ways:+eg with \f[CR]\-1\f[R] or other depth limit to show less detail,+\f[CR]\-0\f[R] to show just the total count, without the accounts\(aq+detail, \f[CR]\-S\f[R]/\f[CR]\-\-sort\-amount\f[R] to show the accounts+with most postings first.+(Transaction counts show just the total, since a transaction\(aqs+postings can be in several accounts.)+.PP+\f[CR]\-\-txns\f[R] selects transaction counts explicitly; if both+\f[CR]\-\-txns\f[R] and \f[CR]\-\-postings\f[R] are given, the last one+wins.+.PP+Both kinds of chart can be shown in the usual ways, eg with+\f[CR]\-w\f[R]/\f[CR]\-\-width\f[R] to set the width,+\f[CR]\-T\f[R]/\f[CR]\-\-total\f[R] and+\f[CR]\-A\f[R]/\f[CR]\-\-average\f[R] to show the total count and the+average count per period below the chart (in graphical charts, the+average is also drawn as a dashed line), or \f[CR]\-o FILE.svg\f[R] (or+\f[CR]\-O svg\f[R]) for a graphical chart.+.PP+Examples:+.IP+.EX+$ hledger activity \-M \-T \-A \-w 40+Transaction counts in 2008:++Jan 1 █+Feb 0+Mar 0+Apr 0+May 0+Jun 3 ███+Jul 0+Aug 0+Sep 0+Oct 0+Nov 0+Dec 1 █++Total 5, Average 0.4+.EE+.IP+.EX+$ hledger activity \-M \-\-postings \-1 \-w 40+Posting counts in 2008:++▓ assets █ expenses ░ income+▒ liabilities++Jan 2 ▓░+Feb 0+Mar 0+Apr 0+May 0+Jun 7 ▓▓▓▓██░+Jul 0+Aug 0+Sep 0+Oct 0+Nov 0+Dec 2 ▓▒+.EE+.SS aregister+(areg)+.PP+Show the transactions and running balances in one account, with one+entry per transaction.+.IP+.EX+Flags:+ \-\-txn\-dates filter strictly by transaction date, not posting+ date. Warning: this can show a wrong running+ balance.+ \-\-no\-elide don\(aqt show only 2 commodities per amount+ \-\-cumulative accumulation mode: show running total from report+ start date+ \-H \-\-historical accumulation mode: show historical running+ total/balance (includes postings before report+ start date) (default)+ \-A \-\-average show running average of transaction amounts+ instead of balance (implies \-\-empty and, unless \-H+ is used, \-\-cumulative)+ \-r \-\-related show the other accounts in each transaction+ (default)+ \-\-matched show the matched accounts (this account or its+ subaccounts) instead+ \-\-invert display all amounts with reversed sign+ \-\-drop=N omit N leading account name parts+ \-\-heading=YN show heading row above table: yes (default) or no+ \-w \-\-width=N set output width (default: terminal width). \-wN,M+ sets description width as well.+ \-\-align\-all guarantee alignment across all lines (slower)+ \-O \-\-output\-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ \-o \-\-output\-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ \-\-view write output to FILE, or to view.FMT in hledger\(aqs+ cache directory, and open it in the system\(aqs+ default viewer for its format (eg a web browser for+ html). The default format is html.+ \-\-chart[=net,SCALE] show a chart: instead of the table (txt), above+ it (html), or as data (csv, tsv, json). net: also+ draw the net total (a line, or marks in text+ charts). SCALE: the amount that fills the chart (eg+ 1000 or 1000 USD; one per commodity), for+ comparable charts.+.EE+.PP+\f[CR]aregister\f[R] shows the overall transactions affecting a+particular account (and any subaccounts).+Each report line represents one transaction in this account.+Transactions before the report start date are included in the running+balance (\f[CR]\-\-historical\f[R] mode is the default).+You can suppress this behaviour using the \f[CR]\-\-cumulative\f[R]+option.+.PP+This is a more \(dqreal world\(dq, bank\-like view than the+\f[CR]register\f[R] command (which shows individual postings, possibly+from multiple accounts, not necessarily in historical mode).+As a quick rule of thumb:+.IP \(bu 2+\f[CR]aregister\f[R] is best when reconciling real\-world+asset/liability accounts+.IP \(bu 2+\f[CR]register\f[R] is best when reviewing individual revenues/expenses.+.PP+Note this command\(aqs non\-standard, and required, first argument; it+specifies the account whose register will be shown.+You can write the account\(aqs name, or (to save typing) a+case\-insensitive infix regular expression matching the name, which+selects the alphabetically first matched account.+(For example, if you have \f[CR]assets:personal checking\f[R] and+\f[CR]assets:business checking\f[R], \f[CR]hledger areg checking\f[R]+would select \f[CR]assets:business checking\f[R].)+.PP+Transactions involving subaccounts of this account will also be shown.+\f[CR]aregister\f[R] ignores depth limits, so its final total will+always match a historical balance report with similar arguments.+.PP+Any additional arguments are standard query arguments, which will limit+the transactions shown.+Note some queries will disturb the running balance, causing it to be+different from the account\(aqs real\-world running balance.+.PP+An example: this shows the transactions and historical running balance+during july, in the first account whose name contains \(dqchecking\(dq:+.IP+.EX+$ hledger areg checking date:jul+.EE+.PP+Each \f[CR]aregister\f[R] line item shows:+.IP \(bu 2+the transaction\(aqs date (or the relevant posting\(aqs date if+different, see below)+.IP \(bu 2+the names of all the other account(s) involved in this transaction+(probably abbreviated)+.IP \(bu 2+the total change to this account\(aqs balance from this transaction+.IP \(bu 2+the account\(aqs historical running balance after this transaction.+.PP+The account column normally shows the other accounts in each transaction+(this is also selectable with \f[CR]\-r/\-\-related\f[R]).+With \f[CR]\-\-matched\f[R], it shows the matched accounts instead: this+account, or the subaccounts of it that were posted to.+This is useful when the account has subaccounts, eg:+.IP+.EX+$ hledger areg expenses \-\-matched+.EE+.PP+shows which expense categories each transaction touched.+Any additional query arguments also narrow the matched accounts shown.+The amounts and running balance are the same in both modes.+.PP+Transactions making a net change of zero are not shown by default; add+the \f[CR]\-E/\-\-empty\f[R] flag to show them.+.PP+The \f[CR]\-A/\-\-average\f[R] flag shows the running average change per+transaction, instead of the running balance, so the last number shown is+the average for the whole report period.+It implies \f[CR]\-\-empty\f[R], since zero\-change transactions also+affect the average.+Unlike aregister\(aqs other reports, it is not historical by default;+add \f[CR]\-H\f[R] to include the transactions before the report start+date in the average.+Like \f[CR]register \-A\f[R], it works best with a single commodity.+.PP+For performance reasons, column widths are chosen based on the first+1000 lines; this means unusually wide values in later lines can cause+visual discontinuities as column widths are adjusted.+If you want to ensure perfect alignment, at the cost of more time and+memory, use the \f[CR]\-\-align\-all\f[R] flag.+.PP+By default, \f[CR]aregister\f[R] shows a heading above the data.+However, when reporting in a language different from English, it is+easier to omit this heading and prepend your own one.+For this purpose, use the \f[CR]\-\-heading=no\f[R] option.+.PP+This command also supports the output destination and output format+options.+The output formats supported are \f[CR]txt\f[R], \f[CR]csv\f[R],+\f[CR]tsv\f[R], \f[CR]html\f[R], \f[CR]fods\f[R] and \f[CR]json\f[R].+.PP+With \f[CR]\-\-chart\f[R], or with \f[CR]svg\f[R] output+(\f[CR]\-o FILE.svg\f[R]), it shows a chart of the account\(aqs balance+(or running total or average) over time instead.+A text chart has a row per transaction (for a row per period instead,+use a balance report with a report interval and \f[CR]\-H\f[R]).+An SVG chart draws the balance as a line on a time scale.+With \f[CR]\-\-chart \-O csv\f[R] (or tsv or json) it shows the+chart\(aqs data.+See also Balance charts.+.SS aregister and posting dates+aregister always shows one entry (and one date and amount) per+transaction.+(With a single commodity, this means line = one transaction.+But multi\-commodity amounts will be shown with one line per commodity.)+But sometimes transactions have postings with different dates.+Also, not all of a transaction\(aqs postings may be within the report+period.+To resolve this, aregister shows the earliest of the transaction\(aqs+date and posting dates that is in\-period, and the sum of the in\-period+postings.+In other words it will show a combined line item with just the earliest+date, and the running balance will (temporarily, until the+transaction\(aqs last posting) be inaccurate.+Use \f[CR]register \-H\f[R] if you need to see the individual postings.+.PP+There is also a \f[CR]\-\-txn\-dates\f[R] flag, which filters strictly+by transaction date, ignoring posting dates.+This too can cause an inaccurate running balance.+.SS balance+(bal)+.PP+Show accounts with some kind of summed numeric data: balance changes per+period, end balances on period end dates, simple capital gains, budget+goal performance, etc.+.IP+.EX+Flags:+ \-\-sum calculation mode: show sum of posting amounts+ (default)+ \-\-valuechange calculation mode: show total change of value+ of period\-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ \-\-gain calculation mode: show capital gain/loss+ (historical balance value minus cost basis, or+ transacted cost where there is none)+ \-\-budget[=DESCPAT] calculation mode: show sum of posting amounts+ together with budget goals defined by periodic+ transactions. With a DESCPAT argument (must be+ separated by = not space),+ use only periodic transactions with matching+ description+ (case insensitive substring match).+ \-\-count calculation mode: show the count of postings+ \-\-change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports, default)+ \-\-cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. \-b/\-\-begin) to+ column end+ \-H \-\-historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date)+ \-l \-\-flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth\-clipped.+ \-t \-\-tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ \-\-drop=N in list mode, omit N leading account name+ parts+ \-\-declared include non\-parent declared accounts (best+ used with \-E)+ \-A \-\-average show a row average column (in multicolumn+ reports)+ \-T \-\-row\-total show a row total column (in multicolumn+ reports)+ \-\-summary\-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ \-N \-\-no\-total omit the final total row+ \-\-no\-elide in tree mode, don\(aqt squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without \-E)+ \-\-full\-names in tree mode, show full account names instead+ of indented leaf names+ \-\-format=FORMATSTR use this custom line format (in simple+ reports)+ \-S \-\-sort\-amount sort by amount instead of account code/name+ (in flat mode). With multiple columns, sorts by+ the row total, or by row average if that is+ displayed.+ \-% \-\-percent express values in percentage of each column\(aqs+ total+ \-r \-\-related show the other accounts transacted with,+ instead+ \-\-invert display all amounts with reversed sign+ \-\-transpose switch rows and columns (use vertical time+ axis); repeat to cancel+ \-\-layout=ARG how to lay out multi\-commodity amounts and the+ overall table:+ \(aqwide[,W]\(aq: commodities on same line, up to W+ wide+ \(aqtall\(aq : commodities on separate lines+ \(aqbare\(aq : commodity symbols in a separate+ column+ \(aqtidy\(aq : each data field in its own column+ \-\-base\-url=URLPREFIX in html output, generate links to hledger\-web,+ with this prefix. (Usually the base url shown by+ hledger\-web; can also be relative.)+ \-O \-\-output\-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, fods, svg.+ \-o \-\-output\-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ \-\-view write output to FILE, or to view.FMT in+ hledger\(aqs cache directory, and open it in the+ system\(aqs default viewer for its format (eg a web+ browser for html). The default format is html.+ \-\-chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: grouped (a bar per account type, side by+ side). net: also draw the net total (a line, or+ marks in text charts). SCALE: the amount that+ fills the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ \-w \-\-width=N with \-\-chart: draw the chart N characters wide+ (default: the terminal width)+.EE+.PP+\f[CR]balance\f[R] is one of hledger\(aqs oldest and most versatile+commands, for listing account balances, balance changes, values, value+changes and more, during one time period or many.+Generally it shows a table, with rows representing accounts, and columns+representing periods.+.PP+Note there are some variants of the \f[CR]balance\f[R] command with+convenient defaults, which are simpler to use: \f[CR]balancesheet\f[R],+\f[CR]balancesheetequity\f[R], \f[CR]cashflow\f[R] and+\f[CR]incomestatement\f[R].+When you need more control, then use \f[CR]balance\f[R].+.SS balance features+Here\(aqs a quick overview of the \f[CR]balance\f[R] command\(aqs+features, followed by more detailed descriptions and examples.+Many of these work with the other balance\-like commands as well+(\f[CR]bs\f[R], \f[CR]cf\f[R], \f[CR]is\f[R]..).+.PP+\f[CR]balance\f[R] can show..+.IP \(bu 2+accounts as a list (\f[CR]\-l\f[R]) or a tree (\f[CR]\-t\f[R])+.IP \(bu 2+optionally depth\-limited (\f[CR]\-[1\-9]\f[R])+.IP \(bu 2+sorted by declaration order and name, or by amount+.PP+\&..and their..+.IP \(bu 2+balance changes (the default)+.IP \(bu 2+or actual and planned balance changes (\f[CR]\-\-budget\f[R])+.IP \(bu 2+or value of balance changes (\f[CR]\-V\f[R])+.IP \(bu 2+or change of balance values (\f[CR]\-\-valuechange\f[R])+.IP \(bu 2+or capital gain/loss (\f[CR]\-\-gain\f[R])+.IP \(bu 2+or balance changes from sibling postings+(\f[CR]\-\-related\f[R]/\f[CR]\-r\f[R])+.IP \(bu 2+or postings count (\f[CR]\-\-count\f[R])+.PP+\&..in..+.IP \(bu 2+one time period (the whole journal period by default)+.IP \(bu 2+or multiple periods (\f[CR]\-D\f[R], \f[CR]\-W\f[R], \f[CR]\-M\f[R],+\f[CR]\-Q\f[R], \f[CR]\-Y\f[R], \f[CR]\-p INTERVAL\f[R])+.PP+\&..either..+.IP \(bu 2+per period (the default)+.IP \(bu 2+or accumulated since report start date (\f[CR]\-\-cumulative\f[R])+.IP \(bu 2+or accumulated since account creation (\f[CR]\-\-historical/\-H\f[R])+.PP+\&..possibly converted to..+.IP \(bu 2+cost+(\f[CR]\-\-value=cost[,COMM]\f[R]/\f[CR]\-\-cost\f[R]/\f[CR]\-B\f[R])+.IP \(bu 2+or market value, as of transaction dates+(\f[CR]\-\-value=then[,COMM]\f[R])+.IP \(bu 2+or at period ends (\f[CR]\-\-value=end[,COMM]\f[R])+.IP \(bu 2+or now (\f[CR]\-\-value=now\f[R])+.IP \(bu 2+or at some other date (\f[CR]\-\-value=YYYY\-MM\-DD\f[R])+.PP+\&..with..+.IP \(bu 2+totals (\f[CR]\-T\f[R]), averages (\f[CR]\-A\f[R]), percentages+(\f[CR]\-%\f[R]), inverted sign (\f[CR]\-\-invert\f[R])+.IP \(bu 2+rows and columns swapped (\f[CR]\-\-transpose\f[R])+.IP \(bu 2+another field used as account name (\f[CR]\-\-pivot\f[R])+.IP \(bu 2+custom\-formatted line items (single\-period reports only)+(\f[CR]\-\-format\f[R])+.IP \(bu 2+commodities displayed on the same line or multiple lines+(\f[CR]\-\-layout\f[R])+.IP \(bu 2+a chart instead of a table (\f[CR]\-\-chart\f[R])+.PP+This command supports the output destination and output format options,+with output formats \f[CR]txt\f[R], \f[CR]csv\f[R], \f[CR]tsv\f[R],+\f[CR]json\f[R], \f[CR]html\f[R], \f[CR]fods\f[R], and \f[CR]svg\f[R].+In \f[CR]txt\f[R] output in a colour\-supporting terminal, negative+amounts are shown in red.+.SS Simple balance report+With no arguments, \f[CR]balance\f[R] shows a list of all accounts and+their change of balance \- ie, the sum of posting amounts, both inflows+and outflows \- during the entire period of the journal.+(\(dqSimple\(dq here means just one column of numbers, covering a single+period.+You can also have multi\-period reports, described later.)+.PP+For real\-world accounts, these numbers will normally be their end+balance at the end of the journal period; more on this below.+.PP+Accounts are sorted by declaration order if any, and then alphabetically+by account name.+For instance (using examples/sample.journal):+.IP+.EX+$ hledger \-f examples/sample.journal bal+ $1 assets:bank:saving+ $\-2 assets:cash+ $1 expenses:food+ $1 expenses:supplies+ $\-1 income:gifts+ $\-1 income:salary+ $1 liabilities:debts+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ 0 +.EE+.PP+Accounts with a zero balance (and no non\-zero subaccounts, in tree mode+\- see below) are hidden by default.+Use \f[CR]\-E/\-\-empty\f[R] to show them (revealing+\f[CR]assets:bank:checking\f[R] here):+.IP+.EX+$ hledger \-f examples/sample.journal bal \-E+ 0 assets:bank:checking+ $1 assets:bank:saving+ $\-2 assets:cash+ $1 expenses:food+ $1 expenses:supplies+ $\-1 income:gifts+ $\-1 income:salary+ $1 liabilities:debts+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ 0 +.EE+.PP+The total of the amounts displayed is shown as the last line, unless+\f[CR]\-N\f[R]/\f[CR]\-\-no\-total\f[R] is used.+.SS Balance report line format+For single\-period balance reports displayed in the terminal (only), you+can use \f[CR]\-\-format FMT\f[R] to customise the format and content of+each line.+Eg:+.IP+.EX+$ hledger \-f examples/sample.journal balance \-\-format \(dq%20(account) %12(total)\(dq+ assets $\-1+ bank:saving $1+ cash $\-2+ expenses $2+ food $1+ supplies $1+ income $\-2+ gifts $\-1+ salary $\-1+ liabilities:debts $1+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ 0+.EE+.PP+The FMT format string specifies the formatting applied to each+account/balance pair.+It may contain any suitable text, with data fields interpolated like so:+.PP+\f[CR]%[MIN][.MAX](FIELDNAME)\f[R]+.IP \(bu 2+MIN pads with spaces to at least this width (optional)+.IP \(bu 2+MAX truncates at this width (optional)+.IP \(bu 2+FIELDNAME must be enclosed in parentheses, and can be one of:+.RS 2+.IP \(bu 2+\f[CR]depth_spacer\f[R] \- a number of spaces equal to the account\(aqs+depth, or if MIN is specified, MIN * depth spaces.+.IP \(bu 2+\f[CR]account\f[R] \- the account\(aqs name+.IP \(bu 2+\f[CR]total\f[R] \- the account\(aqs balance/posted total, right+justified+.RE+.PP+Also, FMT can begin with an optional prefix to control how+multi\-commodity amounts are rendered:+.IP \(bu 2+\f[CR]%_\f[R] \- render on multiple lines, bottom\-aligned (the default)+.IP \(bu 2+\f[CR]%\(ha\f[R] \- render on multiple lines, top\-aligned+.IP \(bu 2+\f[CR]%,\f[R] \- render on one line, comma\-separated+.PP+There are some quirks.+Eg in one\-line mode, \f[CR]%(depth_spacer)\f[R] has no effect, instead+\f[CR]%(account)\f[R] has indentation built in.+Experimentation may be needed to get pleasing results.+.PP+Some example formats:+.IP \(bu 2+\f[CR]%(total)\f[R] \- the account\(aqs total+.IP \(bu 2+\f[CR]%\-20.20(account)\f[R] \- the account\(aqs name, left justified,+padded to 20 characters and clipped at 20 characters+.IP \(bu 2+\f[CR]%,%\-50(account) %25(total)\f[R] \- account name padded to 50+characters, total padded to 20 characters, with multiple commodities+rendered on one line+.IP \(bu 2+\f[CR]%20(total) %2(depth_spacer)%\-(account)\f[R] \- the default+format for the single\-column balance report.+The total field keeps this 20\-character width as a minimum, but widens+automatically when displayed amounts need more room.+.SS Filtered balance report+You can show fewer accounts, a different time period, totals from+cleared transactions only, etc.+by using query arguments or options to limit the postings being matched.+Eg:+.IP+.EX+$ hledger \-f examples/sample.journal bal \-\-cleared assets date:200806+ $\-2 assets:cash+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ $\-2 +.EE+.SS List or tree mode+By default, or with \f[CR]\-l/\-\-flat\f[R], accounts are shown as a+flat list with their full names visible, as in the examples above.+.PP+With \f[CR]\-t/\-\-tree\f[R], the account hierarchy is shown, with+subaccounts\(aq \(dqleaf\(dq names indented below their parent:+.IP+.EX+$ hledger \-f examples/sample.journal balance+ $\-1 assets+ $1 bank:saving+ $\-2 cash+ $2 expenses+ $1 food+ $1 supplies+ $\-2 income+ $\-1 gifts+ $\-1 salary+ $1 liabilities:debts+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ 0+.EE+.PP+Notes:+.IP \(bu 2+\(dqBoring\(dq accounts are combined with their subaccount for more+compact output, unless \f[CR]\-\-no\-elide\f[R] is used.+Boring accounts have no balance of their own and just one subaccount (eg+\f[CR]assets:bank\f[R] and \f[CR]liabilities\f[R] above).+.IP \(bu 2+All balances shown are \(dqinclusive\(dq, ie including the balances from+all subaccounts.+Note this means some repetition in the output, which requires+explanation when sharing reports with non\-plaintextaccounting\-users.+A tree mode report\(aqs final total is the sum of the top\-level+balances shown, not of all the balances shown.+.IP \(bu 2+Each group of sibling accounts (ie, under a common parent) is sorted+separately.+.PP+In list mode, \f[CR]\-\-no\-elide\f[R] shows parent accounts as well,+with their exclusive balances.+These are zero unless the parent has postings of its own, so+\f[CR]\-E/\-\-empty\f[R] is usually also needed to make them visible.+Together, these flags guarantee a complete table of all posted\-to+accounts and their parents, with full names:+.IP+.EX+$ hledger \-f examples/sample.journal balance \-\-no\-elide \-E+ 0 assets+ 0 assets:bank+ 0 assets:bank:checking+ $1 assets:bank:saving+ $\-2 assets:cash+ 0 expenses+ $1 expenses:food+ $1 expenses:supplies+ 0 income+ $\-1 income:gifts+ $\-1 income:salary+ 0 liabilities+ $1 liabilities:debts+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ 0+.EE+.PP+This can be useful eg when exporting to a spreadsheet which will look up+balances by account name.+.PP+In tree mode, \f[CR]\-\-full\-names\f[R] writes each account\(aqs full+name instead of indenting leaf names, while keeping tree mode\(aqs+inclusive balances.+So \f[CR]\-\-tree \-\-no\-elide \-\-full\-names \-E\f[R] shows the same+complete table as above, but with inclusive balances:+.IP+.EX+$ hledger \-f examples/sample.journal balance \-\-tree \-\-no\-elide \-\-full\-names \-E+ $\-1 assets+ $1 assets:bank+ 0 assets:bank:checking+ $1 assets:bank:saving+ $\-2 assets:cash+ $2 expenses+ $1 expenses:food+ $1 expenses:supplies+ $\-2 income+ $\-1 income:gifts+ $\-1 income:salary+ $1 liabilities+ $1 liabilities:debts+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ 0+.EE+.PP+Note that in this variant, parent and subaccount balances overlap, so+(as in any tree mode report) the rows sum to more than the final total.+.SS Depth limiting+With a \f[CR]depth:NUM\f[R] query, or \f[CR]\-\-depth NUM\f[R] option,+or just \f[CR]\-NUM\f[R] (eg: \f[CR]\-3\f[R]) balance reports will show+accounts only to the specified depth, hiding the deeper subaccounts.+This can be useful for getting an overview without too much detail.+.PP+Account balances at the depth limit always include the balances from any+deeper subaccounts (even in list mode).+Eg, limiting to depth 1:+.IP+.EX+$ hledger \-f examples/sample.journal balance \-1+ $\-1 assets+ $2 expenses+ $\-2 income+ $1 liabilities+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ 0 +.EE+.SS Dropping top\-level accounts+You can also hide one or more top\-level account name parts, using+\f[CR]\-\-drop NUM\f[R].+This can be useful for hiding repetitive top\-level account names:+.IP+.EX+$ hledger \-f examples/sample.journal bal expenses \-\-drop 1+ $1 food+ $1 supplies+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ $2 +.EE+.PP+.SS Showing declared accounts+With \f[CR]\-\-declared\f[R], accounts which have been declared with an+account directive will be included in the balance report, even if they+have no transactions.+(Since they will have a zero balance, you will also need+\f[CR]\-E/\-\-empty\f[R] to see them.)+.PP+More precisely, \f[I]leaf\f[R] declared accounts (with no subaccounts)+will be included, since those are usually the more useful in reports.+.PP+The idea of this is to be able to see a useful \(dqcomplete\(dq balance+report, even when you don\(aqt have transactions in all of your declared+accounts yet.+.SS Sorting by amount+With \f[CR]\-S/\-\-sort\-amount\f[R], accounts with the largest (most+positive) balances are shown first.+Eg: \f[CR]hledger bal expenses \-MAS\f[R] shows your biggest averaged+monthly expenses first.+When more than one commodity is present, they will be sorted by the+alphabetically earliest commodity first, and then by subsequent+commodities (if an amount is missing a commodity, it is treated as 0).+.PP+Revenues and liability balances are typically negative, however, so+\f[CR]\-S\f[R] shows these in reverse order.+To work around this, you can add \f[CR]\-\-invert\f[R] to flip the+signs.+Or you could use one of the higher\-level balance reports+(\f[CR]bs\f[R], \f[CR]is\f[R]..), which flip the sign automatically (eg:+\f[CR]hledger is \-MAS\f[R]).+.PP+.SS Percentages+With \f[CR]\-%/\-\-percent\f[R], balance reports show each account\(aqs+value expressed as a percentage of the (column) total.+.PP+Note it is not useful to calculate percentages if the amounts in a+column have mixed signs.+In this case, make a separate report for each sign, eg:+.IP+.EX+$ hledger bal \-% amt:\(ga>0\(ga+$ hledger bal \-% amt:\(ga<0\(ga+.EE+.PP+Similarly, if the amounts in a column have mixed commodities, convert+them to one commodity with \f[CR]\-B\f[R], \f[CR]\-V\f[R],+\f[CR]\-X\f[R] or \f[CR]\-\-value\f[R], or make a separate report for+each commodity:+.IP+.EX+$ hledger bal \-% cur:\(rs\(rs$+$ hledger bal \-% cur:€+.EE+.SS Multi\-period balance report+With a report interval (set by the \f[CR]\-D/\-\-daily\f[R],+\f[CR]\-W/\-\-weekly\f[R], \f[CR]\-M/\-\-monthly\f[R],+\f[CR]\-Q/\-\-quarterly\f[R], \f[CR]\-Y/\-\-yearly\f[R], or+\f[CR]\-p/\-\-period\f[R] flag), \f[CR]balance\f[R] shows a tabular+report, with columns representing successive time periods (and a title):+.IP+.EX+$ hledger \-f examples/sample.journal bal \-\-quarterly income expenses \-E+Balance changes in 2008:++ || 2008q1 2008q2 2008q3 2008q4 +===================++=================================+ expenses:food || 0 $1 0 0 + expenses:supplies || 0 $1 0 0 + income:gifts || 0 $\-1 0 0 + income:salary || $\-1 0 0 0 +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ || $\-1 $1 0 0 +.EE+.PP+Notes:+.IP \(bu 2+The report\(aqs start/end dates will be expanded, if necessary, to fully+encompass the displayed subperiods (so that the first and last+subperiods have the same duration as the others).+.IP \(bu 2+Leading and trailing periods (columns) containing all zeroes are not+shown, unless \f[CR]\-E/\-\-empty\f[R] is used.+.IP \(bu 2+Accounts (rows) containing all zeroes are not shown, unless+\f[CR]\-E/\-\-empty\f[R] is used.+.IP \(bu 2+Amounts with many commodities are shown in abbreviated form, unless+\f[CR]\-\-no\-elide\f[R] is used.+.IP \(bu 2+Average and/or total columns can be added with the+\f[CR]\-A/\-\-average\f[R] and \f[CR]\-T/\-\-row\-total\f[R] flags.+.IP \(bu 2+The \f[CR]\-\-transpose\f[R] flag can be used to exchange rows and+columns.+Repeating it reverses its effect (an even number of+\f[CR]\-\-transpose\f[R] flags has no effect).+.IP \(bu 2+The \f[CR]\-\-pivot FIELD\f[R] option causes a different transaction+field to be used as \(dqaccount name\(dq.+See PIVOTING.+.IP \(bu 2+The \f[CR]\-\-summary\-only\f[R] flag (\f[CR]\-\-summary\f[R] also+works) hides all but the Total and Average columns (those should be+enabled with \f[CR]\-\-row\-total\f[R] and \f[CR]\-A/\-\-average\f[R]).+.PP+Multi\-period reports with many periods can be too wide for easy viewing+in the terminal.+Here are some ways to handle that:+.IP \(bu 2+Hide the totals row with \f[CR]\-N/\-\-no\-total\f[R]+.IP \(bu 2+Filter to a single currency with \f[CR]cur:\f[R]+.IP \(bu 2+Convert to a single currency with+\f[CR]\-V [\-\-infer\-market\-price]\f[R]+.IP \(bu 2+Use a more compact layout like \f[CR]\-\-layout=bare\f[R]+.IP \(bu 2+Maximize the terminal window+.IP \(bu 2+Reduce the terminal\(aqs font size+.IP \(bu 2+View with a pager like less, eg:+\f[CR]hledger bal \-D \-\-color=yes | less \-RS\f[R]+.IP \(bu 2+Output as CSV and use a CSV viewer like visidata+(\f[CR]hledger bal \-D \-O csv | vd \-f csv\f[R]), Emacs\(aq csv\-mode+(\f[CR]M\-x csv\-mode, C\-c C\-a\f[R]), or a spreadsheet+(\f[CR]hledger bal \-D \-o a.csv && open a.csv\f[R])+.IP \(bu 2+Output as HTML and view with a browser:+\f[CR]hledger bal \-D \-o a.html && open a.html\f[R]+.SS Balance change, end balance+It\(aqs important to be clear on the meaning of the numbers shown in+balance reports.+Here is some terminology we use:+.PP+A \f[B]\f[BI]balance change\f[B]\f[R] is the net amount added to, or+removed from, an account during some period.+.PP+An \f[B]\f[BI]end balance\f[B]\f[R] is the amount accumulated in an+account as of some date (and some time, but hledger doesn\(aqt store+that; assume end of day in your timezone).+It is the sum of previous balance changes.+.PP+We call it a \f[B]\f[BI]historical end balance\f[B]\f[R] if it includes+all balance changes since the account was created.+For a real world account, this means it will match the \(dqhistorical+record\(dq, eg the balances reported in your bank statements or bank web+UI.+(If they are correct!)+.PP+In general, balance changes are what you want to see when reviewing+revenues and expenses, and historical end balances are what you want to+see when reviewing or reconciling asset, liability and equity accounts.+.PP+\f[CR]balance\f[R] shows balance changes by default.+To see accurate historical end balances:+.IP "1." 3+Initialise account starting balances with an \(dqopening balances\(dq+transaction (a transfer from equity to the account), unless the journal+covers the account\(aqs full lifetime.+.IP "2." 3+Include all of of the account\(aqs prior postings in the report, by not+specifying a report start date, or by using the+\f[CR]\-H/\-\-historical\f[R] flag.+(\f[CR]\-H\f[R] causes report start date to be ignored when summing+postings.)+.SS Balance report modes+The balance command is quite flexible; here is the full detail on how to+control what it reports.+If the following seems complicated, don\(aqt worry \- this is for+advanced reporting, and it does take time and experimentation to get+familiar with all the report modes.+.PP+There are three important option groups:+.PP+\f[CR]hledger balance [CALCULATIONMODE] [ACCUMULATIONMODE] [VALUATIONMODE] ...\f[R]+.SS Calculation mode+The basic calculation to perform for each table cell.+It is one of:+.IP \(bu 2+\f[CR]\-\-sum\f[R] : sum the posting amounts (\f[B]default\f[R])+.IP \(bu 2+\f[CR]\-\-budget\f[R] : sum the amounts, but also show the budget goal+amount (for each account/period)+.IP \(bu 2+\f[CR]\-\-valuechange\f[R] : show the change in period\-end historical+balance values (caused by deposits, withdrawals, and/or market price+fluctuations)+.IP \(bu 2+\f[CR]\-\-gain\f[R] : show capital gain/loss for each account: the+current valued balance minus its cost.+For lot\-tracked commodities the cost is the cost basis of the units+still held, so this is the unrealised gain.+For other commodities it is the net of postings\(aq transacted costs+(acquisition costs minus disposal proceeds): where nothing has been sold+this too is the unrealised gain, but once disposals exist the figure+also includes the realised gain on the disposed units, so it is best+read as \(dqtotal gain since inception\(dq (to separate realised and+unrealised gains, track lots).+Compare \f[CR]\-\-valuechange\f[R], which shows how much the value moved+in a period, from price changes and from buying and selling.+See Unrealised gains for examples.+.IP \(bu 2+\f[CR]\-\-count\f[R] : show the count of postings+.SS Accumulation mode+How amounts should accumulate across a report\(aqs subperiods/columns.+Another way to say it: which time period\(aqs postings should contribute+to each cell\(aqs calculation.+It is one of:+.IP \(bu 2+\f[CR]\-\-change\f[R] : calculate with postings from column start to+column end, ie \(dqjust this column\(dq.+Typically used to see revenues/expenses.+(\f[B]default for balance, cashflow, incomestatement\f[R])+.IP \(bu 2+\f[CR]\-\-cumulative\f[R] : calculate with postings from report start to+column end, ie \(dqprevious columns plus this column\(dq.+Typically used to show changes accumulated since the report\(aqs start+date.+Not often used.+.IP \(bu 2+\f[CR]\-\-historical/\-H\f[R] : calculate with postings from journal+start to column end, ie \(dqall postings from before report start date+until this column\(aqs end\(dq.+Typically used to see historical end balances of+assets/liabilities/equity.+(\f[B]default for balancesheet, balancesheetequity\f[R])+.SS Valuation mode+Which kind of value or cost conversion should be applied, if any, before+displaying the report.+See Cost reporting and Value reporting for more about conversions.+.PP+A valuation (or cost) mode can be selected with the \-\-value option:+.IP \(bu 2+no conversion : don\(aqt convert to cost or value (\f[B]default\f[R])+.IP \(bu 2+\f[CR]\-\-value=cost[,COMM]\f[R] : convert amounts to cost (then+optionally to some other commodity)+.IP \(bu 2+\f[CR]\-\-value=then[,COMM]\f[R] : convert amounts to market value on+transaction dates+.IP \(bu 2+\f[CR]\-\-value=end[,COMM]\f[R] : convert amounts to market value on+period end date(s)+.PD 0+.P+.PD+(\f[B]default with \f[CB]\-\-valuechange\f[B], \f[CB]\-\-gain\f[B]\f[R])+.IP \(bu 2+\f[CR]\-\-value=now[,COMM]\f[R] : convert amounts to market value on+today\(aqs date+.IP \(bu 2+\f[CR]\-\-value=YYYY\-MM\-DD[,COMM]\f[R] : convert amounts to market+value on another date+.PP+or with the legacy \-B/\-V/\-X options, which are equivalent and easier+to type:+.IP \(bu 2+\f[CR]\-B\f[R]/\f[CR]\-\-cost\f[R] : like \-\-value=cost+.IP \(bu 2+\f[CR]\-V\f[R]/\f[CR]\-\-market\f[R] : like \-\-value=end+.IP \(bu 2+\f[CR]\-X COMM\f[R]/\f[CR]\-\-exchange COMM\f[R] : like+\-\-value=end,COMM+.PP+Note that \-\-value can also convert to cost, as a convenience; but+actually \-\-cost and \-\-value are independent options, and could be+used together.+.SS Combining balance report modes+Most combinations of these modes produce reasonable reports.+The following restrictions are applied:+.IP \(bu 2+\f[CR]\-\-valuechange\f[R] implies \f[CR]\-\-value=end\f[R]+.IP \(bu 2+\f[CR]\-\-valuechange\f[R] makes \f[CR]\-\-change\f[R] the default when+used with the \f[CR]balancesheet\f[R]/\f[CR]balancesheetequity\f[R]+commands+.IP \(bu 2+\f[CR]\-\-cumulative\f[R] or \f[CR]\-\-historical\f[R] disables+\f[CR]\-\-row\-total/\-T\f[R]+.PP+For reference, here is what the combinations of accumulation and+valuation show:+.PP+.TS+tab(@);+lw(7.9n) lw(16.4n) lw(16.9n) lw(15.1n) lw(13.7n).+T{+Valuation:> Accumulation:v+T}@T{+no valuation+T}@T{+\f[CR]\-\-value= then\f[R]+T}@T{+\f[CR]\-\-value= end\f[R]+T}@T{+\f[CR]\-\-value= YYYY\-MM\-DD /now\f[R]+T}+_+T{+\f[CR]\-\-change\f[R]+T}@T{+change in period+T}@T{+sum of posting\-date market values in period+T}@T{+period\-end value of change in period+T}@T{+DATE\-value of change in period+T}+T{+\f[CR]\-\-cumulative\f[R]+T}@T{+change from report start to period end+T}@T{+sum of posting\-date market values from report start to period end+T}@T{+period\-end value of change from report start to period end+T}@T{+DATE\-value of change from report start to period end+T}+T{+\f[CR]\-\-historical /\-H\f[R]+T}@T{+change from journal start to period end (historical end balance)+T}@T{+sum of posting\-date market values from journal start to period end+T}@T{+period\-end value of change from journal start to period end+T}@T{+DATE\-value of change from journal start to period end+T}+.TE+.SS Budget report+The \f[CR]balance \-\-budget\f[R] report is like a regular balance+report, but with two main differences:+.IP \(bu 2+Budget goals and performance percentages are also shown, in brackets+.IP \(bu 2+Accounts which don\(aqt have budget goals are hidden by default.+.PP+This is useful for comparing planned and actual income, expenses, time+usage, etc.+.PP+Periodic transaction rules are used to define budget goals.+For example, here\(aqs a periodic rule defining monthly goals for bus+travel and food expenses:+.IP+.EX+;; Budget+\(ti monthly+ (expenses:bus) $30+ (expenses:food) $400+.EE+.PP+After recording some actual expenses,+.IP+.EX+;; Two months worth of expenses+2017\-11\-01+ income $\-1950+ expenses:bus $35+ expenses:food:groceries $310+ expenses:food:dining $42+ expenses:movies $38+ assets:bank:checking++2017\-12\-01+ income $\-2100+ expenses:bus $53+ expenses:food:groceries $380+ expenses:food:dining $32+ expenses:gifts $100+ assets:bank:checking+.EE+.PP+we can see a budget report like this:+.IP+.EX+$ hledger bal \-M \-\-budget+Budget performance in 2017\-11\-01..2017\-12\-31:++ || Nov Dec +===============++============================================+ <unbudgeted> || $\-425 $\-565 + expenses || $425 [ 99% of $430] $565 [131% of $430] + expenses:bus || $35 [117% of $30] $53 [177% of $30] + expenses:food || $352 [ 88% of $400] $412 [103% of $400] +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ || 0 [ 0% of $430] 0 [ 0% of $430] +.EE+.PP+This is \(dqgoal\-based budgeting\(dq; you define goals for accounts and+periods, often recurring, and hledger shows performance relative to the+goals.+This contrasts with \(dqenvelope budgeting\(dq, which is more detailed+and strict \- useful when cash is tight, but also quite a bit more work.+https://plaintextaccounting.org/Budgeting has more on this topic.+.SS Using the budget report+Historically this report has been confusing and fragile.+hledger\(aqs version should be relatively robust and intuitive, but you+may still find surprises.+Here are more notes to help with learning and troubleshooting.+.IP \(bu 2+In the above example, \f[CR]expenses:bus\f[R] and+\f[CR]expenses:food\f[R] are shown because they have budget goals during+the report period.+.IP \(bu 2+Their parent \f[CR]expenses\f[R] is also shown, with budget goals+aggregated from the children.+.IP \(bu 2+The subaccounts \f[CR]expenses:food:groceries\f[R] and+\f[CR]expenses:food:dining\f[R] are not shown since they have no budget+goal of their own, but they contribute to \f[CR]expenses:food\f[R]\(aqs+actual amount.+.IP \(bu 2+Unbudgeted accounts \f[CR]expenses:movies\f[R] and+\f[CR]expenses:gifts\f[R] are also not shown, but they contribute to+\f[CR]expenses\f[R]\(aqs actual amount.+.IP \(bu 2+The other unbudgeted accounts \f[CR]income\f[R] and+\f[CR]assets:bank:checking\f[R] are grouped as \f[CR]<unbudgeted>\f[R].+.IP \(bu 2+\f[CR]\-\-depth\f[R] or \f[CR]depth:\f[R] can be used to limit report+depth in the usual way (but will not reveal unbudgeted subaccounts).+.IP \(bu 2+Amounts are always inclusive of subaccounts (even in+\f[CR]\-l/\-\-list\f[R] mode).+.IP \(bu 2+Numbers displayed in a \-\-budget report will not always agree with the+totals, because of hidden unbudgeted accounts; this is normal.+\f[CR]\-E/\-\-empty\f[R] can be used to reveal the hidden accounts.+.IP \(bu 2+In the periodic rules used for setting budget goals, unbalanced postings+are convenient.+.IP \(bu 2+You can filter budget reports with the usual queries, eg to focus on+particular accounts.+It\(aqs common to restrict them to just expenses.+(The \f[CR]<unbudgeted>\f[R] account is occasionally hard to exclude;+this is because of date surprises, discussed below.)+.IP \(bu 2+Only the account, account type, depth, date and commodity parts of the+query are applied to the budget goals; the other parts+(\f[CR]status:\f[R]/\f[CR]\-U\f[R]/\f[CR]\-P\f[R]/\f[CR]\-C\f[R],+\f[CR]code:\f[R], \f[CR]desc:\f[R], \f[CR]payee:\f[R], \f[CR]note:\f[R],+\f[CR]tag:\f[R], \f[CR]real:\f[R], \f[CR]amt:\f[R]) select actual+transactions and postings only.+So eg \f[CR]\-\-budget \-\-cleared\f[R] compares your cleared spending+against the full budget goals.+.IP \(bu 2+When you have multiple currencies, you may want to convert them to one+(\f[CR]\-X COMM \-\-infer\-market\-prices\f[R]) and/or show just one at+a time (\f[CR]cur:COMM\f[R]).+If you do need to show multiple currencies at once,+\f[CR]\-\-layout bare\f[R] can be helpful.+.IP \(bu 2+You can \(dqroll over\(dq amounts (actual and budgeted) to the next+period with \f[CR]\-\-cumulative\f[R].+.PP+See also: https://hledger.org/budgeting.html.+.SS Budget date surprises+With small data, or when starting out, some of the generated budget goal+transaction dates might fall outside the report periods.+Eg with the following journal and report, the first period appears to+have no \f[CR]expenses:food\f[R] budget.+(Also the \f[CR]<unbudgeted>\f[R] account should be excluded by the+\f[CR]expenses\f[R] query, but isn\(aqt.):+.IP+.EX+\(ti monthly in 2020+ (expenses:food) $500++2020\-01\-15+ expenses:food $400+ assets:checking+.EE+.IP+.EX+$ hledger bal \-\-budget expenses+Budget performance in 2020\-01\-15:++ || 2020\-01\-15 +===============++====================+ <unbudgeted> || $400 + expenses:food || 0 [ 0% of $500] +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ || $400 [80% of $500] +.EE+.PP+In this case, the budget goal transactions are generated on first days+of of month (this can be seen with+\f[CR]hledger print \-\-forecast tag:generated expenses\f[R]).+Whereas the report period defaults to just the 15th day of january (this+can be seen from the report table\(aqs column headings).+.PP+To fix this kind of thing, be more explicit about the report period+(and/or the periodic rules\(aq dates).+In this case, adding \f[CR]\-b 2020\f[R] does the trick.+.SS Selecting budget goals+By default, the budget report uses all available periodic transaction+rules to generate goals.+This includes rules with a different report interval from your report.+Eg if you have daily, weekly and monthly periodic rules, all of these+will contribute to the goals in a monthly budget report.+.PP+You can select a subset of periodic rules by providing an argument to+the \f[CR]\-\-budget\f[R] flag.+\f[CR]\-\-budget=DESCPAT\f[R] will match all periodic rules whose+description contains DESCPAT, a case\-insensitive substring (not a+regular expression or query).+This means you can give your periodic rules descriptions (remember that+two spaces are needed between period expression and description), and+then select from multiple budgets defined in your journal.+.SS Budgeting vs forecasting+\f[CR]\-\-forecast\f[R] and \f[CR]\-\-budget\f[R] both use the periodic+transaction rules in the journal to generate temporary transactions for+reporting purposes.+However they are separate features \- though you can use both at the+same time if you want.+Here are some differences between them:+.PP+.TS+tab(@);+lw(38.2n) lw(31.8n).+T{+\-\-forecast+T}@T{+\-\-budget+T}+_+T{+is a general option; it enables forecasting with all reports+T}@T{+is a balance command option; it selects the balance report\(aqs budget+mode+T}+T{+generates visible transactions which appear in reports+T}@T{+generates invisible transactions which produce goal amounts+T}+T{+generates forecast transactions from after the last regular transaction,+to the end of the report period; or with an argument+\f[CR]\-\-forecast=PERIODEXPR\f[R] generates them throughout the+specified period, both optionally restricted by periods specified in the+periodic transaction rules+T}@T{+generates budget goal transactions throughout the report period,+optionally restricted by periods specified in the periodic transaction+rules+T}+T{+uses all periodic rules+T}@T{+uses all periodic rules; or with an argument+\f[CR]\-\-budget=DESCPAT\f[R] uses just the rules matched by DESCPAT+T}+.TE+.SS Balance report layout+The \f[CR]\-\-layout\f[R] option affects how \f[CR]balance\f[R] and the+other balance\-like commands show multi\-commodity amounts and commodity+symbols.+It can improve readability, for humans and/or machines (other software).+It has four possible values:+.IP \(bu 2+\f[CR]\-\-layout=wide[,WIDTH]\f[R]: commodities are shown on a single+line, optionally elided to WIDTH+.IP \(bu 2+\f[CR]\-\-layout=tall\f[R]: each commodity is shown on a separate line+.IP \(bu 2+\f[CR]\-\-layout=bare\f[R]: commodity symbols are in their own column,+amounts are bare numbers+.IP \(bu 2+\f[CR]\-\-layout=barewide\f[R]: commodities are shown on a single line,+all in separate columns, amounts are bare numbers+.IP \(bu 2+\f[CR]\-\-layout=tidy\f[R]: data is normalised to easily\-consumed+\(dqtidy\(dq form, with one row per data value.+(This one is currently supported only by the \f[CR]balance\f[R]+command.)+.PP+Here are the \f[CR]\-\-layout\f[R] modes supported by each output format+Only CSV output supports all of them:+.PP+.TS+tab(@);+l l l l l l.+T{+\-+T}@T{+txt+T}@T{+csv+T}@T{+html+T}@T{+json+T}@T{+sql+T}+_+T{+wide+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+T}@T{+T}+T{+tall+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+T}@T{+T}+T{+bare+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+T}@T{+T}+T{+barewide+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+T}@T{+T}+T{+tidy+T}@T{+T}@T{+Y+T}@T{+T}@T{+T}@T{+T}+.TE+.PP+Choice of layouts for budget reports is more restricted:+.PP+.TS+tab(@);+l l l l l l.+T{+\-+T}@T{+txt+T}@T{+csv+T}@T{+html+T}@T{+json+T}@T{+sql+T}+_+T{+wide+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+T}@T{+T}+T{+tall+T}@T{+Y+T}@T{+T}@T{+T}@T{+T}@T{+T}+T{+bare+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+T}@T{+T}+T{+barewide+T}@T{+T}@T{+Y+T}@T{+Y+T}@T{+T}@T{+T}+T{+tidy+T}@T{+T}@T{+T}@T{+T}@T{+T}@T{+T}+.TE+.PP+Examples:+.SS Wide layout+With many commodities, reports can be very wide:+.IP+.EX+$ hledger \-f examples/bcexample.journal bal assets:us:etrade \-3 \-T \-Y \-\-layout=wide+Balance changes in 2012\-01\-01..2014\-12\-31:++ || 2012 2013 2014 Total +==================++====================================================================================================================================================================================================================+ Assets:US:ETrade || 10.00 ITOT, 337.18 USD, 12.00 VEA, 106.00 VHT 70.00 GLD, 18.00 ITOT, \-98.12 USD, 10.00 VEA, 18.00 VHT \-11.00 ITOT, 4881.44 USD, 14.00 VEA, 170.00 VHT 70.00 GLD, 17.00 ITOT, 5120.50 USD, 36.00 VEA, 294.00 VHT +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ || 10.00 ITOT, 337.18 USD, 12.00 VEA, 106.00 VHT 70.00 GLD, 18.00 ITOT, \-98.12 USD, 10.00 VEA, 18.00 VHT \-11.00 ITOT, 4881.44 USD, 14.00 VEA, 170.00 VHT 70.00 GLD, 17.00 ITOT, 5120.50 USD, 36.00 VEA, 294.00 VHT +.EE+.PP+A width limit reduces the width, but some commodities will be hidden:+.IP+.EX+$ hledger \-f examples/bcexample.journal bal assets:us:etrade \-3 \-T \-Y \-\-layout=wide,32+Balance changes in 2012\-01\-01..2014\-12\-31:++ || 2012 2013 2014 Total +==================++===========================================================================================================================+ Assets:US:ETrade || 10.00 ITOT, 337.18 USD, 2 more.. 70.00 GLD, 18.00 ITOT, 3 more.. \-11.00 ITOT, 3 more.. 70.00 GLD, 17.00 ITOT, 3 more.. +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ || 10.00 ITOT, 337.18 USD, 2 more.. 70.00 GLD, 18.00 ITOT, 3 more.. \-11.00 ITOT, 3 more.. 70.00 GLD, 17.00 ITOT, 3 more.. +.EE+.SS Tall layout+Each commodity gets a new line (may be different in each column), and+account names are repeated:+.IP+.EX+$ hledger \-f examples/bcexample.journal bal assets:us:etrade \-3 \-T \-Y \-\-layout=tall+Balance changes in 2012\-01\-01..2014\-12\-31:++ || 2012 2013 2014 Total +==================++==================================================+ Assets:US:ETrade || 10.00 ITOT 70.00 GLD \-11.00 ITOT 70.00 GLD + Assets:US:ETrade || 337.18 USD 18.00 ITOT 4881.44 USD 17.00 ITOT + Assets:US:ETrade || 12.00 VEA \-98.12 USD 14.00 VEA 5120.50 USD + Assets:US:ETrade || 106.00 VHT 10.00 VEA 170.00 VHT 36.00 VEA + Assets:US:ETrade || 18.00 VHT 294.00 VHT +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ || 10.00 ITOT 70.00 GLD \-11.00 ITOT 70.00 GLD + || 337.18 USD 18.00 ITOT 4881.44 USD 17.00 ITOT + || 12.00 VEA \-98.12 USD 14.00 VEA 5120.50 USD + || 106.00 VHT 10.00 VEA 170.00 VHT 36.00 VEA + || 18.00 VHT 294.00 VHT +.EE+.SS Bare layout+Commodity symbols are kept in one column, each commodity has its own+row, amounts are bare numbers, account names are repeated:+.IP+.EX+$ hledger \-f examples/bcexample.journal bal assets:us:etrade \-3 \-T \-Y \-\-layout=bare+Balance changes in 2012\-01\-01..2014\-12\-31:++ || Commodity 2012 2013 2014 Total +==================++=============================================+ Assets:US:ETrade || GLD 0 70.00 0 70.00 + Assets:US:ETrade || ITOT 10.00 18.00 \-11.00 17.00 + Assets:US:ETrade || USD 337.18 \-98.12 4881.44 5120.50 + Assets:US:ETrade || VEA 12.00 10.00 14.00 36.00 + Assets:US:ETrade || VHT 106.00 18.00 170.00 294.00 +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ || GLD 0 70.00 0 70.00 + || ITOT 10.00 18.00 \-11.00 17.00 + || USD 337.18 \-98.12 4881.44 5120.50 + || VEA 12.00 10.00 14.00 36.00 + || VHT 106.00 18.00 170.00 294.00 +.EE+.PP+Bare layout also affects CSV output, which is useful for producing data+that is easier to consume, eg for making charts:+.IP+.EX+$ hledger \-f examples/bcexample.journal bal assets:us:etrade \-3 \-O csv \-\-layout=bare+\(dqaccount\(dq,\(dqcommodity\(dq,\(dqbalance\(dq+\(dqAssets:US:ETrade\(dq,\(dqGLD\(dq,\(dq70.00\(dq+\(dqAssets:US:ETrade\(dq,\(dqITOT\(dq,\(dq17.00\(dq+\(dqAssets:US:ETrade\(dq,\(dqUSD\(dq,\(dq5120.50\(dq+\(dqAssets:US:ETrade\(dq,\(dqVEA\(dq,\(dq36.00\(dq+\(dqAssets:US:ETrade\(dq,\(dqVHT\(dq,\(dq294.00\(dq+\(dqTotal:\(dq,\(dqGLD\(dq,\(dq70.00\(dq+\(dqTotal:\(dq,\(dqITOT\(dq,\(dq17.00\(dq+\(dqTotal:\(dq,\(dqUSD\(dq,\(dq5120.50\(dq+\(dqTotal:\(dq,\(dqVEA\(dq,\(dq36.00\(dq+\(dqTotal:\(dq,\(dqVHT\(dq,\(dq294.00\(dq+.EE+.PP+Bare layout will sometimes display an extra row for the no\-symbol+commodity, because of zero amounts (hledger treats zeroes as+commodity\-less, usually).+This can break \f[CR]hledger\-bar\f[R] confusingly (workaround: add a+\f[CR]cur:\f[R] query to exclude the no\-symbol row).+.SS Barewide layout+Commodity symbols are spread in the table headers, each commodity has+its own column, all column groups share the same set of commodities even+if in one commodity column all values are zero.+For consistency you may think of layout \f[CR]bare\f[R] as+\f[CR]baretall\f[R].+.IP+.EX+$ hledger \-f examples/bcexample.journal bal assets:us:etrade \-3 \-T \-Y \-\-layout=barewide+Balance changes in 2012\-01\-01..2014\-12\-31:++ || 2012 (GLD) 2012 (ITOT) 2012 (USD) 2012 (VEA) 2012 (VHT) 2013 (GLD) 2013 (ITOT) 2013 (USD) 2013 (VEA) 2013 (VHT) 2014 (GLD) 2014 (ITOT) 2014 (USD) 2014 (VEA) 2014 (VHT) Total (GLD) Total (ITOT) Total (USD) Total (VEA) Total (VHT) +==================++===================================================================================================================================================================================================================================================================+ Assets:US:ETrade || 0 10.00 337.18 12.00 106.00 70.00 18.00 \-98.12 10.00 18.00 0 \-11.00 4881.44 14.00 170.00 70.00 17.00 5120.50 36.00 294.00 +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ || 0 10.00 337.18 12.00 106.00 70.00 18.00 \-98.12 10.00 18.00 0 \-11.00 4881.44 14.00 170.00 70.00 17.00 5120.50 36.00 294.00 +.EE+.PP+Barewide layout is very useful for FODS and CSV output, since you can+easily use LibreOffice\(aqs \f[CR]VLOOKUP\f[R] function for accessing+numbers in a table with mixed commodities.+.SS Tidy layout+This produces normalised \(dqtidy data\(dq (see+https://cran.r\-project.org/web/packages/tidyr/vignettes/tidy\-data.html)+where every variable has its own column and each row represents a single+data point.+This is the easiest kind of data for other software to consume:+.IP+.EX+$ hledger \-f examples/bcexample.journal bal assets:us:etrade \-3 \-Y \-O csv \-\-layout=tidy+\(dqaccount\(dq,\(dqperiod\(dq,\(dqstart_date\(dq,\(dqend_date\(dq,\(dqcommodity\(dq,\(dqvalue\(dq+\(dqAssets:US:ETrade\(dq,\(dq2012\(dq,\(dq2012\-01\-01\(dq,\(dq2012\-12\-31\(dq,\(dqGLD\(dq,\(dq0\(dq+\(dqAssets:US:ETrade\(dq,\(dq2012\(dq,\(dq2012\-01\-01\(dq,\(dq2012\-12\-31\(dq,\(dqITOT\(dq,\(dq10.00\(dq+\(dqAssets:US:ETrade\(dq,\(dq2012\(dq,\(dq2012\-01\-01\(dq,\(dq2012\-12\-31\(dq,\(dqUSD\(dq,\(dq337.18\(dq+\(dqAssets:US:ETrade\(dq,\(dq2012\(dq,\(dq2012\-01\-01\(dq,\(dq2012\-12\-31\(dq,\(dqVEA\(dq,\(dq12.00\(dq+\(dqAssets:US:ETrade\(dq,\(dq2012\(dq,\(dq2012\-01\-01\(dq,\(dq2012\-12\-31\(dq,\(dqVHT\(dq,\(dq106.00\(dq+\(dqAssets:US:ETrade\(dq,\(dq2013\(dq,\(dq2013\-01\-01\(dq,\(dq2013\-12\-31\(dq,\(dqGLD\(dq,\(dq70.00\(dq+\(dqAssets:US:ETrade\(dq,\(dq2013\(dq,\(dq2013\-01\-01\(dq,\(dq2013\-12\-31\(dq,\(dqITOT\(dq,\(dq18.00\(dq+\(dqAssets:US:ETrade\(dq,\(dq2013\(dq,\(dq2013\-01\-01\(dq,\(dq2013\-12\-31\(dq,\(dqUSD\(dq,\(dq\-98.12\(dq+\(dqAssets:US:ETrade\(dq,\(dq2013\(dq,\(dq2013\-01\-01\(dq,\(dq2013\-12\-31\(dq,\(dqVEA\(dq,\(dq10.00\(dq+\(dqAssets:US:ETrade\(dq,\(dq2013\(dq,\(dq2013\-01\-01\(dq,\(dq2013\-12\-31\(dq,\(dqVHT\(dq,\(dq18.00\(dq+\(dqAssets:US:ETrade\(dq,\(dq2014\(dq,\(dq2014\-01\-01\(dq,\(dq2014\-12\-31\(dq,\(dqGLD\(dq,\(dq0\(dq+\(dqAssets:US:ETrade\(dq,\(dq2014\(dq,\(dq2014\-01\-01\(dq,\(dq2014\-12\-31\(dq,\(dqITOT\(dq,\(dq\-11.00\(dq+\(dqAssets:US:ETrade\(dq,\(dq2014\(dq,\(dq2014\-01\-01\(dq,\(dq2014\-12\-31\(dq,\(dqUSD\(dq,\(dq4881.44\(dq+\(dqAssets:US:ETrade\(dq,\(dq2014\(dq,\(dq2014\-01\-01\(dq,\(dq2014\-12\-31\(dq,\(dqVEA\(dq,\(dq14.00\(dq+\(dqAssets:US:ETrade\(dq,\(dq2014\(dq,\(dq2014\-01\-01\(dq,\(dq2014\-12\-31\(dq,\(dqVHT\(dq,\(dq170.00\(dq+.EE+.SS Balance report output+As noted in Output format, if you choose HTML output (by using+\f[CR]\-O html\f[R] or \f[CR]\-o somefile.html\f[R]), you can create a+\f[CR]hledger.css\f[R] file in the same directory to customise the+report\(aqs appearance.+.PP+The HTML and FODS output formats can generate hyperlinks to+\f[CR]hledger\-web\f[R] register views: an account name links to the+account\(aqs transactions, a period heading to the period\(aqs+transactions, and, in the default layout, a figure to the transactions+it is made of, in a register whose final balance is that figure (a+historical balance report asks the register for its historical mode).+The two can differ when a transaction\(aqs postings have dates of their+own, since the report counts such a posting in its own period while the+register shows its whole transaction.+Each link says where it leads in its title, which browsers show on+hover.+E.g.+if your \f[CR]hledger\-web\f[R] server is reachable at+\f[CR]http://localhost:5000\f[R] then you might run the+\f[CR]balance\f[R] command with the extra option+\f[CR]\-\-base\-url=http://localhost:5000\f[R].+You can also produce relative links, like+\f[CR]\-\-base\-url=\(dqsome/path\(dq\f[R] or+\f[CR]\-\-base\-url=\(dq\(dq\f[R].)+.SS Balance charts+With \f[CR]\-\-chart\f[R], \f[CR]balance\f[R] shows a chart of the+report instead of a table, choosing a useful kind of chart+automatically.+In the terminal, this is a bar chart drawn with text characters:+.IP+.EX+$ hledger \-f examples/bcexample.journal bal \-M expenses:food \-b 2013 \-e 2013\-04 cur:USD \-\-chart \-w 70+Balance changes in 2013Q1:++█ Expenses:Food:Groceries ▓ Expenses:Food:Restaurant++Jan 396.46 USD █████████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓+Feb 481.48 USD ████████████████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓+Mar 603.32 USD ██████████████████████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓+.EE+.IP \(bu 2+A multi\-period report of balance changes is charted as stacked bars per+period, showing the net total as the value (and with \f[CR]net\f[R], see+below, as a line mark, \f[CR]┃\f[R] in text).+.IP \(bu 2+A multi\-period report of end balances (\f[CR]\-\-cumulative\f[R],+\f[CR]\-H\f[R]) is charted the same way in text (and as lines in+graphical charts).+.IP \(bu 2+With \f[CR]\-\-chart=grouped\f[R], the accounts are stacked in a bar for+each account type (assets, liabilities, equity, revenues, expenses, then+any accounts of unknown type), side by side in each period, so that the+types can be compared.+Amounts keep their signs (eg liabilities are usually below zero), and+end balances are drawn as bars too.+In text charts, each period has a row for each type, and one for the+total.+Without a report interval, the whole report period is charted this way,+as one period.+.IP \(bu 2+A single\-period report is charted as one bar per account, with the+total below the chart (as a number only, since it belongs to no+account\(aqs bar, even with \f[CR]net\f[R]).+.PP+Negative amounts grow left from an axis, positive amounts right.+Each account has its own colour (when colour is enabled) and fill+character; fill characters repeat after four accounts.+The legend lists the accounts visible in the chart (an account too small+to fill a character cell is left out).+Accounts are coloured by their account type, with conventional colours:+assets blue, liabilities amber, equity violet, revenues green, expenses+red; several accounts of one type get different shades of its colour (up+to eight; beyond that, shades are shared).+(In terminals which advertise 24\-bit colour support, by setting+\f[CR]COLORTERM=truecolor\f[R], these are the same exact colours as in+SVG charts; otherwise they are the terminal\(aqs basic blue, yellow,+magenta, green and red, whose shades depend on its colour theme.)+Accounts of unknown type get distinct colours instead.+But when it shows just one account (in each panel), there is nothing to+tell apart, so the account has its type\(aqs colour, or if its type is+unknown, cyan, a colour no account type uses.+A chart showing just a total (eg with \f[CR]\-0\f[R], or of all+accounts\(aq transaction counts) is also cyan.+Colours and fill characters are chosen by account name, not by position,+so an account usually keeps its colour in other charts: with or without+\f[CR]\-S\f[R], or when you exclude other accounts to see more detail.+(Not always, since there are only a few colours: an account may get a+different one when some accounts are added or removed.)+The chart fills the terminal width, or the width set by+\f[CR]\-w\f[R]/\f[CR]\-\-width\f[R] (except for posting counts, with+\f[CR]\-\-count\f[R], which use at most one character per posting).+It is drawn with unicode block characters, or with ASCII characters if+the system\(aqs text encoding is not UTF\-8.+.PP+There is one chart panel per commodity.+You can reduce this by converting to one commodity (eg+\f[CR]\-X USD\f[R]) or selecting some (eg \f[CR]cur:USD\f[R]); hledger+suggests this when there are more than 8 panels.+In tree mode, each account\(aqs own amounts are stacked, excluding its+subaccounts\(aq, so that nothing is counted twice.+At most 8 accounts are shown per panel; the smallest are combined into+\(dqother\(dq series, one for each account type (so eg assets and+liabilities are never combined), and each type keeps at least its+largest account.+\(dqother\(dq series are grey, or when coloured by type, a greyed+version of their type\(aqs colour.+The total is omitted with \f[CR]\-N\f[R] or \f[CR]\-\-percent\f[R].+Charts draw it (as a line or marks) only with \f[CR]net\f[R], eg+\f[CR]\-\-chart=net\f[R] (or \f[CR]\-\-chart=grouped,net\f[R]).+\f[CR]net\f[R] draws the total where a bar combines several amounts; a+chart of one account, or with one bar per account, does not draw it.+(Text charts show it as a number either way.)+.PP+In a chart of balance changes per period,+\f[CR]\-T\f[R]/\f[CR]\-\-row\-total\f[R] and+\f[CR]\-A\f[R]/\f[CR]\-\-average\f[R] show the net total\(aqs total and+average per period on a line below the chart, eg+\f[CR]Total 11, Average 0.9\f[R]; and in graphical charts, the average+is also drawn as a dashed line across the chart, with an entry in the+legend.+In a chart of end balances (eg with \f[CR]\-H\f[R], or \f[CR]bs\f[R]),+\f[CR]\-A\f[R] shows the average of the net total\(aqs period\-end+balances in the same way (there is no total).+.PP+Each chart is scaled to fit its values.+To draw charts at a fixed scale instead, so that you can compare them+(eg this month\(aqs chart with last month\(aqs), add a SCALE amount:+\f[CR]\-\-chart=SCALE\f[R].+This is the amount that the chart spans; eg with+\f[CR]\-\-chart=5000\f[R], a bar of 5000 fills the chart.+If the chart also has negative values, they take the room they need and+positive values get the rest.+Bars that don\(aqt fit are clipped, with a mark at the edge+(\f[CR]▸\f[R] or \f[CR]◂\f[R] in text, a small triangle in SVG); lines+go off the edge.+A SCALE with a commodity symbol (eg+\f[CR]\-\-chart=\(aq5000 USD\(aq\f[R]) applies to that commodity\(aqs+panel, and one without, to the others.+SCALE can follow KIND and \f[CR]net\f[R], and several SCALEs can be+given, separated by commas (eg+\f[CR]\-\-chart=\(aqauto,5000 USD,4000 EUR\(aq\f[R]); so a SCALE+can\(aqt contain a comma: write it without digit group marks, or with+spaces or periods (eg \f[CR]10 000 EUR\f[R]).+A number like \f[CR]10.000\f[R] is read using that commodity\(aqs+decimal mark, as it is shown in the report: eg in a journal where EUR is+written with a decimal comma, \f[CR]10.000 EUR\f[R] is ten thousand.+For the same scale in text charts, use the same width too+(\f[CR]\-w\f[R]).+.PP+With SVG output (\f[CR]\-o FILE.svg\f[R] or \f[CR]\-O svg\f[R]),+\f[CR]balance\f[R] always shows a chart, as a graphical image.+Time runs along the x axis, and end balances are drawn as lines.+A single\-period report is drawn as vertical bars, one per account, with+the account names below (angled if needed) and values above the bars+(where they fit); or with more than 30 accounts, as horizontal bars.+The y axis shows the unit only on its top (or bottom) label.+In an HTML page, the chart shrinks to fit a narrower window.+.PP+With HTML output, \f[CR]\-\-chart\f[R] shows the chart (as SVG), with+the report\(aqs table collapsed below it (click Report details to show+it).+.PP+With \f[CR]\-O csv\f[R], \f[CR]\-O tsv\f[R] or \f[CR]\-O json\f[R],+\f[CR]\-\-chart\f[R] shows the chart\(aqs data, eg to inspect it or+chart it with other tools.+.PP+The compound balance commands (\f[CR]balancesheet\f[R],+\f[CR]balancesheetequity\f[R], \f[CR]cashflow\f[R],+\f[CR]incomestatement\f[R]) can show charts in the same ways.+They chart their sections\(aq accounts, with the net total (as a number+in text charts, and with \f[CR]net\f[R], as a mark in text charts or a+line in SVG charts), in one of two layouts:+.IP \(bu 2+\f[B]diverging\f[R] (the default, or with+\f[CR]\-\-chart=diverging\f[R]): at each period, all accounts are+stacked in one bar, showing each amount as its contribution to the net+total: sections that add to it (eg assets, revenues) above zero, and+sections that subtract from it (eg liabilities, expenses) below zero.+(This is also why an \f[CR]is\f[R] chart draws expenses below zero while+\f[CR]bal\f[R] draws them above, as their raw amounts are positive;+\f[CR]bal \-\-invert\f[R] gives the same signs.)+In text charts, each period is a row showing the net total, the totals+of the sections on each side at the ends of the bar (as the report\(aqs+table shows them; headed by the sections\(aq names), and with+\f[CR]net\f[R], a mark at the net total\(aqs position.+.IP \(bu 2+\f[B]grouped\f[R] (with \f[CR]\-\-chart=grouped\f[R]): at each period,+each section\(aqs accounts are stacked in a bar of their own, side by+side, so that the sections\(aq sizes can be compared.+Amounts are shown as the tables show them, eg expenses as well as+revenues are positive.+In text charts, each period has a row for each section, showing its+total, and a row showing the net total (and with \f[CR]net\f[R], marking+it).+.PP+Contra amounts \- those with the opposite sign to their section\(aqs+usual sign, like a refund recorded as a negative expense, or a contra+account like accumulated depreciation \- are drawn next to the zero+line, hatched in their account\(aqs colour (below zero in the grouped+layout, and on the other side from their section in the diverging+layout).+They are included in their section\(aqs totals.+(Cash flows, in \f[CR]cf\f[R], have no usual sign: decreases are drawn+like increases, below zero.)+Each section shows at most five accounts, combining the smallest into+\(dqother\(dq; use a depth limit (eg \f[CR]\-1\f[R] or \f[CR]\-2\f[R])+for less detail.+A single\-period report is charted the same way, with one period.+The chart data has one record per value, with fields: commodity, series+(usually an account name), role (\f[CR]item\f[R], \f[CR]other\f[R] or+\f[CR]total\f[R]), mark (\f[CR]bar\f[R], \f[CR]line\f[R] or+\f[CR]marker\f[R]), x (a period heading, period end date, or account+name), and value.+With \f[CR]\-T\f[R] or \f[CR]\-A\f[R], each commodity\(aqs total or+average follows, with role \f[CR]rowtotal\f[R] or \f[CR]average\f[R],+and an empty mark and x.+Eg:+.IP+.EX+$ hledger \-f examples/sample.journal bal \-M expenses \-N \-\-chart \-O csv+\(dqcommodity\(dq,\(dqseries\(dq,\(dqrole\(dq,\(dqmark\(dq,\(dqx\(dq,\(dqvalue\(dq+\(dq$\(dq,\(dqexpenses:food\(dq,\(dqitem\(dq,\(dqbar\(dq,\(dqJan\(dq,\(dq0\(dq+\(dq$\(dq,\(dqexpenses:food\(dq,\(dqitem\(dq,\(dqbar\(dq,\(dqFeb\(dq,\(dq0\(dq+\&...+.EE+.SS Some useful balance reports+Some frequently used \f[CR]balance\f[R] options/reports are:+.IP \(bu 2+\f[CR]bal \-M revenues expenses\f[R]+.PD 0+.P+.PD+Show revenues/expenses in each month.+Also available as the \f[CR]incomestatement\f[R] command.+.IP \(bu 2+\f[CR]bal \-M \-H assets liabilities\f[R]+.PD 0+.P+.PD+Show historical asset/liability balances at each month end.+Also available as the \f[CR]balancesheet\f[R] command.+.IP \(bu 2+\f[CR]bal \-M \-H assets liabilities equity\f[R]+.PD 0+.P+.PD+Show historical asset/liability/equity balances at each month end.+Also available as the \f[CR]balancesheetequity\f[R] command.+.IP \(bu 2+\f[CR]bal \-M assets not:receivable\f[R]+.PD 0+.P+.PD+Show changes to liquid assets in each month.+Also available as the \f[CR]cashflow\f[R] command.+.PP+Also:+.IP \(bu 2+\f[CR]bal \-M expenses \-2 \-SA\f[R]+.PD 0+.P+.PD+Show monthly expenses summarised to depth 2 and sorted by average+amount.+.IP \(bu 2+\f[CR]bal \-M \-\-budget expenses\f[R]+.PD 0+.P+.PD+Show monthly expenses and budget goals.+.IP \(bu 2+\f[CR]bal \-M \-\-valuechange investments\f[R]+.PD 0+.P+.PD+Show monthly change in market value of investment assets.+.IP \(bu 2+\f[CR]bal \-M \-H \-\-gain investments\f[R]+.PD 0+.P+.PD+Show unrealised gain on investment assets (market value minus cost) at+each month end.+.IP \(bu 2+\f[CR]bal investments \-\-valuechange \-D date:lastweek amt:\(aq>1000\(aq \-STA [\-\-invert]\f[R]+.PD 0+.P+.PD+Show top gainers [or losers] last week+.SS balancesheet+(bs)+.PP+Show the end balances in asset and liability accounts.+Amounts are shown with normal positive sign, as in conventional+financial statements.+.IP+.EX+Flags:+ \-\-sum calculation mode: show sum of posting amounts+ (default)+ \-\-valuechange calculation mode: show total change of value+ of period\-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ \-\-gain calculation mode: show unrealised capital+ gain/loss (historical balance value minus cost+ basis)+ \-\-count calculation mode: show the count of postings+ \-\-change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports)+ \-\-cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. \-b/\-\-begin) to+ column end+ \-H \-\-historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date) (default)+ \-l \-\-flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth\-clipped.+ \-t \-\-tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ \-\-drop=N in list mode, omit N leading account name+ parts+ \-\-declared include non\-parent declared accounts (best+ used with \-E)+ \-A \-\-average show a row average column (in multicolumn+ reports)+ \-T \-\-row\-total show a row total column (in multicolumn+ reports)+ \-\-summary\-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ \-N \-\-no\-total omit the final total row+ \-\-no\-elide in tree mode, don\(aqt squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without \-E)+ \-\-full\-names in tree mode, show full account names instead+ of indented leaf names+ \-\-format=FORMATSTR use this custom line format (in simple+ reports)+ \-S \-\-sort\-amount sort by amount instead of account code/name+ \-% \-\-percent express values in percentage of each column\(aqs+ total+ \-\-layout=ARG how to show multi\-commodity amounts:+ \(aqwide[,WIDTH]\(aq: all commodities on one line+ \(aqtall\(aq : each commodity on a new line+ \(aqbare\(aq : bare numbers, symbols in a+ column+ \-\-base\-url=URLPREFIX in html output, generate hyperlinks to+ hledger\-web, with this prefix. (Usually the base+ url shown by hledger\-web; can also be relative.)+ \-O \-\-output\-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ \-o \-\-output\-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ \-\-view write output to FILE, or to view.FMT in+ hledger\(aqs cache directory, and open it in the+ system\(aqs default viewer for its format (eg a web+ browser for html). The default format is html.+ \-\-chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: diverging (sections above and below zero;+ the default) or grouped (sections side by side).+ net: also draw the net total (a line, or marks+ in text charts). SCALE: the amount that fills+ the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ \-w \-\-width=N with \-\-chart: draw the chart N characters wide+ (default: the terminal width)+.EE+.PP+This command displays a balance sheet, showing historical ending+balances of asset and liability accounts.+(To see equity as well, use the balancesheetequity command.)+.PP+Accounts declared with the \f[CR]Asset\f[R], \f[CR]Cash\f[R] or+\f[CR]Liability\f[R] type are shown (see account types).+Or if no such accounts are declared, it shows top\-level accounts named+\f[CR]asset\f[R] or \f[CR]liability\f[R] (case insensitive, plurals+allowed) and their subaccounts.+.PP+Example:+.IP+.EX+$ hledger balancesheet+Balance Sheet 2008\-12\-31++ || 2008\-12\-31 +====================++============+ Assets || +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-+ assets:bank:saving || $1 + assets:cash || $\-2 +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-+ || $\-1 +====================++============+ Liabilities || +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-+ liabilities:debts || $\-1 +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-+ || $\-1 +====================++============+ Net: || 0 +.EE+.PP+This command is a higher\-level variant of the \f[CR]balance\f[R]+command, and supports many of that command\(aqs features, such as+multi\-period reports.+It is similar to \f[CR]hledger balance \-H assets liabilities\f[R], but+with smarter account detection, and liabilities displayed with their+sign flipped.+.PP+This command also supports the output destination and output format+options The output formats supported are \f[CR]txt\f[R], \f[CR]csv\f[R],+\f[CR]tsv\f[R], \f[CR]html\f[R], \f[CR]json\f[R], and \f[CR]svg\f[R] (a+chart; see Balance charts).+.SS balancesheetequity+(bse)+.PP+Show a balance sheet, with historical ending balances of asset,+liability and equity accounts.+Amounts are shown with normal positive sign, as in conventional+financial statements.+.IP+.EX+Flags:+ \-\-sum calculation mode: show sum of posting amounts+ (default)+ \-\-valuechange calculation mode: show total change of value+ of period\-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ \-\-gain calculation mode: show unrealised capital+ gain/loss (historical balance value minus cost+ basis)+ \-\-count calculation mode: show the count of postings+ \-\-change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports)+ \-\-cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. \-b/\-\-begin) to+ column end+ \-H \-\-historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date) (default)+ \-l \-\-flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth\-clipped.+ \-t \-\-tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ \-\-drop=N in list mode, omit N leading account name+ parts+ \-\-declared include non\-parent declared accounts (best+ used with \-E)+ \-A \-\-average show a row average column (in multicolumn+ reports)+ \-T \-\-row\-total show a row total column (in multicolumn+ reports)+ \-\-summary\-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ \-N \-\-no\-total omit the final total row+ \-\-no\-elide in tree mode, don\(aqt squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without \-E)+ \-\-full\-names in tree mode, show full account names instead+ of indented leaf names+ \-\-format=FORMATSTR use this custom line format (in simple+ reports)+ \-S \-\-sort\-amount sort by amount instead of account code/name+ \-% \-\-percent express values in percentage of each column\(aqs+ total+ \-\-layout=ARG how to show multi\-commodity amounts:+ \(aqwide[,WIDTH]\(aq: all commodities on one line+ \(aqtall\(aq : each commodity on a new line+ \(aqbare\(aq : bare numbers, symbols in a+ column+ \-\-base\-url=URLPREFIX in html output, generate hyperlinks to+ hledger\-web, with this prefix. (Usually the base+ url shown by hledger\-web; can also be relative.)+ \-O \-\-output\-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ \-o \-\-output\-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ \-\-view write output to FILE, or to view.FMT in+ hledger\(aqs cache directory, and open it in the+ system\(aqs default viewer for its format (eg a web+ browser for html). The default format is html.+ \-\-chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: diverging (sections above and below zero;+ the default) or grouped (sections side by side).+ net: also draw the net total (a line, or marks+ in text charts). SCALE: the amount that fills+ the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ \-w \-\-width=N with \-\-chart: draw the chart N characters wide+ (default: the terminal width)+.EE+.PP+This report shows accounts declared with the \f[CR]Asset\f[R],+\f[CR]Cash\f[R], \f[CR]Liability\f[R] or \f[CR]Equity\f[R] type (see+account types).+Or if no such accounts are declared, it shows top\-level accounts named+\f[CR]asset\f[R], \f[CR]liability\f[R] or \f[CR]equity\f[R] (case+insensitive, plurals allowed) and their subaccounts.+.PP+Example:+.IP+.EX+$ hledger balancesheetequity+Balance Sheet With Equity 2008\-12\-31++ || 2008\-12\-31 +====================++============+ Assets || +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-+ assets:bank:saving || $1 + assets:cash || $\-2 +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-+ || $\-1 +====================++============+ Liabilities || +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-+ liabilities:debts || $\-1 +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-+ || $\-1 +====================++============+ Equity || +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-+ || 0 +====================++============+ Net: || 0 +.EE+.PP+This command is a higher\-level variant of the \f[CR]balance\f[R]+command, and supports many of that command\(aqs features, such as+multi\-period reports.+It is similar to+\f[CR]hledger balance \-H assets liabilities equity\f[R], but with+smarter account detection, and liabilities/equity displayed with their+sign flipped.+.PP+This report is the easiest way to see if the accounting equation (A+L+E+= 0) is satisfied (after you have done a \f[CR]close \-\-retain\f[R] to+merge revenues and expenses with equity, and perhaps added+\f[CR]\-\-infer\-equity\f[R] to balance your commodity conversions).+.PP+This command also supports the output destination and output format+options The output formats supported are \f[CR]txt\f[R], \f[CR]csv\f[R],+\f[CR]tsv\f[R], \f[CR]html\f[R], \f[CR]json\f[R], and \f[CR]svg\f[R] (a+chart; see Balance charts).+.SS cashflow+(cf)+.PP+Show a (simple) cashflow statement, with the inflows and outflows+affecting \(dqcash\(dq (ie, liquid, easily convertible) assets.+Amounts are shown with normal positive sign, as in conventional+financial statements.+.IP+.EX+Flags:+ \-\-sum calculation mode: show sum of posting amounts+ (default)+ \-\-valuechange calculation mode: show total change of value+ of period\-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ \-\-gain calculation mode: show unrealised capital+ gain/loss (historical balance value minus cost+ basis)+ \-\-count calculation mode: show the count of postings+ \-\-change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports) (default)+ \-\-cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. \-b/\-\-begin) to+ column end+ \-H \-\-historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date)+ \-l \-\-flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth\-clipped.+ \-t \-\-tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ \-\-drop=N in list mode, omit N leading account name+ parts+ \-\-declared include non\-parent declared accounts (best+ used with \-E)+ \-A \-\-average show a row average column (in multicolumn+ reports)+ \-T \-\-row\-total show a row total column (in multicolumn+ reports)+ \-\-summary\-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ \-N \-\-no\-total omit the final total row+ \-\-no\-elide in tree mode, don\(aqt squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without \-E)+ \-\-full\-names in tree mode, show full account names instead+ of indented leaf names+ \-\-format=FORMATSTR use this custom line format (in simple+ reports)+ \-S \-\-sort\-amount sort by amount instead of account code/name+ \-% \-\-percent express values in percentage of each column\(aqs+ total+ \-\-layout=ARG how to show multi\-commodity amounts:+ \(aqwide[,WIDTH]\(aq: all commodities on one line+ \(aqtall\(aq : each commodity on a new line+ \(aqbare\(aq : bare numbers, symbols in a+ column+ \-\-base\-url=URLPREFIX in html output, generate hyperlinks to+ hledger\-web, with this prefix. (Usually the base+ url shown by hledger\-web; can also be relative.)+ \-O \-\-output\-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ \-o \-\-output\-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ \-\-view write output to FILE, or to view.FMT in+ hledger\(aqs cache directory, and open it in the+ system\(aqs default viewer for its format (eg a web+ browser for html). The default format is html.+ \-\-chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: diverging (sections above and below zero;+ the default) or grouped (sections side by side).+ net: also draw the net total (a line, or marks+ in text charts). SCALE: the amount that fills+ the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ \-w \-\-width=N with \-\-chart: draw the chart N characters wide+ (default: the terminal width)+.EE+.PP+This report shows accounts declared with the \f[CR]Cash\f[R] type (see+account types).+Or if no such accounts are declared, it shows accounts+.IP \(bu 2+under a top\-level account named \f[CR]asset\f[R] (case insensitive,+plural allowed)+.IP \(bu 2+whose name contains some variation of \f[CR]cash\f[R], \f[CR]bank\f[R],+\f[CR]checking\f[R] or \f[CR]saving\f[R].+.PP+More precisely: all accounts matching this case insensitive regular+expression:+.PP+\f[CR]\(haassets?(:.+)?:(cash|bank|che(ck|que?)(ing)?|savings?|currentcash)(:|$)\f[R]+.PP+and their subaccounts.+.PP+An example cashflow report:+.IP+.EX+$ hledger cashflow+Cashflow Statement 2008++ || 2008 +====================++======+ Cash flows || +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-+ assets:bank:saving || $1 + assets:cash || $\-2 +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-+ || $\-1 +.EE+.PP+This command is a higher\-level variant of the \f[CR]balance\f[R]+command, and supports many of that command\(aqs features, such as+multi\-period reports.+It is similar to+\f[CR]hledger balance assets not:fixed not:investment not:receivable\f[R],+but with smarter account detection.+.PP+This command also supports the output destination and output format+options The output formats supported are \f[CR]txt\f[R], \f[CR]csv\f[R],+\f[CR]tsv\f[R], \f[CR]html\f[R], \f[CR]json\f[R], and \f[CR]svg\f[R] (a+chart; see Balance charts).+.SS codes+List the codes seen in transactions, in the order parsed.+.IP+.EX+Flags:+no command\-specific flags+.EE+.PP+This command prints the value of each transaction\(aqs code field, in+the order transactions were parsed.+The transaction code is an optional value written in parentheses between+the date and description, often used to store a cheque number, order+number or similar.+.PP+Transactions aren\(aqt required to have a code, and missing or empty+codes will not be shown by default.+With the \f[CR]\-E\f[R]/\f[CR]\-\-empty\f[R] flag, they will be printed+as blank lines.+.PP+You can add a query to select a subset of transactions.+.PP+Examples:+.IP+.EX+2022/1/1 (123) Supermarket + Food $5.00+ Checking ++2022/1/2 (124) Post Office+ Postage $8.32+ Checking++2022/1/3 Supermarket+ Food $11.23+ Checking ++2022/1/4 (126) Post Office+ Postage $3.21+ Checking+.EE+.IP+.EX+$ hledger codes+123+124+126+.EE+.IP+.EX+$ hledger codes \-E+123+124++126+.EE+.SS commodities+(comm)+.PP+List the commodity symbols used or declared in the journal.+.IP+.EX+Flags:+ \-\-used list commodities used in transactions+ \-\-priced list commodities appearing in P directives+ \-\-declared list commodities declared by commodity directives+ \-\-undeclared list commodities used or priced but not declared+ \-\-unused list commodities declared but not used or priced+ \-\-find list the first commodity matched by the first+ argument (a case\-insensitive infix regexp)+ \-\-directives show as commodity directives (with their display+ styles), for use in journals+.EE+.PP+Most of these flags can be combined.+With \f[CR]\-\-directives\f[R], it shows valid commodity directives,+declaring each commodity\(aqs (declared or inferred) display style,+which could be pasted into a journal file.+Some kinds of query argument are supported: \f[CR]cur:\f[R],+\f[CR]tag:\f[R], and \f[CR]date:\f[R] (also+\f[CR]\-b\f[R]/\f[CR]\-e\f[R]/\f[CR]\-p\f[R] report period options).+.PP+Providing a date query will affect which commodities are reported, as+follows:+.PP+.TS+tab(@);+lw(10.5n) lw(28.1n) lw(31.4n).+T{+Flag+T}@T{+No date query+T}@T{+With a date query+T}+_+T{+(none)+T}@T{+declared ∪ transacted ∪ priced+T}@T{+(transacted ∪ priced) in the period+T}+T{+\f[CR]\-\-used\f[R]+T}@T{+transacted in the journal+T}@T{+transacted in the period+T}+T{+\f[CR]\-\-priced\f[R]+T}@T{+appearing in any P directive+T}@T{+appearing in a P directive in the period+T}+T{+\f[CR]\-\-declared\f[R]+T}@T{+declared with a \f[CR]commodity\f[R] directive+T}@T{+same+T}+T{+\f[CR]\-\-undeclared\f[R]+T}@T{+(transacted ∪ priced) ∖ declared+T}@T{+(transacted ∪ priced in the period) ∖ declared+T}+T{+\f[CR]\-\-unused\f[R]+T}@T{+declared ∖ (transacted ∪ priced)+T}@T{+same+T}+T{+\f[CR]\-\-find\f[R]+T}@T{+the first commodity matching the argument+T}@T{+same+T}+.TE+.PP+Example:+.IP+.EX+$ hledger commodities+$+AAPL+EUR+.EE+.SS descriptions+(desc)+.PP+List the unique descriptions used in transactions.+.IP+.EX+Flags:+no command\-specific flags+.EE+.PP+This command lists the unique descriptions that appear in transactions,+in alphabetic order.+You can add a query to select a subset of transactions.+.PP+Example:+.IP+.EX+$ hledger descriptions+Store Name+Gas Station | Petrol+Person A+.EE+.SS files+List all input files used by the journal(s), in the order they were+read.+This includes the files used to read CSV data: each CSV file is followed+by its rules file and any rules files that includes, and each rules file+is followed by any rules files it includes and the data file it read (if+any).+With a REGEX argument, only file names matching the regular expression+(case sensitive) are shown.+.PP+To find the files, hledger reads them only as far as needed, without+processing their data.+So this command works even when the journal has errors, such as+unbalanced entries or failing balance assertions (but not syntax+errors), and it does not run \f[CR]source\f[R] commands.+If an included file does not exist (or an include\(aqs glob pattern+matches no files), it is omitted from the list, with a warning; this is+not an error.+(This helps tools which generate included files, and need to find them+before they exist.)+If a rules file\(aqs \f[CR]source\f[R] pattern matches several files,+only the one it would read is shown.+.PP+With \f[CR]\-t/\-\-tree\f[R], the files are shown as a tree: each+included file is indented below the file that includes it, and shown+with its path relative to that file\(aqs directory (for a file included+by name, the path as written in the include directive).+The files used to read a CSV or rules file are shown one level below it,+in the same way.+A file included more than once appears at each place it is included.+With a REGEX argument (which is matched against full paths), the files+including a matched file are also shown.+.IP+.EX+Flags:+ \-l \-\-flat list/tree mode: show files as a flat list+ (default)+ \-t \-\-tree list/tree mode: show files as a tree, indenting+ included files below the file that includes them+ \-O \-\-output\-format=FMT select the output format. Supported formats:+ txt, json.+ \-o \-\-output\-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+.EE+.PP+With \f[CR]\-O json\f[R], the files are listed as JSON, for use by other+tools.+Each file is an object with these fields: \f[CR]path\f[R] (the file\(aqs+path, or \f[CR]\-\f[R] for standard input), \f[CR]depth\f[R] (0 for a+main file, 1 for a file it includes or uses, and so on),+\f[CR]parent\f[R] (the path of the file that included or used this one,+or null for a main file), and \f[CR]exists\f[R] (false for a missing+included file, or an include\(aqs glob pattern which matched nothing).+\f[CR]\-\-tree\f[R] does not affect JSON output, and a REGEX argument+selects just the matching files.+.PP+Examples:+.IP+.EX+$ hledger \-f main.journal files+/home/user/finance/main.journal+/home/user/finance/2024.journal+.EE+.IP+.EX+$ hledger \-f main.journal files 2024+/home/user/finance/2024.journal+.EE+.IP+.EX+$ hledger \-f main.journal files \-\-tree+/home/user/finance/main.journal+ 2024.journal+ 2025.journal+ prices/2025.prices+ checking.rules+ common.rules+ data/checking.csv+.EE+.IP+.EX+$ hledger \-f main.journal files \-O json checking+[+ {+ \(dqdepth\(dq: 1,+ \(dqexists\(dq: true,+ \(dqparent\(dq: \(dq/home/user/finance/main.journal\(dq,+ \(dqpath\(dq: \(dq/home/user/finance/checking.rules\(dq+ },+ {+ \(dqdepth\(dq: 2,+ \(dqexists\(dq: true,+ \(dqparent\(dq: \(dq/home/user/finance/checking.rules\(dq,+ \(dqpath\(dq: \(dq/home/user/finance/data/checking.csv\(dq+ }+]+.EE+.SS holdings+Show a report of investment holdings.+.IP+.EX+Flags:+ \-l \-\-flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth\-clipped.+ \-t \-\-tree list/tree mode: show accounts as a tree. Amounts+ include subaccount amounts.+ \-\-no\-elide in tree mode, don\(aqt squash boring parent+ accounts; in list mode, also show parent accounts+ (usually zero, hidden without \-E)+ \-\-full\-names in tree mode, show full account names instead of+ indented leaf names+ \-\-drop=N omit N leading account name parts; in tree mode,+ remove the first N levels+ \-S \-\-sort\-amount sort by value (or with \-B, cost) instead of+ account name, largest first+ \-N \-\-no\-total omit the final total row+ \-\-change show gains during the report period, or with a+ report interval, during each period (default with a+ start date and no interval)+ \-\-cumulative with a report interval, show gains from the+ report start date to each period\(aqs end+ \-H \-\-historical show gains since acquisition, ignoring the report+ start date (default with a report interval)+ \-\-round=TYPE how much rounding or padding should be done when+ displaying amounts ?+ none \- show original decimal digits+ soft \- just add or remove decimal zeros+ to match precision+ hard \- round amounts to precision (default)+ all \- also round cost amounts to precision+ \-\-chart[=net,SCALE] show a chart: instead of the table (txt), above+ it (html), or as data (csv, tsv, json). net: also+ draw the net total (a line, or marks in text+ charts). SCALE: the amount that fills the chart (eg+ 1000 or 1000 USD; one per commodity), for+ comparable charts.+ \-w \-\-width=N with \-\-chart: draw the chart N characters wide+ (default: the terminal width)+ \-O \-\-output\-format=FMT select the output format. Supported formats:+ txt, csv, tsv, html, fods, json, svg.+ \-o \-\-output\-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ \-\-view write output to FILE, or to view.FMT in hledger\(aqs+ cache directory, and open it in the system\(aqs+ default viewer for its format (eg a web browser for+ html). The default format is html.+.EE+.PP+This command shows your lot\-tracked assets (see Lots and capital+gains), and their performance, as of the report end date.+An example:+.IP+.EX+$ hledger holdings \-e 2023\-04\-02+Holdings on 2023\-04\-01++ || Date Age Units Avg cost Unit price Total cost Total value Weight UGain UGain% RGain XIRR +===========================++===========================================================================================================================+ assets:investments:stocks || 2022\-04\-07 359d 10 INFY 2.00 ₹ 100.00 ₹ 20.00 ₹ 1,000.00 ₹ 6.4% 980.00 ₹ 4900.0% 5252.4% + assets:investments:stocks || 73 LTTS 4.79 ₹ 200.00 ₹ 350.00 ₹ 14,600.00 ₹ 93.6% 14,250.00 ₹ 4071.4% 140.00 ₹ 4290.2% +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ || 370.00 ₹ 15,600.00 ₹ 100.0% 15,230.00 ₹ 4116.2% 140.00 ₹ 4342.1% +.EE+.PP+With \f[CR]\-\-lots\f[R], the individual lots are shown:+.IP+.EX+$ hledger holdings \-\-lots \-e 2023\-04\-02+Holdings on 2023\-04\-01++ || Date Age Units Unit cost Unit price Total cost Total value Weight UGain UGain% RGain XIRR +=========================================================++============================================================================================================================+ assets:investments:stocks:{2022\-04\-06, \(dq0002\(dq, 10.00 ₹} || 2022\-04\-06 360d 13 LTTS 10.00 ₹ 200.00 ₹ 130.00 ₹ 2,600.00 ₹ 16.7% 2,470.00 ₹ 1900.0% 140.00 ₹ 3876.1% + assets:investments:stocks:{2022\-04\-07, 2.00 ₹} || 2022\-04\-07 359d 10 INFY 2.00 ₹ 100.00 ₹ 20.00 ₹ 1,000.00 ₹ 6.4% 980.00 ₹ 4900.0% 5252.4% + assets:investments:stocks:{2022\-05\-06, \(dq0002\(dq, 11.00 ₹} || 2022\-05\-06 330d 20 LTTS 11.00 ₹ 200.00 ₹ 220.00 ₹ 4,000.00 ₹ 25.6% 3,780.00 ₹ 1718.2% 5032.7% + assets:investments:stocks:{2022\-06\-06, \(dq0002\(dq, 0.00 ₹} || 2022\-06\-06 299d 40 LTTS 0 200.00 ₹ 0 8,000.00 ₹ 51.3% 8,000.00 ₹ +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ || 370.00 ₹ 15,600.00 ₹ 100.0% 15,230.00 ₹ 4116.2% 140.00 ₹ 4342.1% +.EE+.PP+The columns show:+.IP \(bu 2+each holding\(aqs acquisition date (or earlier basis date) and age+.IP \(bu 2+the number of units held+.IP \(bu 2+the unit cost basis (Unit cost; or Avg cost, the average unit cost of+several lots, or for accounts using the AVERAGE method, the pool\(aqs+running average on the report date)+.IP \(bu 2+the unit market price on the report date (Unit price)+.IP \(bu 2+the total cost basis (Total cost)+.IP \(bu 2+the total market value (Total value)+.IP \(bu 2+the percentage of the portfolio\(aqs total value (Weight).+A holding with no market price has no Weight and isn\(aqt counted in+that total, so the others\(aq weights are a little overstated.+No weights are shown if the holdings are valued in more than one+commodity.+.IP \(bu 2+the unrealised gain and gain percent (UGain, UGain%)+.IP \(bu 2+the realised gain from disposals so far (RGain)+.IP \(bu 2+and the annualised rate of return, as of the report end date (XIRR,+calculated from the holding\(aqs dated cashflows and current value, like+roi\(aqs IRR; it includes realised gains).+Lots received without a transacted cost (eg transferred from another+account) count as invested at their cost basis on their acquisition+date.+.PP+Fully disposed commodities and accounts (\(dqclosed positions\(dq) are+not shown, unless you add \f[CR]\-E/\-\-empty\f[R].+But the totals row\(aqs RGain and XIRR always include them, so those+columns may not add up to their totals; a note below the table then says+how many closed positions are not shown.+.PP+To see a commodity\(aqs performance, a market price should be declared+for it (as of the report end date).+Market prices come from P directives or (with+\f[CR]\-\-infer\-market\-prices\f[R]) from transacted prices, as usual.+Each lot is valued in its cost commodity.+A holding with no market price has no value or gains; the totals\(aq+Total value, UGain, UGain% and XIRR are then those of the other+holdings, and a note below the table names the excluded ones.+(With a report interval, the periods whose totals exclude some are+starred; and a period\(aqs gains exclude the holdings with no market+price at either its start or its end, so that they compare the same+holdings.)+In a multi\-currency portfolio, aggregated values may contain multiple+currencies; use \f[CR]\-X COMM\f[R] for a single\-currency view.+.PP+With \f[CR]\-V\f[R], \f[CR]\-X COMM\f[R] or \f[CR]\-\-value\f[R]+(Valuation), holdings are valued in the default or given valuation+commodity instead, and the cost columns are also converted to it (at the+valuation date, so percent gain is unaffected).+Cashflows are not converted, however, so the XIRR column is left blank+for holdings whose cashflows are in a different commodity.+\f[CR]\-\-value=then\f[R] is not supported, and \f[CR]\-B/\-\-cost\f[R]+doesn\(aqt change the report\(aqs figures (but see sorting and+\f[CR]balance:\f[R] below).+.PP+\f[CR]\-S/\-\-sort\-amount\f[R] sorts the lines by their Total value,+largest first, wherever their account.+Holdings with no market price come after the priced ones, sorted by+their Total cost.+In tree mode, sibling accounts are sorted likewise by their subtree\(aqs+totals, as shown on their headings (an account sorts with the unpriced+ones only when none of its holdings has a market price), and the+holdings under each account as in list mode.+With \f[CR]\-B\f[R], everything is sorted by Total cost.+Values in different commodities are compared by their numbers alone; to+compare them properly, convert them to one commodity with+\f[CR]\-X COMM\f[R].+.PP+Amounts are displayed with their commodity\(aqs display precision.+\f[CR]\-\-round\f[R] can select another rounding strategy.+The percent columns (Weight, UGain%, XIRR) are shown with the display+style configured for the \f[CR]%\f[R] commodity (eg by+\f[CR]\-c \(aq0.00 %\(aq\f[R]).+With colour enabled, the gain columns (UGain, UGain%, RGain, XIRR) show+gains in green and losses in red.+.PP+Query arguments and report flags like \f[CR]\-\-depth\f[R],+\f[CR]\-\-title\f[R] etc.+work as usual.+\f[CR]balance:\f[R] and \f[CR]change:\f[R] query terms test each line+(one commodity in one account).+A line has two amounts, its units and its Total value, and the term\(aqs+commodity symbol selects which is tested:+.IP \(bu 2+\f[CR]holdings balance:\(aq>100\(aq\f[R] \- holdings of more than 100+units (with no symbol, units are tested)+.IP \(bu 2+\f[CR]holdings balance:\(aq>100 AAPL\(aq\f[R] \- holdings of more than+100 AAPL+.IP \(bu 2+\f[CR]holdings balance:\(aq>$1000\(aq\f[R] \- holdings worth more than+$1000.+Lines with no market price have no value, and don\(aqt match.+.IP \(bu 2+\f[CR]holdings \-B balance:\(aq>$1000\(aq\f[R] \- holdings which cost+more than $1000 (with \f[CR]\-B\f[R], Total cost is tested instead of+Total value)+.PP+\f[CR]change:\f[R] tests the line\(aqs change in units during the report+period (so it needs a start date, eg \f[CR]\-b\f[R]), or with the+value\(aqs commodity symbol, the value of that change at the valuation+date.+Unlike in other reports, \f[CR]\-V\f[R]/\f[CR]\-X\f[R] don\(aqt change+which amount is tested; to test the value, write its commodity symbol.+But as in other reports, \f[CR]\-B\f[R] tests cost: the line\(aqs Total+cost, or the cost of its change, instead of their value.+The totals and tree mode\(aqs account headings then cover just the lines+shown.+But Weight is still each line\(aqs share of all the holdings, including+the hidden ones (so the total Weight shows what share the lines shown+make up).+.PP+With \f[CR]\-t/\-\-tree\f[R], holdings are grouped into account+sections: an account with subaccounts or several commodities becomes a+heading row, showing its subtree\(aqs totals computed like the totals+row, with its own holdings beneath it named by their commodity; an+account holding one commodity with no subaccounts is a single combined+row; and with \f[CR]\-\-lots\f[R], each holding\(aqs lots appear beneath+it.+Boring parent accounts are squashed into their child as usual+(considering only accounts with holdings), unless+\f[CR]\-\-no\-elide\f[R] is used.+.PP+With \f[CR]\-O html\f[R], an HTML table is produced instead.+With \f[CR]\-O fods\f[R], a spreadsheet document readable by LibreOffice+etc.+is produced.+With \f[CR]\-O csv\f[R] or \f[CR]\-O tsv\f[R], machine\-readable output+is produced: one record per holding (or lot, with \f[CR]\-\-lots\f[R]),+with full account names, age in days, bare units and gain percent+numbers, and no totals or tree\-mode heading records.+With \f[CR]\-O json\f[R], a JSON array of holding objects is produced.+In both, the cost and value fields are named \f[CR]unitcost\f[R],+\f[CR]unitprice\f[R], \f[CR]totalcost\f[R] and \f[CR]totalvalue\f[R].+.SS Gains during a period+Normally the gain columns show each holding\(aqs gains since it was+acquired.+With a report start date (eg \f[CR]\-b\f[R], \f[CR]\-p\f[R], or+\f[CR]date:\f[R]), they show the gains during the report period instead,+and the report title says so (eg \(dqgains in 2026\-11\(dq):+.IP+.EX+$ hledger holdings \-p today # today\(aqs gains+$ hledger holdings \-p thisyear # this year\(aqs gains so far+$ hledger holdings \-b 2026\-10\-01 # gains since a date (until today)+$ hledger holdings \-p 2026\-q3 # gains in a past period (the report shows holdings at its end)+.EE+.PP+The units, cost, price, value and Weight columns are unchanged; they+show holdings as of the report end date.+But:+.IP \(bu 2+UGain is the change in unrealised gain during the period: the unrealised+gain at the end, minus that on the day before the start date.+(Note that selling realises gains: UGain decreases and RGain increases.)+.IP \(bu 2+UGain% is that as a percentage of the holding\(aqs value on the day+before the start date, plus the net cost added since.+.IP \(bu 2+RGain is the realised gain from disposals during the period.+.IP \(bu 2+XIRR is the annualised rate of return for the period, counting the value+on the day before the start date as invested then.+For a short period this can be a very large number (or blank, when too+large to calculate); UGain% shows the period\(aqs un\-annualised gain.+.PP+The start date is the first day of the period, so gains are measured+from the previous day\(aqs closing prices: \f[CR]\-p today\f[R] shows+today\(aqs gains (today\(aqs market prices compared with the latest ones+before today), and \f[CR]\-b yesterday\f[R] shows yesterday\(aqs and+today\(aqs.+This way consecutive periods\(aq gains add up, and a month\(aqs gains+start from the previous month\(aqs last prices, as in a broker\(aqs+statement.+If a market price is missing at the start or the end, the gains+depending on it are left blank.+With \f[CR]\-E\f[R], holdings fully disposed during the period are shown+too.+.PP+A report start date before your first acquisition gives the same gains+as no start date.+\f[CR]\-H/\-\-historical\f[R] shows the gains since acquisition despite+a start date.+(With a report interval, gains are since acquisition unless you ask+otherwise; see below.)+.SS Holdings over time+With a report interval (eg \f[CR]\-M\f[R], \f[CR]\-Q\f[R],+\f[CR]\-Y\f[R]), holdings shows how your holdings changed: their totals+at the end of each period, each computed as on that date (eg valued at+its market prices).+When the holdings are all of one commodity (eg with a \f[CR]cur:\f[R]+query), their Units, Avg cost and Unit price are shown too.+.PP+The gain columns\(aq period is selected as in other periodic reports+(accumulation mode):+.IP \(bu 2+\f[CR]\-H/\-\-historical\f[R] (the default): gains since acquisition, up+to each period\(aqs end+.IP \(bu 2+\f[CR]\-\-change\f[R]: gains during each period, as in a single\-date+report of that period (above); these add up: the periods\(aq UGain and+RGain sum to those of the whole report period+.IP \(bu 2+\f[CR]\-\-cumulative\f[R]: gains from the report start date up to each+period\(aqs end.+.PP+With no end date, the periods continue up to today, even after your last+transaction (since values change with market prices), and the current+period\(aqs row shows today\(aqs holdings, like the report without an+interval.+List/tree mode and \f[CR]\-\-lots\f[R] make no difference to these+totals, and are ignored.+With \f[CR]\-O csv\f[R], \f[CR]tsv\f[R] or \f[CR]json\f[R], there is one+record per period end, whose \f[CR]unpriced\f[R] field lists the+commodities excluded from its totals for having no market price.+.IP+.EX+$ hledger holdings \-M \-e 2026\-04\-01+Monthly holdings, 2026\-01\-31..2026\-03\-31++ || Units Avg cost Unit price Total cost Total value UGain UGain% RGain XIRR +============++======================================================================================+ 2026\-01\-31 || 10 AAA $10 $12 $100 $120 $20 20.0% 820.5% + 2026\-02\-28 || 6 AAA $10 $15 $60 $90 $30 50.0% $20 1566.4% + 2026\-03\-31 || 6 AAA $10 $9 $60 $54 $\-6 \-10.0% $20 108.0% +.EE+.SS Holdings charts+With \f[CR]\-\-chart\f[R], holdings are shown as a chart: a bar for each+holding (or lot, with \f[CR]\-\-lots\f[R]), labelled by account and+commodity.+A holding\(aqs bar shows its cost basis, and its unrealised gain stacked+on top, reaching its market value (which is shown); or if it has lost+value, the part of its cost basis it is still worth, reaching its market+value, and the part lost beyond it (hatched).+So the solid part of a bar always reaches the market value.+In graphical charts these are coloured like assets (blue), revenues+(green) and expenses (red).+Each bar\(aqs unrealised gain percent is shown after its value, in green+if positive or red if negative.+Graphical charts show it instead of the value (which the axis shows), at+the right of the bars, which are horizontal so that there is room for+all of them.+With a report interval, each period\(aqs gain percent is above its bar,+when there is room for them all.+A holding without a market price is shown as its cost basis, in grey.+There is a chart panel for each commodity the holdings are valued in;+use \f[CR]\-X COMM\f[R] to see them all in one.+With a report interval, there is a bar for each period end instead,+showing all the holdings then: their total cost basis, and their net+unrealised gain or loss (with \f[CR]\-\-chart=net\f[R], also their+value: in graphical charts, a line joining the periods, like other+reports\(aq totals).+With \f[CR]\-\-change\f[R] or \f[CR]\-\-cumulative\f[R], the bars show+the gains the table shows instead: realised gains, and unrealised gains+(hatched, since they are not yet final), with losses below zero, and+with \f[CR]\-\-chart=net\f[R], the net gain (in graphical charts, a line+joining the periods, like other reports\(aq totals).+As in the table, the periods whose values and gains exclude holdings+with no market price are starred, with a note below the chart.+With SVG output (eg \f[CR]\-o holdings.svg\f[R], or \f[CR]\-\-view\f[R])+it is a graphical chart, and with HTML output it is shown above the+report\(aqs table.+See Charts for more.+.IP+.EX+$ hledger holdings \-\-chart \-w 70+Holdings on 2024\-12\-31++USD+█ Cost ▒ Unrealised gain ╱ Unrealised loss ▓ No market price++assets:broker AAPL 2,500.00 USD +66.7% █████████████████▒▒▒▒▒▒▒▒▒▒▒+assets:broker NEW ▓+assets:broker XYZ 450.00 USD \-40.0% █████╱╱╱+.EE+.SS incomestatement+(is)+.PP+Show revenue inflows and expense outflows during the report period.+Amounts are shown with normal positive sign, as in conventional+financial statements.+.IP+.EX+Flags:+ \-\-sum calculation mode: show sum of posting amounts+ (default)+ \-\-valuechange calculation mode: show total change of value+ of period\-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ \-\-gain calculation mode: show unrealised capital+ gain/loss (historical balance value minus cost+ basis)+ \-\-count calculation mode: show the count of postings+ \-\-change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports) (default)+ \-\-cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. \-b/\-\-begin) to+ column end+ \-H \-\-historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date)+ \-l \-\-flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth\-clipped.+ \-t \-\-tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ \-\-drop=N in list mode, omit N leading account name+ parts+ \-\-declared include non\-parent declared accounts (best+ used with \-E)+ \-A \-\-average show a row average column (in multicolumn+ reports)+ \-T \-\-row\-total show a row total column (in multicolumn+ reports)+ \-\-summary\-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ \-N \-\-no\-total omit the final total row+ \-\-no\-elide in tree mode, don\(aqt squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without \-E)+ \-\-full\-names in tree mode, show full account names instead+ of indented leaf names+ \-\-format=FORMATSTR use this custom line format (in simple+ reports)+ \-S \-\-sort\-amount sort by amount instead of account code/name+ \-% \-\-percent express values in percentage of each column\(aqs+ total+ \-\-layout=ARG how to show multi\-commodity amounts:+ \(aqwide[,WIDTH]\(aq: all commodities on one line+ \(aqtall\(aq : each commodity on a new line+ \(aqbare\(aq : bare numbers, symbols in a+ column+ \-\-base\-url=URLPREFIX in html output, generate hyperlinks to+ hledger\-web, with this prefix. (Usually the base+ url shown by hledger\-web; can also be relative.)+ \-O \-\-output\-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ \-o \-\-output\-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ \-\-view write output to FILE, or to view.FMT in+ hledger\(aqs cache directory, and open it in the+ system\(aqs default viewer for its format (eg a web+ browser for html). The default format is html.+ \-\-chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: diverging (sections above and below zero;+ the default) or grouped (sections side by side).+ net: also draw the net total (a line, or marks+ in text charts). SCALE: the amount that fills+ the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ \-w \-\-width=N with \-\-chart: draw the chart N characters wide+ (default: the terminal width)+.EE+.PP+This command displays an income statement, showing revenues and expenses+during one or more periods.+.PP+It shows accounts declared with the \f[CR]Revenue\f[R] or+\f[CR]Expense\f[R] type (see account types).+Or if no such accounts are declared, it shows top\-level accounts named+\f[CR]revenue\f[R] or \f[CR]income\f[R] or \f[CR]expense\f[R] (case+insensitive, plurals allowed) and their subaccounts.+.PP+Example:+.IP+.EX+$ hledger incomestatement+Income Statement 2008++ || 2008 +===================++======+ Revenues || +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-+ income:gifts || $1 + income:salary || $1 +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-+ || $2 +===================++======+ Expenses || +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-+ expenses:food || $1 + expenses:supplies || $1 +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-+ || $2 +===================++======+ Net: || 0 +.EE+.PP+This command is a higher\-level variant of the \f[CR]balance\f[R]+command, and supports many of that command\(aqs features, such as+multi\-period reports.+It is similar to+\f[CR]hledger balance \(aq(revenues|income)\(aq expenses\f[R], but with+smarter account detection, and revenues/income displayed with their sign+flipped.+.PP+This command also supports the output destination and output format+options The output formats supported are \f[CR]txt\f[R], \f[CR]csv\f[R],+\f[CR]tsv\f[R], \f[CR]html\f[R], \f[CR]json\f[R], and \f[CR]svg\f[R] (a+chart; see Balance charts).+.SS notes+List the unique notes that appear in transactions.+.IP+.EX+Flags:+no command\-specific flags+.EE+.PP+This command lists the unique notes that appear in transactions, in+alphabetic order.+You can add a query to select a subset of transactions.+The note is the part of the transaction description after a | character+(or if there is no |, the whole description).+.PP+Example:+.IP+.EX+$ hledger notes+Petrol+Snacks+.EE+.SS payees+List the payee/payer names used or declared in the journal.+.IP+.EX+Flags:+ \-\-used list payees used+ \-\-declared list payees declared+ \-\-undeclared list payees used but not declared+ \-\-unused list payees declared but not used+ \-\-find list the first payee matched by the first+ argument (a case\-insensitive infix regexp)+ \-\-directives show as payee directives, for use in journals+.EE+.PP+This command lists unique payee/payer names \- all of them by default,+or just the ones which have been used in transaction descriptions, or+declared with \f[CR]payee\f[R] directives, or used but not declared, or+declared but not used, or just the first one matched by a pattern (with+\f[CR]\-\-find\f[R], returning a non\-zero exit code if it fails).+.PP+The payee/payer name is the part of the transaction description before a+| character (or if there is no |, the whole description).+.PP+With \f[CR]\-\-directives\f[R], it shows valid payee directives, which+could be pasted into a journal file.+.PP+You can add query arguments to select a subset of transactions or+payees.+Note that transaction\-specific query terms like \f[CR]date:\f[R] will+exclude declared\-but\-unused payees, which don\(aqt have that field.+.PP+Example:+.IP+.EX+$ hledger payees+Store Name+Gas Station+Person A+.EE+.SS prices+Print the market prices declared with P directives.+With \-\-infer\-market\-prices, also show any additional prices inferred+from costs.+With \-\-show\-reverse, also show additional prices inferred by+reversing known prices.+With \-\-show\-aliases, also show the exchange rates provided by+commodity aliases.+.IP+.EX+Flags:+ \-\-show\-reverse also show the prices inferred by reversing known+ prices+ \-\-show\-aliases also show the exchange rates provided by+ commodity aliases+ \-\-summary summarise declared prices per commodity instead+ of listing them+ \-\-locations also show where prices where declared+.EE+.PP+With \f[CR]\-\-locations\f[R], each price line gets a trailing+\f[CR]; location: FILE:LINE\f[R] comment showing where it came from.+Declared prices point at their P directive; prices inferred from costs+point at the parent transaction\(aqs first line.+Reversed prices keep the source position of the directive they were+derived from.+.PP+With \f[CR]\-\-show\-aliases\f[R], each commodity alias which provides+an exchange rate (between a commodity and its alias, when there are no+market prices between them) is shown as a price dated 0000\-01\-01 with+a \f[CR]; commodity alias\f[R] comment.+Its location is the commodity directive which declared the alias.+These are used only when market prices can\(aqt provide a conversion,+see Finding market price.+.PP+Price amounts are always displayed with their full precision, except for+reverse prices which are limited to 8 decimal digits.+.PP+Prices can be filtered by a date:, cur:, amt: or find: query.+.PP+Generally if you run this command with \-\-infer\-market\-prices+\-\-show\-reverse \-\-show\-aliases, it will show the same prices used+internally to calculate value reports.+But if in doubt, you can inspect those directly by running the value+report with \-\-debug=2.+.PP+Examples:+.IP+.EX+$ hledger prices+P 2024\-01\-01 AAPL $150+P 2024\-02\-01 AAPL $160+P 2024\-02\-01 EUR $1.08+.EE+.IP+.EX+$ hledger prices \-\-infer\-market\-prices+P 2024\-01\-01 AAPL $150+P 2024\-01\-05 AAPL $150+P 2024\-02\-01 AAPL $160+P 2024\-02\-01 EUR $1.08+.EE+.SS prices summary+With \f[CR]\-\-summary\f[R], instead of listing individual prices,+\f[CR]prices\f[R] prints one row per commodity used in the journal+(other than the base currency), with the following columns:+.IP \(bu 2+\f[B]Commodity\f[R] \(em the commodity, as an ISO 4217 code if possible.+.IP \(bu 2+\f[B]Prices\f[R] \(em the number of market price declarations for that+commodity.+.IP \(bu 2+\f[B]Earliest\f[R] / \f[B]Latest\f[R] \(em the date range of those+prices.+.IP \(bu 2+\f[B]Period\f[R] \(em the duration between earliest and latest.+.IP \(bu 2+\f[B]Coverage\f[R] \(em the percentage of weekdays in that period that+have a price declared (or blank when fewer than two prices).+.PP+Summary mode is a quick way to spot gaps in your price data, and pairs+naturally with getprices.+Only prices declared with P directives are counted; prices inferred with+\f[CR]\-\-show\-reverse\f[R] or \f[CR]\-\-infer\-market\-prices\f[R] are+ignored.+.PP+Queries (\f[CR]cur:\f[R], \f[CR]date:\f[R], \f[CR]amt:\f[R],+\f[CR]find:\f[R]) can be used to narrow the prices that are summarised.+.SS print+Show transactions\(aq journal entries, or export journal data to another+format.+.IP+.EX+Flags:+ \-a \-\-all show all details (\-\-explicit \-\-lots+ \-\-verbose\-tags)+ \-x \-\-explicit show all inferred info explicitly+ \-\-verbose\-tags add tags indicating generated/modified data+ \-\-invert display all amounts with reversed sign+ \-\-locations add tags showing file paths and line numbers+ \-\-export reproduce the whole journal, with directives and+ comments preserved and included files inlined+ \-m \-\-match=DESC fuzzy search for one recent transaction with+ description closest to DESC+ \-\-new show only newer\-dated transactions added in each+ file since last run+ \-\-round=TYPE how much rounding or padding should be done when+ displaying amounts ?+ none \- show original decimal digits,+ as in journal (default)+ soft \- just add or remove decimal zeros+ to match precision+ hard \- round posting amounts to precision+ (can unbalance transactions)+ all \- also round cost amounts to precision+ (can unbalance transactions)+ \-\-layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 \- right\-align amounts, as in hledger 1+ COL \- align decimal marks at column COL+ (default: 53)+ \-\-base\-url=URLPREFIX in html output, generate links to hledger\-web,+ with this prefix. (Usually the base url shown by+ hledger\-web; can also be relative.)+ \-O \-\-output\-format=FMT select the output format. Supported formats:+ journal, ledger, beancount, csv, tsv, html, fods,+ json, sql.+ \-o \-\-output\-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ \-\-view write output to FILE, or to view.FMT in hledger\(aqs+ cache directory, and open it in the system\(aqs+ default viewer for its format (eg a web browser for+ html). The default format is html.+.EE+.PP+The print command displays full journal entries (transactions) from the+journal file, sorted by date (or with \f[CR]\-\-date2\f[R], by secondary+date).+(For a compact one\-line\-per\-transaction overview, see the+\f[CR]transactions\f[R] command.)+.PP+By default, directives and inter\-transaction comments are not shown+(except for comment lines immediately preceding a transaction, which are+shown with it), and entries are sorted by date.+So the default print output is somewhat lossy.+To reproduce the whole journal, including directives and comments, use+\f[CR]\-\-export\f[R] (see below).+.PP+Eg:+.IP+.EX+$ hledger print \-f examples/sample.journal date:200806+2008/06/01 gift+ assets:bank:checking $1+ income:gifts $\-1++2008/06/02 save+ assets:bank:saving $1+ assets:bank:checking $\-1++2008/06/03 * eat & shop+ expenses:food $1+ expenses:supplies $1+ assets:cash $\-2+.EE+.SS print explicitness+Normally, whether posting amounts are implicit or explicit is preserved.+For example, when an amount is omitted in the journal, it will not+appear in the output.+Similarly, if a conversion cost is implied but not written, it will not+appear in the output.+.PP+You can use the \f[CR]\-x\f[R]/\f[CR]\-\-explicit\f[R] flag to force+explicit display of all amounts and costs.+This can be useful for troubleshooting or for making your journal more+readable and robust against data entry errors.+\f[CR]\-x\f[R] is also implied by using any of+\f[CR]\-B\f[R],\f[CR]\-V\f[R],\f[CR]\-X\f[R],\f[CR]\-\-value\f[R].+.PP+The \f[CR]\-x\f[R]/\f[CR]\-\-explicit\f[R] flag will cause any postings+with a multi\-commodity amount (which can arise when a multi\-commodity+transaction has an implicit amount) to be split into multiple+single\-commodity postings, keeping the output parseable.+.PP+To see more details \(em not just inferred amounts and costs, but also+lot subaccounts and postings, and the hidden tags that hledger adds to+classify things \(em use \f[CR]\-a\f[R]/\f[CR]\-\-all\f[R], which is+equivalent to \f[CR]\-\-explicit \-\-lots \-\-verbose\-tags\f[R].+.SS print layout+By default, \f[CR]print\f[R] aligns posting amounts so that their+decimal mark is at column 53 (or would be if they had a decimal mark).+If needed, it will shift a transaction\(aqs amounts further to the right+to ensure at least 2 spaces between account names and amounts.+Also, any balance assertion/assignment operators (\f[CR]=\f[R],+\f[CR]=*\f[R] etc.)+are aligned to the right of the posting amounts; and the+assertion/assignment amounts will be aligned by their decimal marks.+.PP+You can customise this with \f[CR]\-\-layout\f[R]:+.IP \(bu 2+\f[CR]\-\-layout=COL\f[R] \(em sets a different target column for+posting amounts\(aq decimal mark+.IP \(bu 2+\f[CR]\-\-layout=hledger1\f[R] \(em use hledger 1 layout (right\-aligned+posting amounts in each transaction).+.PP+If you want to change the default, put something like this in+\f[CR]\(ti/.hledger.conf\f[R]:+.IP+.EX+[print]+\-\-layout=hledger1+.EE+.PP+Other print\-like commands (close, import, rewrite, add) also accept+\f[CR]\-\-layout\f[R].+.SS print amount style+Amounts will be displayed mostly in their commodity\(aqs display style,+with standardised symbol placement, decimal mark, and digit group marks.+This does not apply to their decimal digits; \f[CR]print\f[R] normally+shows the same decimal digits that are recorded in each journal entry.+(Calculated amounts with a repeating decimal, eg from converting+\f[CR]10 min\f[R] to hours, are shown with 8 decimal places.)+.PP+You can override the decimal precisions with \f[CR]print\f[R]\(aqs+special \f[CR]\-\-round\f[R] option.+\f[CR]\-\-round\f[R] tries to show amounts with their commodities\(aq+standard decimal precisions, increasingly strongly:+.IP \(bu 2+\f[CR]\-\-round=none\f[R] show amounts with original precisions+(default)+.IP \(bu 2+\f[CR]\-\-round=soft\f[R] add/remove decimal zeros in amounts (except+costs)+.IP \(bu 2+\f[CR]\-\-round=hard\f[R] round amounts (except costs), possibly hiding+significant digits+.IP \(bu 2+\f[CR]\-\-round=all\f[R] round all amounts and costs+.PP+\f[CR]soft\f[R] is good for non\-lossy cleanup, displaying more+consistent decimals where possible, without making entries unbalanced.+.PP+\f[CR]hard\f[R] or \f[CR]all\f[R] can be good for stronger cleanup, when+decimal rounding is wanted.+Note rounding can produce unbalanced journal entries, perhaps requiring+manual fixup.+.SS print parseability+Usually, print\(aqs output is a valid hledger journal, which you can+pipe into a second hledger command for further processing.+This is sometimes convenient for rewriting journal entries:+.IP+.EX+# Make today\(aqs shopping entry explicit. (\-f \- means read from standard input.)+$ hledger print date:today desc:shop | hledger \-f\- print \-x+.EE+.PP+or for achieving certain kinds of query:+.IP+.EX+# Show running total of food expenses paid from cash.+$ hledger print assets:cash | hledger \-f\- reg expenses:food+.EE+.PP+But here are some things which can cause print\(aqs output to become+unparseable:+.IP \(bu 2+\f[CR]\-\-round\f[R] (see above) can disrupt transaction balancing.+.IP \(bu 2+Account aliases or pivoting can disrupt account names, balance+assertions, or balance assignments.+.IP \(bu 2+Value reporting also can disrupt balance assertions or balance+assignments.+.IP \(bu 2+Auto postings can generate too many amountless postings.+.IP \(bu 2+\f[CR]\-\-infer\-costs or \-\-infer\-equity\f[R] can generate+too\-complex redundant costs.+.IP \(bu 2+Because print always shows transactions in date order, balance+assertions involving non\-date\-ordered transactions (and same\-day+postings) could be disrupted.+.PP+Also, printing a subset of journal entries can disrupt validation of+balance assertions or lot entries.+And print does not reproduce directives (unless \f[CR]\-\-export\f[R] is+used).+Lot entries are printed with their inferred cost basis annotations, so+they can still be read without the commodity\(aqs \f[CR]lots:\f[R]+declaration when the default cost basis method is used; but with other+methods, or \f[CR]lots: NONE\f[R] accounts, the missing declarations+will change how they are read.+(\f[CR]\-\-export\f[R] output keeps lot entries as written, since it+reproduces the declarations.)+To suppress errors from these, we often use the \f[CR]\-I\f[R] flag+(short for \f[CR]\-\-ignore\-assertions \-\-ignore\-lots\f[R]).+So any time you are reading from standard input with \f[CR]\-f\-\f[R],+consider adding \f[CR]\-I\f[R] also.+.SS print export mode+With \f[CR]\-\-export\f[R], print reproduces the whole journal in its+original order, with directives, top\-level comment lines and+\f[CR]comment\f[R] blocks preserved verbatim, and with each transaction+shown as print normally shows it (so \f[CR]\-x\f[R],+\f[CR]\-\-round\f[R], \f[CR]\-\-layout\f[R] etc.+still apply).+Blank lines are normalised: there is one blank line between+transactions, and between groups of directive or comment lines.+The output can be read by hledger as an equivalent journal, so this is+the mode to use when reformatting or regenerating a journal file.+Some details:+.IP \(bu 2+Included files are inlined at the position of their \f[CR]include\f[R]+directive, and the \f[CR]include\f[R] line itself is dropped.+If you want to preserve a multi\-file structure rather than flattening+it, currently the best way is: comment out the \f[CR]include\f[R]+directives (they will be preserved as comments), export each file+individually, then uncomment the \f[CR]include\f[R] directives in the+exported main file.+(A file which depends on directives in its parent file, such as+\f[CR]Y\f[R] or \f[CR]decimal\-mark\f[R], might need those added+temporarily while it is exported.)+.IP \(bu 2+\f[CR]apply account\f[R], \f[CR]alias\f[R] and their \f[CR]end\f[R]+directives are dropped, since their effect is already applied to the+account names shown.+(An \f[CR]account\f[R] declaration inside an \f[CR]apply account\f[R]+block is reproduced as written, without the parent account prefix.)+.IP \(bu 2+Directives which hledger ignores (for compatibility with Ledger) are not+exported.+.IP \(bu 2+By default, periodic transaction rules (\f[CR]\(ti\f[R]) and auto+posting rules (\f[CR]=\f[R]) are exported as directives.+With \f[CR]\-\-forecast\f[R] and/or \f[CR]\-\-auto\f[R], the generated+transactions (at the end of the output) and postings are exported+instead, and the rules are not.+In other words, these flags materialise the rules.+Postings generated by \f[CR]\-\-infer\-equity\f[R] are exported too.+(In Beancount output, these rules are never exported, only whatever has+been generated.)+.IP \(bu 2+A query still selects which transactions are shown, but all directives+and comments are kept.+.IP \(bu 2+Transactions from non\-journal files (eg an included CSV file) are added+at the end.+.IP \(bu 2+The \f[CR]journal\f[R] (default), \f[CR]ledger\f[R] and+\f[CR]beancount\f[R] output formats are supported.+With \f[CR]\-O ledger\f[R], transactions use Ledger\(aqs lot syntax, and+directives which hledger accepts but Ledger does not+(\f[CR]decimal\-mark\f[R], a one\-line \f[CR]commodity\f[R] directive+with an amount, a periodic transaction rule with a description, an auto+posting rule with \f[CR]*N\f[R] amount multipliers) are commented out,+with an explanatory comment.+Other hledger\-specific syntax may remain; see Ledger output.+With \f[CR]\-O beancount\f[R], Beancount \f[CR]option\f[R],+\f[CR]commodity\f[R], \f[CR]open\f[R] and \f[CR]price\f[R] directives+are generated from the journal\(aqs declarations and data, other+directives (which have no Beancount equivalent) are dropped, and+comments are converted to Beancount comments; see Beancount output.+Note for both Ledger and Beancount, manual fixups may still be required+in some cases; but the export will be a good start.+.SS print, other features+With \f[CR]\-B\f[R]/\f[CR]\-\-cost\f[R], amounts with costs are shown+converted to cost.+.PP+With \f[CR]\-\-invert\f[R], posting amounts are shown with their sign+flipped.+It could be useful if you have accidentally recorded some transactions+with the wrong signs.+.PP+With \f[CR]\-\-new\f[R], print shows only transactions it has not seen+on a previous run.+This uses the same deduplication system as the \f[CR]import\f[R]+command.+(See import\(aqs docs for details.)+.PP+With \f[CR]\-m DESC\f[R]/\f[CR]\-\-match=DESC\f[R], print shows one+recent transaction whose description is most similar to DESC.+DESC should contain at least two characters.+If there is no similar\-enough match, no transaction will be shown and+the program exit code will be non\-zero.+.PP+With \f[CR]\-\-locations\f[R], print adds the source file and line+number to every transaction, as a tag.+.SS print output format+This command also supports the output destination and output format+options The output formats supported are \f[CR]journal\f[R] (the+default; \f[CR]txt\f[R] is also accepted), \f[CR]ledger\f[R],+\f[CR]beancount\f[R], \f[CR]csv\f[R], \f[CR]tsv\f[R], \f[CR]html\f[R],+\f[CR]fods\f[R], \f[CR]json\f[R] and \f[CR]sql\f[R].+.PP+The \f[CR]ledger\f[R] format is currently the same as \f[CR]journal\f[R]+except it renders amounts\(aq cost basis using Ledger\(aqs lot syntax+(\f[CR][DATE] (LABEL) {COST}\f[R]) instead of hledger\(aqs+(\f[CR]{DATE, \(dqLABEL\(dq, COST}\f[R]).+.PP+The \f[CR]beancount\f[R] format tries to produce Beancount\-compatible+output, as follows:+.IP \(bu 2+Transaction and postings with unmarked status are converted to cleared+(\f[CR]*\f[R]) status.+.IP \(bu 2+Transactions\(aq payee and note are backslash\-escaped and+double\-quote\-escaped and wrapped in double quotes.+.IP \(bu 2+Transaction and posting tags are converted to Beancount metadata lines.+.IP \(bu 2+Commodity symbols are converted to upper case, and a small number of+currency symbols like \f[CR]$\f[R] are converted to the corresponding+currency names.+.IP \(bu 2+Account name parts are capitalised and unsupported characters are+replaced with \f[CR]\-\f[R].+The first part must be one of Assets, Liabilities, Equity, Income or+Expenses; if it is not, but the account\(aqs type is known (declared or+inferred), the corresponding one of those is prepended; otherwise an+error is raised.+(Or, use \f[CR]\-\-alias\f[R] options to bring your accounts into+compliance.)+.IP \(bu 2+Balance assignments are converted to explicit amounts.+.IP \(bu 2+Virtual and balanced virtual postings are dropped.+.PP+By default only transactions are shown.+With \f[CR]\-\-export\f[R], the directives Beancount needs are also+generated: options (a commented\-out tolerance option, and+\f[CR]operating_currency\f[R] for the currencies used in costs), a+\f[CR]commodity\f[R] directive for each declared commodity, an+\f[CR]open\f[R] directive for each declared or used account (on the+account\(aqs earliest posting date, or the earliest transaction date),+and \f[CR]price\f[R] directives.+Account and commodity tags become metadata on those directives, and an+account\(aqs \f[CR]lots:\f[R] tag becomes the Beancount booking method.+Other hledger directives are dropped, and top\-level comments are+converted to Beancount comments.+.PP+Here\(aqs an example of print\(aqs CSV output:+.IP+.EX+$ hledger print \-Ocsv+\(dqtxnidx\(dq,\(dqdate\(dq,\(dqdate2\(dq,\(dqstatus\(dq,\(dqcode\(dq,\(dqdescription\(dq,\(dqcomment\(dq,\(dqaccount\(dq,\(dqamount\(dq,\(dqcommodity\(dq,\(dqdebit\(dq,\(dqcredit\(dq,\(dqposting\-status\(dq,\(dqposting\-comment\(dq+\(dq1\(dq,\(dq2008/01/01\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq,\(dqincome\(dq,\(dq\(dq,\(dqassets:bank:checking\(dq,\(dq1\(dq,\(dq$\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq+\(dq1\(dq,\(dq2008/01/01\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq,\(dqincome\(dq,\(dq\(dq,\(dqincome:salary\(dq,\(dq\-1\(dq,\(dq$\(dq,\(dq\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq+\(dq2\(dq,\(dq2008/06/01\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq,\(dqgift\(dq,\(dq\(dq,\(dqassets:bank:checking\(dq,\(dq1\(dq,\(dq$\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq+\(dq2\(dq,\(dq2008/06/01\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq,\(dqgift\(dq,\(dq\(dq,\(dqincome:gifts\(dq,\(dq\-1\(dq,\(dq$\(dq,\(dq\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq+\(dq3\(dq,\(dq2008/06/02\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq,\(dqsave\(dq,\(dq\(dq,\(dqassets:bank:saving\(dq,\(dq1\(dq,\(dq$\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq+\(dq3\(dq,\(dq2008/06/02\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq,\(dqsave\(dq,\(dq\(dq,\(dqassets:bank:checking\(dq,\(dq\-1\(dq,\(dq$\(dq,\(dq\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq+\(dq4\(dq,\(dq2008/06/03\(dq,\(dq\(dq,\(dq*\(dq,\(dq\(dq,\(dqeat & shop\(dq,\(dq\(dq,\(dqexpenses:food\(dq,\(dq1\(dq,\(dq$\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq+\(dq4\(dq,\(dq2008/06/03\(dq,\(dq\(dq,\(dq*\(dq,\(dq\(dq,\(dqeat & shop\(dq,\(dq\(dq,\(dqexpenses:supplies\(dq,\(dq1\(dq,\(dq$\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq+\(dq4\(dq,\(dq2008/06/03\(dq,\(dq\(dq,\(dq*\(dq,\(dq\(dq,\(dqeat & shop\(dq,\(dq\(dq,\(dqassets:cash\(dq,\(dq\-2\(dq,\(dq$\(dq,\(dq\(dq,\(dq2\(dq,\(dq\(dq,\(dq\(dq+\(dq5\(dq,\(dq2008/12/31\(dq,\(dq\(dq,\(dq*\(dq,\(dq\(dq,\(dqpay off\(dq,\(dq\(dq,\(dqliabilities:debts\(dq,\(dq1\(dq,\(dq$\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq,\(dq\(dq+\(dq5\(dq,\(dq2008/12/31\(dq,\(dq\(dq,\(dq*\(dq,\(dq\(dq,\(dqpay off\(dq,\(dq\(dq,\(dqassets:bank:checking\(dq,\(dq\-1\(dq,\(dq$\(dq,\(dq\(dq,\(dq1\(dq,\(dq\(dq,\(dq\(dq+.EE+.IP \(bu 2+There is one CSV record per posting, with the parent transaction\(aqs+fields repeated.+.IP \(bu 2+The \(dqtxnidx\(dq (transaction index) field shows which postings belong+to the same transaction.+(This number might change if transactions are reordered within the file,+files are parsed/included in a different order, etc.)+.IP \(bu 2+The amount is separated into \(dqcommodity\(dq (the symbol) and+\(dqamount\(dq (numeric quantity) fields.+.IP \(bu 2+The numeric amount is repeated in either the \(dqdebit\(dq or+\(dqcredit\(dq column, for convenience.+(Those names are not accurate in the accounting sense; it just puts zero+or greater amounts under debit and negative amounts under credit.)+.SS register+(reg)+.PP+Show postings & running total across accounts.+.IP+.EX+Flags:+ \-\-cumulative accumulation mode: show running total from report+ start date (default)+ \-H \-\-historical accumulation mode: show historical running+ total/balance (includes postings before report+ start date)+ \-A \-\-average show running average of posting amounts instead+ of total (implies \-\-empty)+ \-m \-\-match=DESC fuzzy search for one recent posting with+ description closest to DESC+ \-r \-\-related show postings\(aq siblings instead+ \-\-invert display all amounts with reversed sign+ \-\-drop=N omit N leading account name parts+ \-\-sort=FIELDS sort by: date, desc, account, amount, absamount,+ or a comma\-separated combination of these. For a+ descending sort, prefix with \-. (Default: date)+ \-w \-\-width=N set output width (default: terminal width). \-wN,M+ sets description width as well.+ \-\-align\-all guarantee alignment across all lines (slower)+ \-\-base\-url=URLPREFIX in html output, generate links to hledger\-web,+ with this prefix. (Usually the base url shown by+ hledger\-web; can also be relative.)+ \-O \-\-output\-format=FMT select the output format. Supported formats:+ txt, csv, tsv, html, fods, json, svg.+ \-o \-\-output\-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ \-\-view write output to FILE, or to view.FMT in hledger\(aqs+ cache directory, and open it in the system\(aqs+ default viewer for its format (eg a web browser for+ html). The default format is html.+ \-\-chart[=net,SCALE] show a chart: instead of the table (txt), above+ it (html), or as data (csv, tsv, json). net: also+ draw the net total (a line, or marks in text+ charts). SCALE: the amount that fills the chart (eg+ 1000 or 1000 USD; one per commodity), for+ comparable charts.+.EE+.PP+The register command displays matched postings, across all accounts, in+date order, with their running total or running historical balance.+(See also the \f[CR]aregister\f[R] command, which shows matched+transactions in a specific account.)+.PP+register normally shows line per posting, but note that multi\-commodity+amounts will occupy multiple lines (one line per commodity).+.PP+It is typically used with a query selecting a particular account, to see+that account\(aqs activity:+.IP+.EX+$ hledger register checking+2008/01/01 income assets:bank:checking $1 $1+2008/06/01 gift assets:bank:checking $1 $2+2008/06/02 save assets:bank:checking $\-1 $1+2008/12/31 pay off assets:bank:checking $\-1 0+.EE+.PP+With \f[CR]\-\-date2\f[R], it shows and sorts by secondary date instead.+.PP+Postings with a zero amount (including amounts inferred from a balance+assignment) are not shown by default; use the+\f[CR]\-\-empty\f[R]/\f[CR]\-E\f[R] flag to see them.+.PP+For performance reasons, column widths are chosen based on the first+1000 lines; this means unusually wide values in later lines can cause+visual discontinuities as column widths are adjusted.+If you want to ensure perfect alignment, at the cost of more time and+memory, use the \f[CR]\-\-align\-all\f[R] flag.+.PP+The \f[CR]\-\-historical\f[R]/\f[CR]\-H\f[R] flag adds the balance from+any undisplayed prior postings to the running total.+This is useful when you want to see only recent activity, with a+historically accurate running balance:+.IP+.EX+$ hledger register checking \-b 2008/6 \-\-historical+2008/06/01 gift assets:bank:checking $1 $2+2008/06/02 save assets:bank:checking $\-1 $1+2008/12/31 pay off assets:bank:checking $\-1 0+.EE+.PP+The \f[CR]\-\-depth\f[R] option limits the amount of sub\-account detail+displayed.+.PP+The \f[CR]\-\-drop\f[R] option will trim leading segments from account+names.+.PP+The \f[CR]\-\-average\f[R]/\f[CR]\-A\f[R] flag shows the running average+posting amount instead of the running total (so, the final number+displayed is the average for the whole report period).+This flag implies \f[CR]\-\-empty\f[R] (see below).+It is affected by \f[CR]\-\-historical\f[R].+It works best when showing just one account and one commodity.+.PP+The \f[CR]\-\-related\f[R]/\f[CR]\-r\f[R] flag shows the \f[I]other\f[R]+postings in the transactions of the postings which would normally be+shown.+.PP+The \f[CR]\-\-invert\f[R] flag negates all amounts.+For example, it can be used on an income account where amounts are+normally displayed as negative numbers.+It\(aqs also useful to show postings on the checking account together+with the related account:+.PP+The \f[CR]\-\-sort=FIELDS\f[R] flag sorts by the fields given, which can+be any of \f[CR]account\f[R], \f[CR]amount\f[R], \f[CR]absamount\f[R],+\f[CR]date\f[R], or \f[CR]desc\f[R]/\f[CR]description\f[R], optionally+separated by commas.+For example, \f[CR]\-\-sort account,amount\f[R] will group all+transactions in each account, sorted by transaction amount.+Each field can be negated by a preceding \f[CR]\-\f[R], so+\f[CR]\-\-sort \-amount\f[R] will show transactions ordered from+smallest amount to largest amount.+.IP+.EX+$ hledger register \-\-related \-\-invert assets:checking+.EE+.PP+With a reporting interval, register shows summary postings, one per+interval, aggregating the postings to each account:+.IP+.EX+$ hledger register \-\-monthly income+2008/01 income:salary $\-1 $\-1+2008/06 income:gifts $\-1 $\-2+.EE+.PP+Here too, periods with no activity, and summary postings with a zero+amount, are not shown by default; use the+\f[CR]\-\-empty\f[R]/\f[CR]\-E\f[R] flag to see them:+.IP+.EX+$ hledger register \-\-monthly income \-E+2008/01 income:salary $\-1 $\-1+2008/02 0 $\-1+2008/03 0 $\-1+2008/04 0 $\-1+2008/05 0 $\-1+2008/06 income:gifts $\-1 $\-2+2008/07 0 $\-2+2008/08 0 $\-2+2008/09 0 $\-2+2008/10 0 $\-2+2008/11 0 $\-2+2008/12 0 $\-2+.EE+.PP+Often, you\(aqll want to see just one line per interval.+The \f[CR]\-\-depth\f[R] option helps with this, causing subaccounts to+be aggregated:+.IP+.EX+$ hledger register \-\-monthly assets \-\-depth 1+2008/01 assets $1 $1+2008/06 assets $\-1 0+2008/12 assets $\-1 $\-1+.EE+.PP+Note when using report intervals, if you specify start/end dates these+will be adjusted outward if necessary to contain a whole number of+intervals.+This ensures that the first and last intervals are full length and+comparable to the others in the report.+.PP+If you have a deeply nested account tree some reports might benefit from+trimming leading segments from the account names using+\f[CR]\-\-drop\f[R].+.IP+.EX+$ hledger register \-\-monthly income \-\-drop 1+2008/01 salary $\-1 $\-1+2008/06 gifts $\-1 $\-2+.EE+.PP+With \f[CR]\-m DESC\f[R]/\f[CR]\-\-match=DESC\f[R], register does a+fuzzy search for one recent posting whose description is most similar to+DESC.+DESC should contain at least two characters.+If there is no similar\-enough match, no posting will be shown and the+program exit code will be non\-zero.+.SS Custom register output+register normally uses the full terminal width (or 80 columns if it+can\(aqt detect that).+You can override this with the \f[CR]\-\-width\f[R]/\f[CR]\-w\f[R]+option.+.PP+The description and account columns normally share the space equally+(about half of (width \- 40) each).+You can adjust this by adding a description width as part of+\-\-width\(aqs argument, comma\-separated: \f[CR]\-\-width W,D\f[R] .+Here\(aqs a diagram (won\(aqt display correctly in \-\-help):+.IP+.EX+<\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- width (W) \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\->+date (10) description (D) account (W\-41\-D) amount (12) balance (12)+DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA+.EE+.PP+and some examples:+.IP+.EX+$ hledger reg # use terminal width (or 80 on windows)+$ hledger reg \-w 100 # use width 100+$ hledger reg \-w 100,40 # set overall width 100, description width 40+.EE+.PP+This command also supports the output destination and output format+options The output formats supported are \f[CR]txt\f[R], \f[CR]csv\f[R],+\f[CR]tsv\f[R], \f[CR]html\f[R], \f[CR]fods\f[R], \f[CR]json\f[R], and+\f[CR]svg\f[R].+.SS Register charts+With \f[CR]\-\-chart\f[R], or with \f[CR]svg\f[R] output+(\f[CR]\-o FILE.svg\f[R]), it shows a chart instead.+Without a report interval, this is the running total (or average) after+each posting, as a line over time; with postings to several accounts,+each account\(aqs own running total is shown too, in its account+type\(aqs colour (starting from its balance before the report period,+with \f[CR]\-H\f[R]), at most eight of them, the smallest combined into+\(dqother\(dq.+A text chart has a row per posting, with the accounts\(aq running totals+stacked.+With a report interval, it is each account\(aqs amount in each period,+as stacked bars, with the period\(aqs total.+Charts draw the overall running total (with several accounts) or the+periods\(aq totals only with \f[CR]\-\-chart=net\f[R].+With \f[CR]\-\-chart \-O csv\f[R] (or tsv or json) it shows the+chart\(aqs data.+See also Balance charts.+.SS roi+Show the money\-weighted (IRR) and time\-weighted (TWR) rate of return+on your investments.+.IP+.EX+Flags:+ \-\-cashflow show all amounts that were used to compute+ returns+ \-\-investment=QUERY query to select your investment transactions+ \-\-profit\-loss=QUERY \-\-pnl query to select profit\-and\-loss or+ appreciation/valuation transactions (optional)+.EE+.PP+At a minimum, you need to supply a query (which could be just an account+name) to select your investment(s) with \f[CR]\-\-inv\f[R].+.PP+An optional second query to identify your profit and loss transactions+could be given with \f[CR]\-\-pnl\f[R].+If your investment\(aqs value changes are captured solely through price+directives (rather than manual P&L journal entries), or if you do not+need TWR, you can simply omit \f[CR]\-\-pnl\f[R], and no transactions+will be classed as profit and loss in this case.+.PP+This command will compute and display the internal rate of return (IRR,+also known as money\-weighted rate of return) and time\-weighted rate of+return (TWR) for your investments for the time period requested.+IRR is always annualized due to the way it is computed, but TWR is+reported both as a rate over the chosen reporting period and as an+annual rate.+.PP+Price directives will be taken into account if you supply appropriate+\f[CR]\-\-cost\f[R] or \f[CR]\-\-value\f[R] flags (see Value reporting).+.PP+Some special cases of IRR have no solution in the usual sense, and are+reported as:+.IP \(bu 2+0%, when there are no cash flows, or when they all fall on the same day+and add up to zero (nothing is gained or lost, and no time passes)+.IP \(bu 2+\-100%, when money is put in, but nothing comes out of the investment or+is left in it (all of it is lost).+A total loss is \-100% however long the money was invested, even for a+day.+(But a partial loss within one day is an error, below, since its annual+rate depends on how much time passes.)+.PP+In some cases a rate of return can\(aqt be computed.+Then its cell in the report shows \f[CR]error\f[R], the rest of the+report is still shown, and the reasons (each with its period) are+printed after it as a warning.+The reasons can be:+.IP \(bu 2+No solution for Internal Rate of Return (IRR).+Possible causes: IRR is huge (>1000000%), balance of investment becomes+negative at some point in time.+.IP \(bu 2+No solution for Internal Rate of Return (IRR), because money only came+out of the investment in that period (or is still in it at the end), and+none was put in (counting its value at the start as put in), so the IRR+is infinite.+.IP \(bu 2+No solution for Internal Rate of Return (IRR), because all of a+period\(aqs cash flows (including the values at its start and end) fall+on the same day, so no time passes for the gain or loss to happen in.+.IP \(bu 2+Failed to find solution for Internal Rate of Return (IRR).+Either search does not converge to a solution, or converges too slowly.+.IP \(bu 2+Cannot compute the time\-weighted return for DATES (PART): the+investment\(aqs value at the start (...)+plus deposits (...)+is negative.+Possible cause: the balance of the investment becomes negative, eg more+is sold than is held (a short position).+.PP+And in some cases the whole report can\(aqt be produced:+.IP \(bu 2+Error: Could not value the investment on DATE: no market price ...+is known for COMMODITY on or before that date.+A holding has no market price, and none of the investment\(aqs+transactions on or before that date records a price for buying or+selling it.+Add a P directive for it, or record the price of its purchase.+.IP \(bu 2+Error: Period ...+has multiple commodities: ...+The investment, its cash flows or its profit and loss are in more than+one commodity.+Use \-\-value to convert them to one (eg+\f[CR]\-\-value=end,$ \-\-infer\-market\-prices\f[R]).+.PP+Examples:+.IP \(bu 2+Using roi to compute total return of investment in stocks:+https://github.com/hledgerorg/hledger/blob/main/examples/investing/roi\-unrealised.ledger+.IP \(bu 2+Cookbook > Return on Investment: https://hledger.org/roi.html+.SS Spaces and special characters in \f[CR]\-\-inv\f[R] and \f[CR]\-\-pnl\f[R]+Note that \f[CR]\-\-inv\f[R] and \f[CR]\-\-pnl\f[R]\(aqs argument is a+query, and queries could have several space\-separated terms (see+QUERIES).+.PP+To indicate that all search terms form single command\-line argument,+you will need to put them in quotes (see Special characters):+.IP+.EX+$ hledger roi \-\-inv \(aqterm1 term2 term3 ...\(aq+.EE+.PP+If any query terms contain spaces themselves, you will need an extra+level of nested quoting, eg:+.IP+.EX+$ hledger roi \-\-inv=\(dq\(aqAssets:Test 1\(aq cur:USD\(dq \-\-pnl=\(dq\(aqEquity:Unrealized Profit and Loss\(aq\(dq+.EE+.SS Semantics of \f[CR]\-\-inv\f[R] and \f[CR]\-\-pnl\f[R]+Query supplied to \f[CR]\-\-inv\f[R] has to match all transactions that+are related to your investment.+Transactions not matching \f[CR]\-\-inv\f[R] will be ignored.+.PP+In these transactions, ROI will consider postings that match+\f[CR]\-\-inv\f[R] to be \(dqinvestment postings\(dq and other postings+(not matching \f[CR]\-\-inv\f[R]) will be sorted into two categories:+\(dqcash flow\(dq and \(dqprofit and loss\(dq, as ROI needs to know+which part of the investment value is your contributions and which is+due to the return on investment.+.IP \(bu 2+\(dqCash flow\(dq is depositing or withdrawing money, buying or selling+assets, or otherwise converting between your investment commodity and+any other commodity.+Example:+.RS 2+.IP+.EX+2019\-01\-01 Investing in Snake Oil+ assets:cash \-$100+ investment:snake oil++2020\-01\-01 Selling my Snake Oil+ assets:cash $10+ investment:snake oil = 0+.EE+.RE+.IP \(bu 2+\(dqProfit and loss\(dq is change in the value of your investment:+.RS 2+.IP+.EX+2019\-06\-01 Snake Oil falls in value+ investment:snake oil = $57+ equity:unrealized profit or loss+.EE+.RE+.PP+All non\-investment postings are assumed to be \(dqcash flow\(dq, unless+they match \f[CR]\-\-pnl\f[R] query.+Changes in value of your investment due to \(dqprofit and loss\(dq+postings will be considered as part of your investment return.+.PP+The amount of each cash flow is measured from the investment\(aqs+perspective: it is the cost of the transaction\(aqs investment postings,+minus any profit and loss in that transaction.+Its date is the date of those investment postings, even if the+money\(aqs posting has a different date (eg a settlement date).+This means that other postings in the same transaction, such as fees,+don\(aqt change the amount of the cash flow.+.PP+In this example, the investment receives $100, so without+\f[CR]\-\-pnl\f[R] the cash flow is a $100 deposit, and the $1 fee is+not part of the investment at all.+With \f[CR]\-\-pnl expenses\f[R], the fee counts as part of the+investment\(aqs return instead: the cash flow is a $101 deposit, of+which $1 is immediately lost (shown as profit/loss of \-$1):+.IP+.EX+2019\-01\-01 Buying Snake Oil, with a fee+ assets:cash \-$101+ expenses:fees $1+ investment:snake oil $100+.EE+.PP+Example: if you use \f[CR]\-\-inv snake \-\-pnl equity:unrealized\f[R],+then postings in the example below would be classifed as:+.IP+.EX+2019\-01\-01 Snake Oil #1+ assets:cash \-$100 ; cash flow posting+ investment:snake oil ; investment posting++2019\-03\-01 Snake Oil #2+ equity:unrealized pnl \-$100 ; profit and loss posting+ snake oil ; investment posting++2019\-07\-01 Snake Oil #3+ equity:unrealized pnl ; profit and loss posting+ cash \-$100 ; cash flow posting+ snake oil $50 ; investment posting+.EE+.SS Using roi with lots+If your journal records lots, each disposal transaction has a realised+gain posting, by default to \f[CR]revenues:gain\f[R].+Make sure \f[CR]\-\-pnl\f[R] matches that account, eg+\f[CR]\-\-pnl revenues:gain\f[R], so realised gains are counted as+profit.+Cash flows are measured at the investment postings\(aq cost, which for+lots is their cost basis, so without \f[CR]\-\-pnl\f[R] a sale is a+withdrawal of its cost basis only, and its gain is not counted at all:+IRR and TWR will understate the return (eg showing 0% for a buy and a+sale at a profit).+.SS IRR and TWR explained+\(dqROI\(dq stands for \(dqreturn on investment\(dq.+Traditionally this was computed as a difference between current value of+investment and its initial value, expressed in percentage of the initial+value.+.PP+However, this approach is only practical in simple cases, where the+investment receives no in\-flows or out\-flows of money and the rate of+growth is fixed over time.+For more complex scenarios you need different ways to compute rate of+return, and this command implements two of them: IRR and TWR.+.PP+\f[B]Internal rate of return (IRR)\f[R], also called money\-weighted+rate of return, answers the question: \f[I]what single constant annual+interest rate, applied to your actual sequence of deposits and+withdrawals, would produce exactly the ending balance you have?\f[R]+.PP+IRR is inherently personal.+If you deposited a large sum right before a bad period, your IRR is+dragged down \- not because the investment was poorly managed, but+because your timing was bad.+Conversely, investing heavily just before a rally makes your IRR look+great.+This is what makes IRR \(dqmoney\-weighted\(dq: periods when more of+your money is at stake contribute more to the result.+.PP+In technical terms, IRR uses the same approach as computation of net+present value, and tries to find a discount rate that makes the net+present value of all the cash flows of your investment add up to zero.+The implementation in hledger produces results that match the+\f[CR]=XIRR\f[R] formula in Excel.+.PP+\f[B]Time\-weighted rate of return (TWR)\f[R] strips out the effect of+your deposit and withdrawal timing, measuring the investment\(aqs own+performance rather than your experience of it.+.PP+hledger computes TWR from the value of your investment at the end of+each day: its balance at the end of the day, valued (with+\f[CR]\-\-value\f[R]) using the prices in effect on that day.+The order of transactions and prices within a day doesn\(aqt matter.+.IP \(bu 2+The days between two days with cash flows form one stretch, which starts+at the end of the earlier cash flow day and ends at the end of the day+before the later one.+Its return is the ratio of the investment\(aqs values at those two+moments.+For example, with cash flows on March 1 and March 10, the stretch is+March 2 to 9, and its return is (value at the end of March 9) / (value+at the end of March+.RS 2+.IP "1)" 3+\(bu .RS 2+.IP "1." 3+(March 10 itself is a day with cash flows, handled as below.)+.RE+.RE+.IP \(bu 2+A day with cash flows is split in two parts:+.RS 2+.IP "1." 3+The day\(aqs price changes: the return of the holdings carried over from+the previous day, from their value at the previous day\(aqs prices to+their value at this day\(aqs prices.+(This part is skipped if no prices changed.)+.IP "2." 3+The cash flows, as if all of the day\(aqs trades were made at the+day\(aqs closing prices.+Its return is (value at the end of the day \- withdrawals) / (value+after part 1 + deposits) \- 1, with withdrawals negative.+That is, the day\(aqs deposits count as invested during this part, as if+made at its start, and its withdrawals count as still invested during+it, as if made at its end.+So any difference between the prices you traded at and the closing+prices shows up in this part\(aqs return.+.RE+.IP \(bu 2+Times when nothing is invested earn nothing.+That includes a day on which something arrives in an empty investment+only as profit and loss (eg a stock grant, booked to an account matched+by \f[CR]\-\-pnl\f[R]): there is nothing to compute a return on, so that+day\(aqs return is 0%.+.IP \(bu 2+A holding which has no market price is valued at the price of the+investment\(aqs latest purchase or sale of it, on or before that day (as+\f[CR]\-\-infer\-market\-prices\f[R] would do, but only from the+investment\(aqs own transactions, and only while no market price is+known).+If there are several on a day, the last one recorded is used.+Like any price, it applies to the whole holding on that day, including+what was held before the trade, so a trade at a new price can show up in+\f[CR]\-\-cashflow\f[R] output as a \(dqprices\(dq row, before its cash+flows.+And a trade recorded at zero cost (eg a gift, recorded with+\f[CR]\(at $0\f[R]) gives a price of 0, so such a holding is worth+nothing until a market price is known; add a P directive for it.+.PP+All these returns are then multiplied together (geometrically chained)+to give the TWR for the full period.+In multi\-period reports, each period begins with the value the previous+one ended with, so the periods\(aq returns chain to the total.+.PP+Use \f[CR]\-\-value=then\f[R] for TWR, so that each day is valued with+the prices of that day.+With \f[CR]\-\-value=end\f[R], \f[CR]\-\-value=now\f[R] or+\f[CR]\-\-value=DATE\f[R], all the values in a period use the same+prices, so its TWR only reflects recorded profit and loss and the+differences between the prices you traded at and those prices.+With \f[CR]\-\-value=end\f[R], each period is also valued with its own+end\(aqs prices, so the periods\(aq returns don\(aqt chain to the total.+.PP+TWR can only be as good as the values your journal gives for each day.+If you record changes in value only occasionally (with+\f[CR]\-\-pnl\f[R] transactions, or with sparse price directives), the+growth since the previous record is attributed to the day you record it,+and so is counted on whatever was invested on that day.+If you made a large deposit or withdrawal in between, that can make TWR+quite different from what it would be if the growth had been spread out.+So record a valuation around large deposits and withdrawals+(professional performance standards require this too), or use price+directives, or \f[CR]\-\-infer\-market\-prices\f[R] if your transactions+record their prices.+.PP+\f[B]In short:\f[R] TWR tells you how good the investment was; IRR tells+you how good your experience of the investment was.+.SS Checking the results+\f[CR]\-\-cashflow\f[R] shows everything that IRR and TWR are computed+from, so that you can check them against your journal, against other+hledger reports, or in a spreadsheet:+.IP \(bu 2+\f[B]IRR cash flows\f[R]: one row per cash flow, with the+transaction\(aqs description, the cost of its investment postings, and+its profit or loss, between the investment\(aqs value at the start and+its value at the end (dated the day after the period\(aqs last day,+since it is the value at the end of that day).+Amounts are from your point of view: what you put in is negative, what+you take out or still have is positive.+The dates and amounts can be given to Excel\(aqs \f[CR]=XIRR\f[R] as+they are.+.IP \(bu 2+\f[B]TWR returns\f[R]: one row for each stretch without cash flows, and+for each day with cash flows, a row for its price changes (if any) and a+row for its cash flows.+Each row\(aqs Value (begin) is the previous row\(aqs Value (end), and+each row\(aqs return is+.RS 2+.PP+(Value (end) \- Withdrawals) / (Value (begin) + Deposits) \- 1+.PP+where withdrawals are negative.+The Cumulative column chains the returns by multiplication: each+row\(aqs (1 + Cumulative) is the previous row\(aqs (1 + Cumulative)+times (1 + Return).+Its last row is the period\(aqs TWR.+.RE+.PP+The values can be checked with \f[CR]hledger balance\f[R]: the value at+the end of a day D is the investment\(aqs historical balance at the end+of that day, valued then.+For example, if you ran \f[CR]roi \-\-value=then,$\f[R], check the value+at the end of day D with:+.IP+.EX+$ hledger balance \-\-historical \-\-value=end,$ \-e D+1 INVESTMENTQUERY+.EE+.PP+(where \f[CR]D+1\f[R] is the day after D; \f[CR]\-\-value=end\f[R]+values at the end of the report period, which is day D).+Holdings which have no market price are the exception, as \f[CR]roi\f[R]+values them at the price of their latest purchase or sale.+.PP+\f[B]When each matters\f[R]+.PP+Use IRR when you want to know your actual personal return \- what you+earned on your money, accounting for when you chose to move it.+It is the right measure when evaluating your own deposit and withdrawal+timing decisions.+.PP+Use TWR when you want to evaluate the investment vehicle itself,+independent of your deposit timing.+It is the right measure when comparing two funds or strategies, or when+asking whether you would have been better off elsewhere.+TWR is the standard that professional investment managers use to report+fund performance, precisely because it removes the distortion caused by+investor cash flows.+.PP+References:+.IP \(bu 2+Explanation of rate of return+.IP \(bu 2+Explanation of IRR+.IP \(bu 2+Explanation of TWR+.IP \(bu 2+IRR vs TWR+.IP \(bu 2+Examples of computing IRR and TWR and discussion of the limitations of+both metrics+.SS stats+Show journal and performance statistics.+.IP+.EX+Flags:+ \-q \-\-oneline show a single line of output+ \-v \-\-verbose show more detailed output+ \-o \-\-output\-file=FILE write output to FILE.+.EE+.PP+The stats command shows summary information for the whole journal, or a+matched part of it.+With a reporting interval, it shows a report for each report period.+.PP+It also shows some performance statistics:+.IP \(bu 2+how long the program ran for+.IP \(bu 2+the number of transactions processed per second+.IP \(bu 2+the peak live memory in use by the program to do its work+.IP \(bu 2+the peak allocated memory as seen by the program+.PP+By default, the output is reasonably discreet; it reveals the main file+name, your activity level, and the speed of your machine.+.PP+With \f[CR]\-v/\-\-verbose\f[R], more details are shown: the full paths+of all files, and the names of the commodities you work with.+.PP+With \f[CR]\-q/\-\-oneline\f[R], only one line of output is shown, in a+machine\-friendly tab\-separated format: the program version, the main+journal file name, and the performance stats,+.PP+The run time of \f[CR]stats\f[R] is similar to that of a balance report.+.PP+Example:+.IP+.EX+$ hledger stats \-f examples/1ktxns\-1kaccts.journal +Main file : .../1ktxns\-1kaccts.journal+Included files : 0+Txns span : 2000\-01\-01 to 2002\-09\-27 (1000 days)+Last txn : 2002\-09\-26 (7827 days ago)+Txns : 1000 (1.0 per day)+Txns last 30 days : 0 (0.0 per day)+Txns last 7 days : 0 (0.0 per day)+Payees/descriptions : 1000+Accounts : 1000 (depth 10)+Commodities : 26+Base currency : B+Market prices : 1000+Runtime stats : 0.12 s elapsed, 8266 txns/s, 4 MB live, 16 MB alloc+.EE+.IP+.EX+$ hledger stats \-q \-f examples/10ktxns\-1kaccts.journal+1.50.99\-g0835a2485\-20251119, mac\-aarch64 10ktxns\-1kaccts.journal 0.66 s elapsed 15244 txns/s 28 MB live 86 MB alloc+.EE+.PP+This command supports the \-o/\-\-output\-file option (but not+\-O/\-\-output\-format).+.SS tags+List the tag names used or declared in the journal, or their values.+.IP+.EX+Flags:+ \-\-used list tags used+ \-\-declared list tags declared+ \-\-undeclared list tags used but not declared+ \-\-unused list tags declared but not used+ \-\-find list the first tag whose name is matched by the+ first argument (a case\-insensitive infix regexp)+ \-\-values list tag values instead of tag names+ \-\-parsed show them in the order they were parsed (mostly),+ including duplicates+ \-\-directives show tag names as tag directives, for use in+ journals+.EE+.PP+This command lists tag names \- all of them by default, or just the ones+which have been used on transactions/postings/accounts, or declared with+\f[CR]tag\f[R] directives, or used but not declared, or declared but not+used, or just the first one matched by a pattern (with+\f[CR]\-\-find\f[R], returning a non\-zero exit code if it fails).+.PP+Note this command\(aqs non\-standard first argument: it is a+case\-insensitive infix regular expression for matching tag names, which+limits the tags shown.+Any additional arguments are standard query arguments, which limit the+transactions, postings, or accounts providing tags.+.PP+With \f[CR]\-\-values\f[R], the tags\(aq unique non\-empty values are+listed instead.+.PP+With \f[CR]\-E\f[R]/\f[CR]\-\-empty\f[R], blank/empty values are also+shown.+.PP+With \f[CR]\-\-parsed\f[R], tags or values are shown in the order they+were parsed, with duplicates included.+(Except, tags from account declarations are always shown first.)+.PP+With \f[CR]\-\-directives\f[R], tag names are shown as valid tag+directives, which could be pasted into a journal file.+.PP+Remember that accounts also acquire tags from their parents; postings+also acquire tags from their account and transaction; and transactions+also acquire tags from their postings.+.PP+Examples:+.IP+.EX+$ hledger tags+broker+receipt+trip+.EE+.IP+.EX+$ hledger tags \-\-values+acme+paris+.EE+.SS transactions+(tx)+.PP+List transactions, one per line.+.IP+.EX+Flags:+ \-m \-\-match=DESC fuzzy search for one recent transaction with+ description closest to DESC+.EE+.PP+This command shows each transaction\(aqs first line only (the date,+status, code, description, and any same\-line comment), giving a compact+overview of a journal, in the manner of \f[CR]git log \-\-oneline\f[R].+You can add a query to select a subset of transactions.+(To see full journal entries, use the \f[CR]print\f[R] command.)+.PP+Example:+.IP+.EX+$ hledger transactions \-f examples/sample.journal+2008\-01\-01 income+2008\-06\-01 gift+2008\-06\-02 save+2008\-06\-03 * eat & shop+2008\-12\-31 * pay off+.EE+.SH Maintenance commands+.SS setup+Check the status of the hledger installation.+.IP+.EX+Flags:+no command\-specific flags+.EE+.PP+\f[CR]setup\f[R] tests your hledger installation and prints a list of+results, sometimes with helpful hints.+This is a good first command to run after installing hledger.+Also after upgrading, or when something\(aqs not working, or just when+you want a reminder of where things are.+.PP+It makes one network request to detect the latest hledger release+version.+It\(aqs ok if this fails or times out.+It will use ANSI color by default, unless disabled by NO_COLOR or+\-\-color=n.+It does not use a pager or a config file.+.PP+It expects that the hledger version you are running is installed in your+PATH.+If not, it will stop until you have done that (to keep things simple).+.PP+Example:+.IP+.EX+$ hledger setup+Checking your setup (and contacting hledger.org to find out the current release):+hledger+ is running on macos 27.0 on aarch64+ is built with a supported compiler/RTS yes ghc 9.14.1, using threaded RTS+ is a native binary for this machine ? yes aarch64+ is a released version ? yes hledger 1.52.4, mac\-aarch64+ is up to date ? checking latest... yes latest is 1.52.4, 1.52.4 is installed+ is installed in PATH (this version) ? yes /Users/user/.local/bin/hledger+ has a system text encoding configured ? yes UTF\-8, data files must use this encoding+ has a user config file ? yes /Users/user/.hledger.conf+ has a local config file ? no + the config file is readable ? yes +terminal+ the TERM variable is defined ? yes xterm\-256color+ the terminal supports ANSI color ? yes + ...+journal+ the LEDGER_FILE variable is defined ? yes /Users/user/finance/main.journal+ a default journal file is readable ? yes /Users/user/finance/main.journal+ ...+.EE+.SS init+Create starter files for a new hledger setup, or add missing ones to an+existing setup.+.IP+.EX+Flags:+ \-\-layout=LAYOUT which file layout to write: simple, default, years+ (default: default)+ \-\-dry\-run just show the files that would be created+.EE+.PP+With no argument, or a directory argument, \f[CR]init\f[R] writes a set+of files in that directory (the current directory by default), creating+it if needed.+Which files depends on the layout chosen with \f[CR]\-\-layout\f[R].+Note, these are just to help you get started; you can always change the+file layout to suit your needs.+.PP+\f[B]simple\f[R]:+.PP+Just one file.+Good if you want simplicity and manual data entry.+.IP \(bu 2+\f[CR]main.journal\f[R] \- the journal file, with optional declarations+.PP+\f[B]default\f[R] (the default):+.PP+Declarations are kept separate; subdirectories and starter scripts for+data\-fetching are provided.+This is a good maintainable layout that hledger commands understand+well.+.IP \(bu 2+\f[CR]main.journal\f[R] \- the main journal file, with a few example+transactions+.IP \(bu 2+\f[CR]accounts.journal\f[R], \f[CR]commodities.journal\f[R],+\f[CR]payees.journal\f[R] \- declarations+.IP \(bu 2+\f[CR]data/\f[R] \- downloaded CSV files go here, with+\f[CR]data/getdata\f[R], a starter script for get+.IP \(bu 2+\f[CR]prices/\f[R] \- market prices go here, with+\f[CR]prices/getprices\f[R], a starter script for get+.IP \(bu 2+\f[CR]rules/\f[R] \- CSV rules files go here+.IP \(bu 2+an example CSV file and rules file+.PP+\f[B]years\f[R]:+.PP+Like default, but each year has its own journal file.+This gives you a choice of loading all years or one year at a time (see+close).+It makes life a little more complicated, but it is worthwhile if you+have enough data that a single file becomes slow on your machine; or if+you want to compartmentalise the data for other reasons.+.IP \(bu 2+\f[CR]YEAR.journal\f[R] (eg \f[CR]2026.journal\f[R]) \- this year\(aqs+journal, with a few example transactions.+.IP \(bu 2+\f[CR]all.journal\f[R] \- includes all the year journals, for+multi\-year reports+.IP \(bu 2+the same declaration files, directories and examples as default+.PP+With a journal file argument (a path ending with \f[CR].journal\f[R],+\f[CR].j\f[R], \f[CR].hledger\f[R] or \f[CR].ledger\f[R]), you\(aqll get+the simple layout, written to that file.+.PP+Files that already exist are never changed; they are skipped, with a+warning.+So you can run \f[CR]init\f[R] again to add missing files.+After writing the files, it suggests some next steps.+.PP+These and other file layouts can also be seen in the hledger repo\(aqs+examples/file\-layouts directory.+.PP+Examples:+.IP+.EX+$ hledger init \-\-dry\-run # show what would be created in the current directory+$ hledger init \(ti/finance # create a standard setup in \(ti/finance+$ hledger init \-\-layout years \(ti/finance # create a setup with a journal per year in \(ti/finance+$ hledger init 2026.journal # create a single journal file+.EE+.SS check+Check that your data is valid, using hledger\(aqs built\-in correctness+checks.+.IP+.EX+Flags:+no command\-specific flags+.EE+.PP+hledger provides a number of built\-in correctness checks to help+validate your data and prevent errors.+Some are run automatically, some when you enable \f[CR]\-\-strict\f[R]+mode; or you can run any of them on demand by providing them as+arguments to the \f[CR]check\f[R] command.+\f[CR]check\f[R] produces no output and a zero exit code if all is well.+Eg:+.IP+.EX+hledger check # run default checks+hledger check \-s # run default and strict checks+hledger check ordereddates payees # run default checks and two others+hledger check \(aqassert none daily type:A balance:<0\(aq # run default checks and a custom rule+.EE+.PP+If you are an Emacs user, you can also configure flycheck\-hledger to+run these checks, providing instant feedback as you edit the journal.+.PP+Here are the checks currently available.+They are generally checked in the order they are shown here, and only+the first failure will be reported.+.SS Default checks+These important checks are performed by default, by almost all hledger+commands:+.IP \(bu 2+\f[B]parseable\f[R] \- data files are in a supported format, with no+syntax errors and no invalid include directives.+This ensures that all files exist and are readable.+.IP \(bu 2+\f[B]autobalanced\f[R] \- all transactions are balanced, after+automatically inferring missing amounts and conversion rates and then+converting amounts to cost.+This ensures that each transaction\(aqs journal entry is well formed.+.IP \(bu 2+\f[B]assertions\f[R] \- all balance assertions and assert directives in+the journal are passing.+Balance assertions are a strong defense against errors, catching many+problems; assert directives check standing rules, like \(dqno asset+account is ever negative\(dq.+This check is on by default, but if it gets in your way, you can disable+it temporarily with \f[CR]\-I\f[R] or \f[CR]\-\-ignore\-assertions\f[R],+or as a default by adding that flag to your config file.+If you put it in your config file, you can override that with+\f[CR]\-s\f[R]/\f[CR]\-\-strict\f[R] or+\f[CR]hledger check assertions\f[R].+When a journal has both kinds of problem, lot errors are reported before+assertion failures, and balance assertion failures before assert+directive failures.+.IP \(bu 2+\f[B]lots\f[R] \- all lot entries are valid.+Checks lot posting classifications, lot movements, that an acquisition+writing both a cost basis and a transacted cost has them agree (a+mismatch would silently miscalculate gains), and that any user\-written+realised gain amount on a disposal matches the calculated gain.+This check can be disabled by \f[CR]\-I\f[R] or+\f[CR]\-\-ignore\-lots\f[R].+If you put it in your config file, you can override that with+\f[CR]\-s\f[R]/\f[CR]\-\-strict\f[R] or \f[CR]hledger check lots\f[R].+.SS Strict checks+When the \f[CR]\-s\f[R]/\f[CR]\-\-strict\f[R] flag is used (AKA strict+mode), all commands will perform the following additional checks.+These provide extra error\-catching power to help you keep your data+clean and correct:+.IP \(bu 2+\f[B]balanced\f[R] \- like \f[CR]autobalanced\f[R], but implicit+conversions between commodities are not allowed; all conversion+transactions must use cost notation or equity postings.+This prevents wrong conversions caused by typos.+.IP \(bu 2+\f[B]commodities\f[R] \- all commodity symbols used must be declared.+This guards against mistyping or omitting commodity symbols.+.IP \(bu 2+\f[B]accounts\f[R] \- all account names used must be declared.+This prevents the use of mis\-spelled or outdated account names.+(Except lot subaccounts, like \f[CR]:{2026\-01\-15, $50}\f[R], which are+automatically exempt; only their base account needs to be declared.+And the accounts of postings generated by hledger, such as equity+conversion, gain, and imbalance postings.)+.PP+Also, strict mode ensures that the \f[CR]assertions\f[R] and+\f[CR]lots\f[R] checks run (overriding their ignore flags).+.SS Other checks+These are not wanted by everyone, but can be run using the+\f[CR]check\f[R] command:+.IP \(bu 2+\f[B]tags\f[R] \- all tags used must be declared (tags on transactions,+postings, and account and commodity directives; except the special+tags).+This prevents mis\-spelled tag names.+Note hledger fairly often finds unintended tags in comments.+.IP \(bu 2+\f[B]payees\f[R] \- all payees used in transactions must be declared.+This will force you to declare any new payee name before using it.+Most people will probably find this a bit too strict.+.IP \(bu 2+\f[B]ordereddates\f[R] \- within each file, transactions must be ordered+by date.+(Forecast transactions are not checked.)+This is a simple and effective error catcher.+It\(aqs not included in strict mode, but you can add it by running+\f[CR]hledger check \-s ordereddates\f[R].+If enabled, this check is performed before balance assertions.+.IP \(bu 2+\f[B]recentassertions\f[R] \- all accounts with balance assertions must+have one that\(aqs within the 7 days before their latest posting.+This will encourage adding balance assertions for your active+asset/liability accounts, which in turn should encourage you to+reconcile regularly with those real world balances \- another strong+defense against errors.+(\f[CR]hledger close \-\-assert >>$LEDGER_FILE\f[R] is a convenient way+to add new balance assertions.+Later these become quite redundant, and you might choose to remove them+to reduce clutter.)+.IP \(bu 2+\f[B]uniqueleafnames\f[R] \- no two accounts may have the same last+account name part (eg the \f[CR]checking\f[R] in+\f[CR]assets:bank:checking\f[R]).+This ensures each account can be matched by a unique short name, easier+to remember and to type.+.SS Assert rules+You can also check custom rules, written like assert directives.+Give each one as a single quoted argument, written exactly as the+directive would be written in the journal.+Eg:+.IP+.EX+hledger check \(aqassert none daily type:A balance:<0\(aq+hledger check \(aqassert some monthly income:salary\(aq \(aqassert none assets:oldbank date:2025\-\(aq+.EE+.PP+This is a convenient way to try out a rule before adding it to the+journal, or to check rules you don\(aqt want to keep there.+Unlike assert directives, these rules check all of the data files read,+combined (not each file tree separately), and they are checked even with+\f[CR]\-I\f[R].+They are checked after any other checks requested.+(A plain \f[CR]assert\f[R] argument, with nothing after it, is short for+the \f[CR]assertions\f[R] check.)+.SS Custom checks+You can build your own custom checks with add\-on command scripts.+See also Cookbook > Scripting.+Here are some examples from hledger/bin/:+.IP \(bu 2+\f[B]hledger\-check\-tagfiles\f[R] \- all tag values containing+\f[CR]/\f[R] exist as file paths+.SS diff+Compare a particular account\(aqs transactions in two input files.+It shows any transactions to this account which are in one file but not+in the other.+.IP+.EX+Flags:+no command\-specific flags+.EE+.PP+More precisely: for each posting affecting this account in either file,+this command looks for a corresponding posting in the other file which+posts the same amount to the same account (ignoring date, description,+etc).+.PP+Since it compares postings, not transactions, this also works when+multiple bank transactions have been combined into a single journal+entry.+.PP+This command is useful eg if you have downloaded an account\(aqs+transactions from your bank (eg as CSV data): when hledger and your bank+disagree about the account balance, you can compare the bank data with+your journal to find out the cause.+.PP+Examples:+.IP+.EX+$ hledger diff \-f $LEDGER_FILE \-f bank.csv assets:bank:giro +These transactions are in the first file only:++2014/01/01 Opening Balances+ assets:bank:giro EUR ...+ ...+ equity:opening balances EUR \-...++These transactions are in the second file only:+.EE+.SH Data generation commands+.SS close+(equity)+.PP+Print several kinds of \(dqclosing\(dq and/or \(dqopening\(dq+transactions, useful eg when migrating balances to a new journal file,+retaining earnings into equity, consolidating balances, or viewing lot+costs.+Like \f[CR]print\f[R], it prints valid journal entries.+You can copy these into your journal file(s) when you are happy with how+they look.+.IP+.EX+Flags:+ \-\-clopen[=TAGVAL] show closing and opening balances transactions,+ for AL accounts by default+ \-\-close[=TAGVAL] show just a closing balances transaction+ \-\-open[=TAGVAL] show just an opening balances transaction+ \-\-assert[=TAGVAL] show a balance assertions transaction+ \-\-assign[=TAGVAL] show a balance assignments transaction+ \-\-retain[=TAGVAL] show a retain earnings transaction, for RX+ accounts by default+ \-x \-\-explicit show all amounts explicitly+ \-\-show\-costs show amounts with different costs separately+ \-\-interleaved show source and destination postings together+ \-\-assertion\-type=TYPE =, ==, =* or ==*+ \-\-close\-desc=DESC set closing transaction\(aqs description+ \-\-close\-acct=ACCT set closing transaction\(aqs destination account+ \-\-open\-desc=DESC set opening transaction\(aqs description+ \-\-open\-acct=ACCT set opening transaction\(aqs source account+ \-\-round=TYPE how much rounding or padding should be done when+ displaying amounts ?+ none \- show original decimal digits,+ as in journal (default)+ soft \- just add or remove decimal zeros+ to match precision+ hard \- round posting amounts to precision+ (can unbalance transactions)+ all \- also round cost amounts to precision+ (can unbalance transactions)+ \-\-layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 \- right\-align amounts, as in hledger 1+ COL \- align decimal marks at column COL+ (default: 53)+.EE+.PP+\f[CR]close\f[R] has six modes, selected by choosing one of the mode+flags: \f[CR]\-\-clopen\f[R], \f[CR]\-\-close\f[R] (default),+\f[CR]\-\-open\f[R], \f[CR]\-\-assert\f[R], \f[CR]\-\-assign\f[R], or+\f[CR]\-\-retain\f[R].+They are all doing the same kind of operation, but with different+defaults for different situations.+.PP+The journal entries generated by \f[CR]close\f[R] will have a+\f[CR]clopen:\f[R] tag, which is helpful when you want to exclude them+from reports.+If the main journal file name contains a number, the tag\(aqs value will+be that base file name with the number incremented.+Eg if the journal file is 2025.journal, the tag will be+\f[CR]clopen:2026\f[R].+Or you can set the tag value by providing an argument to the mode flag.+Eg \f[CR]\-\-close=foo\f[R] or \f[CR]\-\-clopen=2025\-main\f[R].+.SS close \-\-clopen+This is useful if migrating balances to a new journal file at the start+of a new year.+It prints a \(dqclosing balances\(dq transaction that zeroes out account+balances (Asset and Liability accounts, by default), and an opposite+\(dqopening balances\(dq transaction that restores them again.+Typically, you would run+.IP+.EX+hledger close \-\-clopen \-e NEWYEAR >> $LEDGER_FILE+.EE+.PP+and then move the opening transaction from the old file to the new file+(and probably also update your LEDGER_FILE environment variable).+.PP+Why might you do this ?+If your reports are fast, you may not need it.+But at some point you will probably want to partition your data by time,+for performance or data integrity or regulatory reasons.+A new file or set of files per year is common.+Then, having each file/fileset \(dqbookended\(dq with opening and+closing balance transactions will allow you to freely pick and choose+which files to read \- just the current year, any past year, any+sequence of years, or all of them \- while showing correct account+balances in each case.+The earliest opening balances transaction sets correct starting+balances, and any later closing/opening pairs will harmlessly cancel+each other out.+.PP+The balances will be transferred to and from+\f[CR]equity:opening/closing balances\f[R] by default.+You can override this by using \f[CR]\-\-close\-acct\f[R] and/or+\f[CR]\-\-open\-acct\f[R].+.PP+You can select a different set of accounts to close/open by providing an+account query.+Eg to add Equity accounts, provide arguments like+\f[CR]assets liabilities equity\f[R] or \f[CR]type:ALE\f[R].+When migrating to a new file, you\(aqll usually want to bring along the+AL or ALE accounts, but not the RX accounts (Revenue, Expense).+.PP+Assertions will be added indicating and checking the new balances of the+closed/opened accounts.+.SS close \-\-close+This prints just the closing balances transaction of+\f[CR]\-\-clopen\f[R].+It is the default if you don\(aqt specify a mode.+.PP+More customisation options are described below.+Among other things, you can use \f[CR]close \-\-close\f[R] to generate a+transaction moving the balances from any set of accounts, to a different+account.+(If you need to move just a portion of the balance, see hledger\-move.)+.SS close \-\-open+This prints just the opening balances transaction of+\f[CR]\-\-clopen\f[R].+(It is similar to Ledger\(aqs equity command.)+.SS close \-\-assert+This prints a transaction that asserts the account balances as they are+on the end date (and adds an \f[CR]assert:\f[R] tag).+It could be useful as documention and to guard against changes.+.SS close \-\-assign+This prints a transaction that assigns the account balances as they are+on the end date (and adds an \(dqassign:\(dq tag).+Unlike balance assertions, assignments will post changes to balances as+needed to reach the specified amounts.+.PP+This is another way to set starting balances when migrating to a new+file, and it will set them correctly even in the presence of earlier+files which do not have a closing balances transaction.+However, it can hide errors, and disturb the accounting equation, so+\f[CR]\-\-clopen\f[R] is usually recommended.+.SS close \-\-retain+This is like \f[CR]\-\-close\f[R], but it closes Revenue and Expense+account balances by default.+They will be transferred to \f[CR]equity:retained earnings\f[R], or+another account specified with \f[CR]\-\-close\-acct\f[R].+.PP+Revenues and expenses correspond to changes in equity.+They are categorised separately for reporting purposes, but+traditionally at the end of each accounting period, businesses+consolidate them into equity, This is called \(dqretaining earnings\(dq,+or \(dqclosing the books\(dq.+.PP+In personal accounting, there\(aqs not much reason to do this, and most+people don\(aqt.+(One reason to do it is to help the \f[CR]balancesheetequity\f[R] report+show a zero total, demonstrating that the accounting equation (A\-L=E)+is satisfied.)+.SS close customisation+In all modes, the following things can be overridden:+.IP \(bu 2+the accounts to be closed/opened, with account query arguments+.IP \(bu 2+the closing/opening dates, with \f[CR]\-e OPENDATE\f[R]+.IP \(bu 2+the balancing account, with \f[CR]\-\-close\-acct=ACCT\f[R] and/or+\f[CR]\-\-open\-acct=ACCT\f[R]+.IP \(bu 2+the transaction descriptions, with \f[CR]\-\-close\-desc=DESC\f[R] and+\f[CR]\-\-open\-desc=DESC\f[R]+.IP \(bu 2+the transactions\(aq \f[CR]clopen\f[R] tag value, with a+\f[CR]TAGVAL\f[R] argument for the mode flag (see above).+.PP+By default, the closing date is yesterday, or the journal\(aqs end date,+whichever is later; and the opening date is always one day after the+closing date.+You can change these by specifying a report end date; the closing date+will be the last day of the report period.+Eg \f[CR]\-e 2024\f[R] means \(dqclose on 2023\-12\-31, open on+2024\-01\-01\(dq.+.PP+With \f[CR]\-\-x/\-\-explicit\f[R], the balancing amount will be shown+explicitly, and if it involves multiple commodities, a separate posting+will be generated for each of them (similar to \f[CR]print \-x\f[R]).+.PP+With \f[CR]\-\-interleaved\f[R], each individual transfer is shown with+source and destination postings next to each other (perhaps useful for+troubleshooting).+.PP+With \f[CR]\-\-show\-costs\f[R], balances\(aq costs are also shown, with+different costs kept separate.+This may generate very large journal entries, if you have many currency+conversions or investment transactions.+\f[CR]close \-\-show\-costs\f[R] is currently the best way to view+investment lots with hledger.+(To move or dispose of lots, see the more capable+\f[CR]hledger\-move\f[R] script.)+With \f[CR]\-\-lots\f[R], lot subaccount balances are always shown+without costs, even under \f[CR]\-\-show\-costs\f[R]: their cost+information is carried by the lot name itself, and transacted costs on+lot postings would prevent the output from being read back.+For lots using the AVERAGE or AVERAGEALL cost basis method, whose lot+names normally leave out the cost, the pool\(aqs average cost as of the+closing date is added to each lot name (eg+\f[CR]{2026\-01\-15, $55}\f[R]), so that the output can be read back, eg+to start a new file.+A non\-terminating average is written with up to 8 decimal places, so+the re\-opened lots\(aq total cost basis may differ from the original by+a tiny amount.+.SS close and balance assertions+\f[CR]close\f[R] adds balance assertions verifying that the accounts+have been reset to zero in a closing transaction or restored to their+previous balances in an opening transaction.+These provide useful error checking, but you can ignore them temporarily+with \f[CR]\-I\f[R], or remove them if you prefer.+.PP+With \f[CR]\-\-lots\f[R], balance assertions are not generated for the+lot subaccount postings in closing transactions (assertions on lot+postings get confusing, because they apply to the parent account).+.PP+Single\-commodity, subaccount\-exclusive balance assertions+(\f[CR]=\f[R]) are generated by default.+This can be changed with \f[CR]\-\-assertion\-type=\(aq==*\(aq\f[R]+(eg).+.PP+When running \f[CR]close\f[R] you should probably avoid using+\f[CR]\-C\f[R], \f[CR]\-R\f[R], \f[CR]status:\f[R] (filtering by status+or realness) or \f[CR]\-\-auto\f[R] (generating postings), since the+generated balance assertions would then require these.+.PP+Transactions with multiple dates (eg posting dates) spanning the file+boundary also can disrupt the balance assertions:+.IP+.EX+2023\-12\-30 a purchase made in december, cleared in january+ expenses:food 5+ assets:bank:checking \-5 ; date: 2023\-01\-02+.EE+.PP+To solve this you can transfer the money to and from a temporary+account, splitting the multi\-day transaction into two single\-day+transactions:+.IP+.EX+; in 2022.journal:+2022\-12\-30 a purchase made in december, cleared in january+ expenses:food 5+ equity:pending \-5++; in 2023.journal:+2023\-01\-02 last year\(aqs transaction cleared+ equity:pending 5 = 0+ assets:bank:checking \-5+.EE+.SS close examples+.SS Retain earnings+Record 2022\(aqs revenues/expenses as retained earnings on 2022\-12\-31,+appending the generated transaction to the journal:+.IP+.EX+$ hledger close \-\-retain \-f 2022.journal \-p 2022 >> 2022.journal+.EE+.PP+After this, to see 2022\(aqs revenues and expenses you must exclude the+retain earnings transaction:+.IP+.EX+$ hledger \-f 2022.journal is not:desc:\(aqretain earnings\(aq+.EE+.SS Migrate balances to a new file+Close assets/liabilities on 2022\-12\-31 and re\-open them on+2023\-01\-01:+.IP+.EX+$ hledger close \-\-clopen \-f 2022.journal \-p 2022+# copy/paste the closing transaction to the end of 2022.journal+# copy/paste the opening transaction to the start of 2023.journal+.EE+.PP+After this, to see 2022\(aqs end\-of\-year balances you must exclude the+closing balances transaction:+.IP+.EX+$ hledger \-f 2022.journal bs not:desc:\(aqclosing balances\(aq+.EE+.PP+For more flexibility, it helps to tag closing and opening transactions+with eg \f[CR]clopen:NEWYEAR\f[R], then you can ensure correct balances+by excluding all opening/closing transactions except the first, like so:+.IP+.EX+$ hledger bs \-Y \-f 2021.j \-f 2022.j \-f 2023.j expr:\(aqtag:clopen=2021 or not tag:clopen\(aq+$ hledger bs \-Y \-f 2021.j \-f 2022.j expr:\(aqtag:clopen=2021 or not tag:clopen\(aq+$ hledger bs \-Y \-f 2022.j \-f 2023.j expr:\(aqtag:clopen=2022 or not tag:clopen\(aq+$ hledger bs \-Y \-f 2021.j expr:\(aqtag:clopen=2021 or not tag:clopen\(aq+$ hledger bs \-Y \-f 2022.j expr:\(aqtag:clopen=2022 or not tag:clopen\(aq+$ hledger bs \-Y \-f 2023.j # unclosed file, no query needed+.EE+.SS More detailed close examples+See examples/multi\-year.+.SS rewrite+Print all transactions, adding auto postings to some of them.+For now the only rewrite available is adding new postings, like print+\-\-auto.+.IP+.EX+Flags:+ \-\-add\-posting=\(aqACCT AMTEXPR\(aq add a posting to ACCT, which may be+ parenthesised. AMTEXPR is either a literal+ amount, or *N which means the transaction\(aqs+ first matched amount multiplied by N (a+ decimal number). Two spaces separate ACCT+ and AMTEXPR.+ \-\-diff generate diff suitable as an input for+ patch tool+ \-\-verbose\-tags add tags indicating generated/modified+ data+ \-\-layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 \- right\-align amounts, as in+ hledger 1+ COL \- align decimal marks at column+ COL (default: 53)+.EE+.PP+This is a start at a generic rewriter of transaction entries.+It reads the default journal and prints the transactions, like print,+but adds one or more specified postings to any transactions matching+QUERY.+The posting amounts can be fixed, or a multiplier of the existing+transaction\(aqs first posting amount.+.PP+Examples:+.IP+.EX+$ hledger\-rewrite.hs \(haincome \-\-add\-posting \(aq(liabilities:tax) *.33 ; income tax\(aq \-\-add\-posting \(aq(reserve:gifts) $100\(aq+$ hledger\-rewrite.hs expenses:gifts \-\-add\-posting \(aq(reserve:gifts) *\-1\(dq\(aq+$ hledger\-rewrite.hs \-f rewrites.hledger+.EE+.PP+rewrites.hledger may consist of entries like:+.IP+.EX+= \(haincome amt:<0 date:2017+ (liabilities:tax) *0.33 ; tax on income+ (reserve:grocery) *0.25 ; reserve 25% for grocery+ (reserve:) *0.25 ; reserve 25% for grocery+.EE+.PP+Note the single quotes to protect the dollar sign from bash, and the two+spaces between account and amount.+.PP+More:+.IP+.EX+$ hledger rewrite [QUERY] \-\-add\-posting \(dqACCT AMTEXPR\(dq ...+$ hledger rewrite \(haincome \-\-add\-posting \(aq(liabilities:tax) *.33\(aq+$ hledger rewrite expenses:gifts \-\-add\-posting \(aq(budget:gifts) *\-1\(dq\(aq+$ hledger rewrite \(haincome \-\-add\-posting \(aq(budget:foreign currency) *0.25 JPY; diversify\(aq+.EE+.PP+Argument for \f[CR]\-\-add\-posting\f[R] option is a usual posting of+transaction with an exception for amount specification.+More precisely, you can use \f[CR]\(aq*\(aq\f[R] (star symbol) before+the amount to indicate that that this is a factor for an amount of+original matched posting.+If the amount includes a commodity name, the new posting amount will be+in the new commodity; otherwise, it will be in the matched posting+amount\(aqs commodity.+.SS Re\-write rules in a file+During the run this tool will execute so called \(dqAutomated+Transactions\(dq found in any journal it process.+I.e instead of specifying this operations in command line you can put+them in a journal file.+.IP+.EX+$ rewrite\-rules.journal+.EE+.PP+Make contents look like this:+.IP+.EX+= \(haincome+ (liabilities:tax) *.33++= expenses:gifts+ budget:gifts *\-1+ assets:budget *1+.EE+.PP+Note that \f[CR]\(aq=\(aq\f[R] (equality symbol) that is used instead of+date in transactions you usually write.+It indicates the query by which you want to match the posting to add new+ones.+.IP+.EX+$ hledger rewrite \-f input.journal \-f rewrite\-rules.journal > rewritten\-tidy\-output.journal+.EE+.PP+This is something similar to the commands pipeline:+.IP+.EX+$ hledger rewrite \-f input.journal \(aq\(haincome\(aq \-\-add\-posting \(aq(liabilities:tax) *.33\(aq \(rs+ | hledger rewrite \-f \- expenses:gifts \-\-add\-posting \(aqbudget:gifts *\-1\(aq \(rs+ \-\-add\-posting \(aqassets:budget *1\(aq \(rs+ > rewritten\-tidy\-output.journal+.EE+.PP+It is important to understand that relative order of such entries in+journal is important.+You can re\-use result of previously added postings.+.SS Diff output format+To use this tool for batch modification of your journal files you may+find useful output in form of unified diff.+.IP+.EX+$ hledger rewrite \-\-diff \-f examples/sample.journal \(aq\(haincome\(aq \-\-add\-posting \(aq(liabilities:tax) *.33\(aq+.EE+.PP+Output might look like:+.IP+.EX+\-\-\- /tmp/examples/sample.journal++++ /tmp/examples/sample.journal+\(at\(at \-28,13 +28,15 \(at\(at+ ; declare commodities:+ ; commodity $+ +\-2008/01/01 income+\- assets:bank:checking $1++2008\-01\-01 income++ assets:bank:checking $1+ income:salary++ (liabilities:tax) $0+ +\-2008/06/01 gift+\- assets:bank:checking $1++2008\-06\-01 gift++ assets:bank:checking $1+ income:gifts++ (liabilities:tax) $0+ + 2008/06/02 save+ assets:bank:saving $1+.EE+.PP+If you\(aqll pass this through \f[CR]patch\f[R] tool you\(aqll get+transactions containing the posting that matches your query be updated.+Note that multiple files might be update according to list of input+files specified via \f[CR]\-\-file\f[R] options and \f[CR]include\f[R]+directives inside of these files.+.PP+Changed transactions are re\-rendered in \f[CR]print\f[R]\(aqs standard+format, so the diff shows any reformatting as well as the postings you+added: amounts are realigned, and dates are written with \f[CR]\-\f[R]+separators.+Transactions you didn\(aqt change are left exactly as they are.+\f[CR]\-\-layout\f[R] selects the amount alignment, so choosing one+which matches your journal will keep the diff small.+Here is the example above again, with \f[CR]\-\-layout=26\f[R] to match+this journal\(aqs own alignment:+.IP+.EX+\(at\(at \-28,13 +28,15 \(at\(at+ ; declare commodities:+ ; commodity $+ +\-2008/01/01 income++2008\-01\-01 income+ assets:bank:checking $1+ income:salary++ (liabilities:tax) $0+ +\-2008/06/01 gift++2008\-06\-01 gift+ assets:bank:checking $1+ income:gifts++ (liabilities:tax) $0+ + 2008/06/02 save+ assets:bank:saving $1+.EE+.PP+Only transactions which exist as journal entries in a file can be+patched this way.+Transactions read from other data formats, such as CSV or timeclock, and+transactions generated by a periodic transaction rule, have no journal+entry of their own; these are left out of the diff, and reported on+stderr.+To rewrite those, convert them to journal entries first, eg with+\f[CR]hledger print\f[R] or \f[CR]hledger import\f[R].+.PP+Be careful.+Whole transaction being re\-formatted in a style of output from+\f[CR]hledger print\f[R].+.PP+See also:+.PP+https://github.com/hledgerorg/hledger/issues/99+.SS rewrite vs. print \-\-auto+This command predates print \-\-auto, and currently does much the same+thing, but with these differences:+.IP \(bu 2+with multiple files, rewrite lets rules in any file affect all other+files.+print \-\-auto uses standard directive scoping; rules affect only child+files.+.IP \(bu 2+rewrite\(aqs query limits which transactions can be rewritten; all are+printed.+print \-\-auto\(aqs query limits which transactions are printed.+.IP \(bu 2+rewrite applies rules specified on command line or in the journal.+print \-\-auto applies rules specified in the journal.+.PP+.SH PART 3: DATA FORMATS+.SH Journal+hledger\(aqs usual data source is a plain text file containing journal+entries in hledger \f[CR]journal\f[R] format.+If you\(aqre looking for a quick reference, jump ahead to the journal+cheatsheet.+.PP+This file represents an accounting General Journal.+The \f[CR].journal\f[R] file extension is most often used, though not+strictly required.+The journal file contains a number of transaction entries, each+describing a transfer of money (or any commodity) between two or more+named accounts, in a simple format readable by both hledger and humans.+.PP+hledger\(aqs journal format is compatible with most of Ledger\(aqs+journal format, but not all of it.+The differences and interoperation tips are described at hledger and+Ledger.+With some care, and by avoiding incompatible features, you can keep your+hledger journal readable by Ledger and vice versa.+This can useful eg for comparing the behaviour of one app against the+other.+.PP+You can use hledger without learning any more about this file; just use+the add or web or import commands to create and update it.+.PP+Many users, though, edit the journal file with a text editor, and track+changes with a version control system such as git.+Editor add\-ons such as ledger\-mode or hledger\-mode for Emacs,+vim\-ledger for Vim, and hledger\-vscode for Visual Studio Code, make+this easier, adding colour, formatting, tab completion, and useful+commands.+See Editors at hledger.org for the full list.+.PP+A hledger journal file can contain three kinds of thing: comment lines,+transactions, and/or directives (including periodic transaction rules+and auto posting rules).+Understanding the journal file format will also give you a good+understanding of hledger\(aqs data model.+Here\(aqs a quick cheatsheet/overview, followed by detailed descriptions+of each part.+.SS Journal cheatsheet+.IP+.EX+# Here is the main syntax of hledger\(aqs journal format+# (omitting extra Ledger compatibility syntax).++###############################################################################++# 1. These are comment lines, for notes or temporarily disabling things.+; They begin with # or ;++comment+Or, lines can be enclosed within \(dqcomment\(dq / \(dqend comment\(dq.+This is a block of +commented lines.+end comment++# Some journal entries can have semicolon comments at end of line ; like this+# Some of them require 2 or more spaces before the semicolon.++###############################################################################++# 2. Directives customise processing or output in some way.+# You don\(aqt need any directives to get started.+# But they can add more error checking, or change how things are displayed.+# They begin with a word, letter, or symbol. +# They are most often placed at the top, before transactions.++account assets ; Declare valid account names and display order.+account assets:savings ; A subaccount. This one represents a bank account.+account assets:checking ; Another. Note, 2+ spaces after the account name.+account assets:receivable ; Accounting type is inferred from english names,+account passifs ; or declared with a \(dqtype\(dq tag, type:L+account expenses ; type:X+ ; A follow\-on comment line, indented.+account expenses:rent ; Expense and revenue categories are also accounts.+ ; Subaccounts inherit their parent\(aqs type.++commodity $0.00 ; Declare valid commodities and their display styles.+commodity 1.000,00 EUR++decimal\-mark . ; The decimal mark used in this file (if ambiguous).++payee Whole Foods ; Declare a valid payee name.++tag trip ; Declare a valid tag name.++P 2024\-03\-01 AAPL $179 ; Declare a market price for AAPL in $ on this date.++include other.journal ; Include another journal file here.++# Declare a recurring \(dqperiodic transaction\(dq, for budget/forecast reports+\(ti monthly set budget goals ; <\- Note, 2+ spaces before the description.+ (expenses:rent) $1000+ (expenses:food) $500++# Declare an auto posting rule, to modify existing transactions in reports+= revenues:consulting+ liabilities:tax:2024:us *0.25 ; Add a tax liability & expense+ expenses:tax:2024:us *\-0.25 ; for 25% of the revenue.++###############################################################################++# 3. Transactions are what it\(aqs all about.+# They are dated events, usually movements of money between 2 or more accounts.+# They begin with a numeric date.+# Here is their basic shape:+#+# DATE DESCRIPTION ; The transaction\(aqs date and optional description.+# ACCOUNT1 AMOUNT ; A posting of an amount to/from this account, indented.+# ACCOUNT2 AMOUNT ; A second posting, balancing the first.+# ... ; More if needed. Amounts must sum to zero.+# ; Note, 2+ spaces between account names and amounts.++2024\-01\-01 opening balances ; At the start, declare pre\-existing balances this way.+ assets:savings $10000 ; Account names can be anything. lower case is easy to type.+ assets:checking $1000 ; assets, liabilities, equity, revenues, expenses are common.+ liabilities:credit card $\-500 ; liabilities, equity, revenues balances are usually negative.+ equity:start ; One amount can be left blank. $\-10500 is inferred here.+ ; Some of these accounts we didn\(aqt declare above,+ ; so \-s/\-\-strict would complain.++2024\-01\-03 ! (12345) pay rent+ ; Additional transaction comment lines, indented.+ ; There can be a ! or * after the date meaning \(dqpending\(dq or \(dqcleared\(dq.+ ; There can be a parenthesised (code) after the date/status.+ ; Amounts\(aq sign shows direction of flow.+ assets:checking $\-500 ; Minus means removed from this account (credit).+ expenses:rent $500 ; Plus means added to this account (debit).++; Keeping transactions in date order is optional (but helps error checking).++2024\-01\-02 Gringott\(aqs Bank | withdrawal ; Description can be PAYEE | NOTE+ assets:bank:gold \-10 gold+ assets:pouch 10 gold++2024\-01\-02 shopping+ expenses:clothing 1 gold+ expenses:wands 5 gold+ assets:pouch \-6 gold++2024\-01\-02 receive gift+ revenues:gifts \-3 \(dqChocolate Frogs\(dq ; Complex commodity symbols+ assets:pouch 3 \(dqChocolate Frogs\(dq ; must be in double quotes.++2024\-01\-15 buy some shares, in two lots ; Cost can be noted.+ assets:investments:2024\-01\-15 2.0 AAAA \(at $1.50 ; \(at means per\-unit cost+ assets:investments:2024\-01\-15\-02 3.0 AAAA \(at\(at $4 ; \(at\(at means total cost+ ; \(ha Per\-lot subaccounts are sometimes useful.+ assets:checking $\-7++2024\-01\-15 assert some account balances on this date+ ; Balances can be asserted in any transaction, with =, for extra error checking.+ ; Assertion txns like this one can be made with hledger close \-\-assert \-\-show\-costs+ ;+ assets:savings $0 = $10000+ assets:checking $0 = $493+ assets:bank:gold 0 gold = \-10 gold+ assets:pouch 0 gold = 4 gold+ assets:pouch 0 \(dqChocolate Frogs\(dq = 3 \(dqChocolate Frogs\(dq+ assets:investments:2024\-01\-15 0.0 AAAA = 2.0 AAAA \(at $1.50+ assets:investments:2024\-01\-15\-02 0.0 AAAA = 3.0 AAAA \(at\(at $4+ liabilities:credit card $0 = $\-500++2024\-02\-01 note some event, or a transaction not yet fully entered, on this date+ ; Postings are not required.++# Consistent YYYY\-MM\-DD date format is recommended,+# but you can use . or / and omit leading zeros if you prefer.+2024.01.01+2024/1/1+.EE+.SS Comments+Lines in the journal will be ignored if they begin with a hash+(\f[CR]#\f[R]) or a semicolon (\f[CR];\f[R]).+(See also Other syntax.)+hledger will also ignore regions beginning with a \f[CR]comment\f[R]+line, and ending with an \f[CR]end comment\f[R] line or file end.+Here\(aqs a suggestion for choosing between them:+.IP \(bu 2+\f[CR]#\f[R] for top\-level notes+.IP \(bu 2+\f[CR];\f[R] for commenting out things temporarily+.IP \(bu 2+\f[CR]comment\f[R] for quickly commenting large regions (remember+it\(aqs there, or you might get confused)+.PP+Eg:+.IP+.EX+# a comment line+; another commentline+comment+A multi\-line comment block,+continuing until \(dqend comment\(dq directive+or the end of the current file.+end comment+.EE+.PP+Some hledger entries can have same\-line comments attached to them, from+; (semicolon) to end of line.+See Transaction comments, Posting comments, and Account comments below.+.PP+Comment lines immediately preceding a transaction (with no blank line in+between) are attached to that transaction, and are shown before it, as+written, in \f[CR]print\f[R] output.+.SS Transactions+Transactions are the main unit of information in a journal file.+They represent events, typically a movement of some quantity of+commodities between two or more named accounts.+.PP+Each transaction is recorded as a journal entry, beginning with a simple+date in column 0.+This can be followed by any of the following optional fields, separated+by spaces:+.IP \(bu 2+a status character (empty, \f[CR]!\f[R], or \f[CR]*\f[R])+.IP \(bu 2+a code (any short number or text, enclosed in parentheses)+.IP \(bu 2+a description (any remaining text until end of line or a semicolon)+.IP \(bu 2+a comment (any remaining text following a semicolon until end of line,+and any following indented lines beginning with a semicolon)+.IP \(bu 2+0 or more indented \f[I]posting\f[R] lines, describing what was+transferred and the accounts involved (indented comment lines are also+allowed, but not blank lines or non\-indented lines).+.PP+Here\(aqs a simple journal file containing one transaction:+.IP+.EX+2008/01/01 income+ assets:bank:checking $1+ income:salary $\-1+.EE+.SS Dates+.SS Simple dates+Dates in the journal file use \f[I]simple dates\f[R] format:+\f[CR]YYYY\-MM\-DD\f[R] or \f[CR]YYYY/MM/DD\f[R] or+\f[CR]YYYY.MM.DD\f[R], with leading zeros optional.+The year may be omitted, in which case it will be inferred from the+context: the current transaction, the default year set with a+\f[CR]Y\f[R] directive, or the current date when the command is run.+Some examples: \f[CR]2010\-01\-31\f[R], \f[CR]2010/01/31\f[R],+\f[CR]2010.1.31\f[R], \f[CR]1/31\f[R].+.PP+(On the command line and in the UIs, you can also use the more flexible+smart dates.)+.SS Posting dates+You can give individual postings a different date from their parent+transaction, by adding a posting comment containing a tag (see below)+like \f[CR]; date:DATE\f[R].+(There\(aqs also a Ledger\-compatible syntax, \f[CR]; [DATE]\f[R], which+can be convenient.)+.PP+This is probably the best way to control posting dates precisely.+Eg in this example the expense should appear in May reports, and the+deduction from checking should be reported on 6/1 for easy bank+reconciliation:+.IP+.EX+2015/5/30+ expenses:food $10 ; food purchased on saturday 5/30+ assets:checking ; bank cleared it on monday, date:6/1+.EE+.IP+.EX+$ hledger \-f t.j register food+2015\-05\-30 expenses:food $10 $10+.EE+.IP+.EX+$ hledger \-f t.j register checking+2015\-06\-01 assets:checking $\-10 $\-10+.EE+.PP+DATE should be a simple date; if the year is not specified it will use+the year of the transaction\(aqs date.+.PD 0+.P+.PD+A non\-empty \f[CR]date:\f[R] tag value must begin with a valid simple+date.+A \f[CR]date:\f[R] tag with an empty value is allowed, and sets no date.+(To disable a date tag temporarily, without removing the date, insert a+comma before the date.)+.SS Status+Transactions (or individual postings within a transaction) can have a+status mark, which is a single character before the transaction+description (or posting account name), separated from it by a space,+indicating one of three statuses:+.PP+.TS+tab(@);+l l.+T{+mark \ +T}@T{+status+T}+_+T{+\ +T}@T{+unmarked+T}+T{+\f[CR]!\f[R]+T}@T{+pending+T}+T{+\f[CR]*\f[R]+T}@T{+cleared+T}+.TE+.PP+When reporting, you can filter by status with the+\f[CR]\-U/\-\-unmarked\f[R], \f[CR]\-P/\-\-pending\f[R], and+\f[CR]\-C/\-\-cleared\f[R] flags (and you can combine these, eg+\f[CR]\-UP\f[R] to match all except cleared things).+Or you can use the \f[CR]status:\f[R], \f[CR]status:!\f[R], and+\f[CR]status:*\f[R] queries, or the U, P, C keys in hledger\-ui.+.PP+(Note: in Ledger the \(dqunmarked\(dq state is called \(dquncleared\(dq;+in hledger we renamed it to \(dqunmarked\(dq for semantic clarity.)+.PP+Status marks are optional, but can be helpful eg for reconciling with+real\-world accounts.+Some editor modes provide highlighting and shortcuts for working with+status.+Eg in Emacs ledger\-mode, you can toggle transaction status with C\-c+C\-e, or posting status with C\-c C\-c.+.PP+What \(dquncleared\(dq, \(dqpending\(dq, and \(dqcleared\(dq actually+mean is up to you.+Here\(aqs one suggestion:+.PP+.TS+tab(@);+lw(9.7n) lw(60.3n).+T{+status+T}@T{+meaning+T}+_+T{+uncleared+T}@T{+recorded but not yet reconciled; needs review+T}+T{+pending+T}@T{+tentatively reconciled (if needed, eg during a big reconciliation)+T}+T{+cleared+T}@T{+complete, reconciled as far as possible, and considered correct+T}+.TE+.PP+With this scheme, you would use \f[CR]\-PC\f[R] to see the current+balance at your bank, \f[CR]\-U\f[R] to see things which will probably+hit your bank soon (like uncashed checks), and no flags to see the most+up\-to\-date state of your finances.+.SS Code+After the status mark, but before the description, you can optionally+write a transaction \(dqcode\(dq, such as a check number or transaction+id, enclosed in parentheses.+.PP+This has a few limitations: The code must not contain a closing+parenthesis (or it will be truncated).+Codes tend to disrupt alignment of the register report, making it harder+to scan visually.+And you can\(aqt store more than one value there per transaction.+For these reasons you might want to avoid the code field and use tags+instead.+.SS Description+After the date, status mark and/or code fields, the rest of the line (or+until a comment is begun with \f[CR];\f[R]) is the transaction\(aqs+description.+Here you can describe the transaction (called the \(dqnarration\(dq in+traditional bookkeeping), or you can record a payee/payer name, or you+can leave it empty.+.PP+Transaction descriptions show up in print output and in register+reports, and can be listed with the descriptions command.+.PP+You can query by description with \f[CR]desc:DESCREGEX\f[R], or pivot on+description with \f[CR]\-\-pivot desc\f[R].+.SS Payee and note+Sometimes people want a dedicated payee/payer field that can be queried+and checked more strictly.+If you want that, you can write a \f[CR]|\f[R] (pipe) character in the+description.+This divides it into a \(dqpayee\(dq field on the left, and a+\(dqnote\(dq field on the right.+(Either can be empty.)+.PP+You can query these with \f[CR]payee:PAYEEREGEX\f[R] and+\f[CR]note:NOTEREGEX\f[R], list their values with the payees and notes+commands, or pivot on \f[CR]payee\f[R] or \f[CR]note\f[R].+.PP+Note: in transactions with no \f[CR]|\f[R] character, description,+payee, and note all have the same value.+Once a \f[CR]|\f[R] is added, they become distinct.+.PP+If you want more strict error checking, you can declare the valid payee+names with payee directives, and then enforce these with hledger check+payees.+(Note: because of the above, for this you\(aqll need to ensure every+transaction description contains a \f[CR]|\f[R] and therefore a+checkable payee name, even if it\(aqs empty.)+.SS Transaction comments+Text following \f[CR];\f[R], after a transaction description, and/or on+indented lines immediately below it, form comments for that transaction.+They are reproduced by \f[CR]print\f[R] but otherwise ignored, except+they may contain tags, which are not ignored.+.IP+.EX+2012\-01\-01 something ; a transaction comment+ ; a second line of transaction comment+ expenses 1+ assets+.EE+.SS Postings+A posting is an addition of some amount to, or removal of some amount+from, an account.+Each posting line begins with at least one space or tab (2 or 4 spaces+is common), followed by:+.IP \(bu 2+(optional) a status character (empty, \f[CR]!\f[R], or \f[CR]*\f[R]),+followed by a space+.IP \(bu 2+(required) an account name (any text, optionally including single+spaces.+If anything follows the account name on the same line, the account name+must be ended by \f[B]two or more spaces\f[R].)+.IP \(bu 2+(optional) an amount+.IP \(bu 2+(optional) a same\-line posting comment, beginning with a semicolon+(\f[CR];\f[R]).+.PP+If the amount is positive, it is being added to the account; if+negative, it is being removed from the account.+.PP+The posting amounts in a transaction must sum up to zero, indicating+that the inflows and outflows are equal.+We call this a balanced transaction.+(You can read more about the details of transaction balancing below.)+.PP+If no amount is written, it will be calculated automatically from the+other postings in the transaction, so as to balance the transaction.+In other words, in any transaction you can leave one posting amountless+to save typing.+.SS Debits and credits+The traditional accounting concepts of debit and credit of course exist+in hledger, but we represent them with numeric sign.+Positive and negative posting amounts represent debits and credits+respectively.+.PP+You don\(aqt need to remember that, but if you would like to \- eg for+helping newcomers or for talking with your accountant \- here\(aqs a+handy mnemonic:+.PP+\f[I]\f[CI]debit / plus / left / short words\f[I]\f[R]+.PD 0+.P+.PD+\f[I]\f[CI]credit / minus / right / longer words\f[I]\f[R]+.SS Account names+Accounts are the main way of categorising things in hledger.+As in Double Entry Bookkeeping, they can represent real world accounts+(such as a bank account), or more abstract categories such as \(dqmoney+spent on food\(dq or \(dqmoney borrowed from Frank\(dq.+.PP+Account names are flexible.+They may be capitalised or not; they may contain letters, numbers,+punctuation, symbols, or single spaces; they may be in any language.+Their parts, separated by \f[CR]:\f[R], can\(aqt be empty; so an account+name can\(aqt begin or end with \f[CR]:\f[R], or contain \f[CR]::\f[R].+.PP+Typically we use the five traditional accounting categories as the+starting point for account names.+In english they are:+.PP+\f[CR]assets\f[R], \f[CR]liabilities\f[R], \f[CR]equity\f[R],+\f[CR]revenues\f[R], \f[CR]expenses\f[R]+.PP+These will be discussed more in Account types below.+In hledger docs you may see them referred to as A, L, E, R, X for short.+.SS Two space delimiter+Note that hledger\(aqs account names, like Ledger\(aqs, may contain+single spaces.+Because of this, they must be separated from anything following them on+the same line by \f[B]two or more spaces\f[R].+(Two or more tabs also work; but spaces are preferred.+A single tab is not a separator, unlike in Ledger.)+.PP+This lets us use expressive account names, while still keeping the+syntax light.+Here are some examples:+.IP+.EX+ assets:accounts receivable ; bad, only one space before the comment+ assets:accounts receivable ; good+.EE+.IP+.EX+ assets:accounts receivable $10 ; bad, one space before the amount+ assets:accounts receivable $10 ; good+.EE+.IP+.EX+ assets:accounts receivable = $1000 ; bad, one space before the balance assignment+ assets:accounts receivable = $1000 ; good+.EE+.PP+The two\-space delimiter is also required in periodic transaction rules,+between period expression and description:+.IP+.EX+\(ti every 5th day YouTube Premium ; bad, one space before the description+\(ti every 5th day YouTube Premium ; good+.EE+.PP+When you are starting out, you can expect this delimiter will trip you+up once or twice.+(If it happens too much, you can check account names strictly to prevent+it.)+.SS Account hierarchy+For more precise reporting, we usually divide accounts into more+detailed subaccounts, subsubaccounts, and so on, by writing a full colon+between account name parts.+For example, instead of writing \f[CR]assets\f[R] and+\f[CR]expenses\f[R], we might write \f[CR]assets:bank:checking\f[R] and+\f[CR]expenses:food\f[R].+From these names hledger will infer this hierarchy of five accounts:+.IP+.EX+assets+assets:bank+assets:bank:checking+expenses+expenses:food+.EE+.PP+Or as an outline:+.IP+.EX+assets+ bank+ checking+expenses+ food+.EE+.PP+hledger reports can summarise the account tree to any depth, so you can+make your subcategories as detailed as you like.+But don\(aqt go overboard, especially when getting started; simpler+categories can be less work.+.SS Other account name features+Enclosing the account name in parentheses or brackets, like+\f[CR](expenses:food)\f[R], enables a non\-standard bookkeeping feature:+virtual postings.+.PP+Account names can be rewritten and restructured, temporarily or+permanently, by account aliases.+.SS Amounts+After the account name, there is usually an amount.+(Remember: between account name and amount, there must be two or more+spaces.)+.PP+hledger\(aqs amount format is flexible, supporting several international+formats.+Here are some examples.+Amounts have a number (the \(dqquantity\(dq):+.IP+.EX+1+.EE+.PP+\&..and usually a currency symbol or commodity name (more on this+below), to the left or right of the quantity, with or without a+separating space:+.IP+.EX+$1+4000 AAPL+3 \(dqgreen apples\(dq+.EE+.PP+Amounts can be preceded by a minus sign (or a plus sign, though plus is+the default), The sign can be written before or after a left\-side+commodity symbol:+.IP+.EX+\-$1+$\-1+.EE+.PP+One or more spaces between the sign and the number are acceptable when+parsing (but they won\(aqt be displayed in output):+.IP+.EX++ $1+$\- 1+.EE+.PP+Scientific E notation is allowed:+.IP+.EX+1E\-6+EUR 1E3+.EE+.PP+.SS Decimal marks+A \f[I]decimal mark\f[R] can be written as a period or a comma:+.IP+.EX+1.23+1,23+.EE+.PP+Both of these are common in international number formats, so hledger is+not biased towards one or the other.+Because hledger also supports digit group marks (eg thousands+separators), this means that a number like \f[CR]1,000\f[R] or+\f[CR]1.000\f[R] containing just one period or comma is ambiguous.+In such cases, hledger by default assumes it is a decimal mark, and will+parse both of those as 1.+.PP+To help hledger parse such ambiguous numbers accurately, if you use+digit group marks, we recommend declaring the decimal mark explicitly.+You can declare it per commodity with \f[CR]commodity\f[R] directives,+or per file with a \f[CR]decimal\-mark\f[R] directive at the top of each+journal file (described below).+.PP+hledger also accepts numbers like \f[CR]10.\f[R] with no digits after+the decimal mark (and will sometimes display numbers that way to+disambiguate them \- see Trailing decimal marks).+.SS Digit group marks+In the integer part of the amount quantity (left of the decimal mark),+groups of digits can optionally be separated by a \f[I]digit group+mark\f[R] \- a comma or period (whichever is not used as decimal mark),+an underscore, an apostrophe, or a space (several Unicode space+variants, like no\-break space, are also accepted).+So these are all valid amounts in a journal file:+.IP+.EX+ $1,000,000.00+ EUR 2.000.000,00+INR 9,99,99,999.00+ CHF 1\(aq000\(aq000.00+ 1_000_000.00+ 1 000 000.00 ; <\- ordinary space+ 1\ 000\ 000.00 ; <\- no\-break space+.EE+.SS Commodity+Amounts in hledger have both a \(dqquantity\(dq, which is a signed+decimal number, and a \(dqcommodity\(dq, which is a currency symbol,+stock ticker, or any word or phrase describing something you are+tracking.+.PP+If the commodity name contains non\-letters (spaces, numbers, or+punctuation), you must always write it inside double quotes+(\f[CR]\(dqgreen apples\(dq\f[R], \f[CR]\(dqABC123\(dq\f[R]).+In particular, in a posting amount, a symbol that begins with+\f[CR](\f[R] before the number, or with \f[CR]/\f[R] after it, or that+contains \f[CR])\f[R] inside parentheses, must be quoted, eg+\f[CR]\(dq(X)\(dq 10\f[R] or \f[CR]10 \(dq/x\(dq\f[R], or it would be+read as part of an amount expression.+.PP+If you write just a bare number, that too will have a commodity, with+name \f[CR]\(dq\(dq\f[R]; we call that the \(dqno\-symbol commodity\(dq.+.PP+Actually, hledger combines these single\-commodity amounts into more+powerful multi\-commodity amounts, which are what it works with most of+the time.+A multi\-commodity amount could be, eg:+\f[CR]1 USD, 2 EUR, 3.456 TSLA\f[R].+In practice, you will only see multi\-commodity amounts in hledger\(aqs+output; you can\(aqt write them directly in the journal file.+.PP+By default, the format of amounts in the journal influences how hledger+displays them in output.+This is explained in Commodity display style below.+.PP+A posting amount can also be an arithmetic expression, like+\f[CR]$47.97 + $15.75\f[R]; see Amount expressions.+.PP+.SS Costs+When one commodity is exchanged for another \- a currency conversion, or+a purchase or sale of stock \- you can record the transacted price or+conversion rate by writing \f[CR]\(at UNITCOST\f[R] or+\f[CR]\(at\(at TOTALCOST\f[R] after a posting amount.+(hledger docs generically call this a \(dqcost\(dq, whether buying or+selling, though \(dqcost\(dq is an overloaded word.+\(dqTransacted cost\(dq or \(dqtransacted price\(dq is more precise.)+Eg:+.IP+.EX+2026\-01\-01 buy euros+ assets:dollars $\-123+ assets:euros €100 \(at $1.23 ; unit cost (exchange rate)+.EE+.PP+or:+.IP+.EX+2026\-01\-01 buy euros+ assets:dollars $\-123+ assets:euros €100 \(at\(at $123 ; total cost+.EE+.PP+The cost should normally be a positive amount.+Negative costs are supported, but can be confusing, as discussed at+\-\-infer\-market\-prices: market prices from transactions.+.PP+Costs participate in transaction balancing: amounts are converted to+their cost before checking if the transaction is balanced.+So you could also write the above less redundantly, like so:+.IP+.EX+2026\-01\-01 buy euros+ assets:dollars ; $\-123 is inferred+ assets:euros €100 \(at $1.23+.EE+.PP+or:+.IP+.EX+2026\-01\-01 buy euros+ assets:dollars ; $\-123 is inferred+ assets:euros €100 \(at\(at $123+.EE+.PP+or even:+.IP+.EX+2026\-01\-01 buy euros+ assets:euros €100 ; \(at\(at $123 is inferred+ assets:dollars $\-123+.EE+.PP+This last form works for transactions involving exactly two commodities,+with neither cost notation nor equity postings.+If one of the postings is recognised as a lot posting, the cost will be+attached to that one.+Otherwise the cost will be attached to the first (top) posting \- so it+can be important to put the right one first.+Here we had to switch the order of postings, to get the same meaning as+above.+.PP+This form is the easiest to make undetected errors with; so it is+rejected by \f[CR]hledger check balanced\f[R], and by strict mode.+.PP+Reports can show amounts converted to their cost when you add the+\f[CR]\-B/\-\-cost\f[R] flag.+.PP+Costs can also be recorded in a more traditional double entry way, with+equity postings; or with both notations at once.+See Cost reporting for a comparison of these styles, and how hledger can+convert between them.+.SS Cost basis+This section briefly describes the \f[CR]{}\f[R] cost basis syntax, used+to record the nominal cost of an investment being acquired, or to select+lots being transferred or disposed.+This is described in more detail later in Lots and capital gains.+If you\(aqre not tracking investment lots and capital gains, you can+skip this.+.PP+hledger\(aqs cost basis annotations look like Beancount\(aqs:+comma\-separated parts enclosed in curly braces, after an amount.+All parts are optional, but when present they must be in this order:+.IP "1." 3+a date, in YYYY\-MM\-DD format+.IP "2." 3+a text label, enclosed in double quotes+.IP "3." 3+a cost, as a single\-commodity hledger amount.+.PP+Here are some valid hledger cost basis annotations:+.IP+.EX+{2026\-01\-15, \(dq12:05\(dq, $50}+{2026\-01\-15, $50}+{1.000.000,33 EUR}+{$50}+{}+.EE+.PP+This means: selling 10 AAPL, originally purchased at $50 each, for $60+each:+.IP+.EX+\-10 AAPL {$50} \(at $60+.EE+.PP+Note the preferred order is to write {} before \(at, as shown.+.PP+hledger can also read Ledger\(aqs cost basis syntax.+Here, the parts are written separately, in any order, with different+enclosing characters:+.IP+.EX+10 AAPL {$50} [2026\-01\-15] (12:05)+.EE+.PP+If a Ledger\-style label annotation contains double quotes, they will be+stripped (\f[CR](\(dqfoo\(dq)\f[R] is read as label \f[CR]foo\f[R]).+.SS Balance assertions+hledger supports Ledger\-style balance assertions in journal files.+These look like, for example, \f[CR]= EXPECTEDBALANCE\f[R] following a+posting\(aqs amount.+Eg here we assert the expected dollar balance in accounts a and b after+each posting:+.IP+.EX+2013/1/1+ a $1 = $1+ b = $\-1++2013/1/2+ a $1 = $2+ b $\-1 = $\-2+.EE+.PP+After reading a journal file, hledger will check all balance assertions+and report an error if any of them fail.+Balance assertions can protect you from, eg, inadvertently disrupting+reconciled balances while cleaning up old entries.+You can disable them temporarily with the \f[CR]\-I\f[R] or+\f[CR]\-\-ignore\-assertions\f[R] flag, which can be useful for+troubleshooting or for reading Ledger files.+(Note: this flag currently does not disable balance assignments,+described below).+.PP+To check rules which should hold at all times, such as \(dqno asset+account is ever negative\(dq, see assert directives.+.SS Assertions and ordering+hledger calculates and checks an account\(aqs balance assertions in date+order (and when there are multiple assertions on the same day, in parse+order).+Note this is different from Ledger, which checks assertions always in+parse order, ignoring dates.+.PP+This means in hledger you can freely reorder transactions, postings, or+files, and balance assertions will usually keep working.+The exception is when you reorder multiple postings on the same day, to+the same account, which have balance assertions; those will likely need+updating.+.SS Assertions and multiple files+If an account has transactions appearing in multiple files, balance+assertions can still work \- but \f[I]only if those files are part of a+hierarchy made by include directives\f[R].+.PP+If the same files are specified with two \f[CR]\-f\f[R] options on the+command line, the assertions in the second will not see the balances+from the first.+.PP+To work around this, arrange your files in a hierarchy with+\f[CR]include\f[R].+Or, you could concatenate the files temporarily, and process them like+one big file.+.PP+This is for stable, predictable reports: the file hierarchy is part of+your data, while the order of command line arguments is not, and+reordering your arguments should not change whether your assertions+pass.+.SS Assertions and costs+Balance assertions ignore costs, and should normally be written without+one:+.IP+.EX+2019/1/1+ (a) $1 \(at €1 = $1+.EE+.PP+We do allow costs to be written in balance assertion amounts, however,+and print shows them, but they don\(aqt affect whether the assertion+passes or fails.+This is for backward compatibility (hledger\(aqs close command used to+generate balance assertions with costs), and because balance+\f[I]assignments\f[R] do use costs (see below).+.SS Assertions and commodities+The balance assertions described so far are \(dq\f[B]single commodity+balance assertions\f[R]\(dq: they assert and check the balance in one+commodity, ignoring any others that may be present.+This is how balance assertions work in Ledger also.+.PP+If an account contains multiple commodities, you can assert their+balances by writing multiple postings with balance assertions, one for+each commodity:+.IP+.EX+2013/1/1+ usd $\-1+ eur €\-1+ both++2013/1/2+ both 0 = $1+ both 0 = €1+.EE+.PP+In hledger you can make a stronger \(dq\f[B]sole commodity balance+assertion\f[R]\(dq by writing two equals signs+(\f[CR]== EXPECTEDBALANCE\f[R]).+This also asserts that there are no other commodities in the account+besides the asserted one (or at least, that their current balance is+zero):+.IP+.EX+2013/1/1+ usd $\-1 == $\-1 ; these sole commodity assertions succeed+ eur €\-1 == €\-1+ both ;== $1 ; this one would fail because \(aqboth\(aq contains $ and €+.EE+.PP+It\(aqs less easy to make a \(dq\f[B]sole commodities balance+assertion\f[R]\(dq (note the plural) \- ie, asserting that an account+contains two or more specified commodities and no others.+It can be done by+.IP "1." 3+isolating each commodity in a subaccount, and asserting those+.IP "2." 3+and also asserting there are no commodities in the parent account+itself:+.IP+.EX+2013/1/1+ usd $\-1+ eur €\-1+ both 0 == 0 ; nothing up my sleeve+ both:usd $1 == $1 ; a dollar here+ both:eur €1 == €1 ; a euro there+.EE+.SS Assertions and subaccounts+All of the balance assertions above (both \f[CR]=\f[R] and+\f[CR]==\f[R]) are \(dq\f[B]subaccount\-exclusive balance+assertions\f[R]\(dq; they ignore any balances that exist in deeper+subaccounts.+.PP+In hledger you can make \(dq\f[B]subaccount\-inclusive balance+assertions\f[R]\(dq by adding a star after the equals (\f[CR]=*\f[R] or+\f[CR]==*\f[R]):+.IP+.EX+2019/1/1+ equity:start+ assets:checking $10+ assets:savings $10+ assets $0 ==* $20 ; assets + subaccounts contains $20 and nothing else+.EE+.SS Assertions and lot subaccounts+Lot subaccounts (a special kind of subaccount for tracking lots,+discussed in \(dqLots and capital gains\(dq below) have only limited+support for balance assertions: the assertions will be checked correctly+only if all postings to that lot mention the subaccount name explicitly.+.PP+Since it\(aqs common practice to leave lot subaccounts implicit,+generally you should avoid writing balance assertions on individual+lots.+(\f[CR]close \-\-lots\f[R] also follows this rule.)+If you forget, the balance assertion failure message will remind you.+If you really need a balance assertion, you can usually write it on the+parent account instead.+.PP+(The restriction is because transaction balancing amounts, balance+assignments, and balance assertions must be calculated and checked+before lot movements are known.)+See also Lot postings and balance assertions.+.SS Assertions and status+Balance assertions always consider postings of all statuses (unmarked,+pending, or cleared); they are not affected by the+\f[CR]\-U\f[R]/\f[CR]\-\-unmarked\f[R] /+\f[CR]\-P\f[R]/\f[CR]\-\-pending\f[R] /+\f[CR]\-C\f[R]/\f[CR]\-\-cleared\f[R] flags or the \f[CR]status:\f[R]+query.+.SS Assertions and virtual postings+Balance assertions always consider both real and virtual postings; they+are not affected by the \f[CR]\-\-real/\-R\f[R] flag or \f[CR]real:\f[R]+query.+.SS Assertions and auto postings+Balance assertions \f[I]are\f[R] affected by the \f[CR]\-\-auto\f[R]+flag, which generates auto postings, which can alter account balances.+Because auto postings are optional in hledger, accounts affected by them+effectively have two balances.+But balance assertions can only test one or the other of these.+So to avoid making fragile assertions, either:+.IP \(bu 2+assert the balance calculated with \f[CR]\-\-auto\f[R], and always use+\f[CR]\-\-auto\f[R] with that file+.IP \(bu 2+or assert the balance calculated without \f[CR]\-\-auto\f[R], and never+use \f[CR]\-\-auto\f[R] with that file+.IP \(bu 2+or avoid balance assertions on accounts affected by auto postings (or+avoid auto postings entirely).+.SS Assertions and precision+Balance assertions compare the exactly calculated amounts, which are not+always what is shown by reports.+Eg a commodity directive may limit the display precision, but this will+not affect balance assertions.+Balance assertion failure messages show exact amounts.+.SS Assertions and hledger add+The \f[CR]add\f[R] command also accepts balance assertions (and+assignments), and re\-checks all of the journal\(aqs assertions as you+enter amounts; see add and balance assertions.+.SS Posting comments+Text following \f[CR];\f[R], at the end of a posting line, and/or on+indented lines immediately below it, form comments for that posting.+They are reproduced by \f[CR]print\f[R] but otherwise ignored, except+they may contain tags, which are not ignored.+.IP+.EX+2012\-01\-01+ expenses 1 ; a comment for posting 1+ assets+ ; a comment for posting 2+ ; a second comment line for posting 2+.EE+.SS Tags+Tags are a way to add extra labels or data fields to transactions,+postings, or accounts, which you can match with a \f[CR]tag:\f[R] query+in reports.+(See queries below.)+.PP+Tags are a single word or hyphenated word, immediately followed by a+full colon, written within a comment.+(Yes, storing data in comments is slightly weird.)+Here\(aqs a transaction with a tag:+.IP+.EX+2025\-01\-01 groceries ; some\-tag:+ assets:checking+ expenses:food $1+.EE+.PP+A tag can have a value: a single line of text written after the colon+(tag values can\(aqt contain newlines):+.IP+.EX+2025\-01\-01 groceries ; tag1: this is tag1\(aqs value+.EE+.PP+Multiple tags can be separated by comma (so tag values can\(aqt contain+commas):+.IP+.EX+2025\-01\-01 groceries ; tag1:value 1, tag2:value 2, comment text+.EE+.PP+A tag can have multiple values:+.IP+.EX+2025\-01\-01 groceries ; tag1:value 1, tag1:value 2+.EE+.PP+You can write each tag on its own line if you prefer (but they still+can\(aqt contain commas):+.IP+.EX+2025\-01\-01 groceries+ ; tag1: value 1+ ; tag2: value 2+.EE+.PP+Tags can be attached to individual postings, rather than the overall+transaction:+.IP+.EX+2025\-01\-01 rent+ assets:checking+ expenses:rent $1000 ; postingtag:+.EE+.PP+Tags can be attached to accounts, in their account directive:+.IP+.EX+account assets:checking ; acct\-number: 123\-45\-6789+.EE+.SS Tag propagation+In addition to what they are attached to, tags also affect related data+in a few ways, allowing more powerful queries:+.IP "1." 3+Accounts \-> postings.+Postings inherit tags from their account.+.IP "2." 3+Transactions \-> postings.+Postings inherit tags from their transaction.+.IP "3." 3+Postings \-> transactions.+Transactions also acquire the tags of their postings.+.PP+So when you use a \f[CR]tag:\f[R] query to match whole transactions,+individual postings, or accounts, it\(aqs good to understand how tags+behave.+Here\(aqs an example showing all three kinds of propagation:+.IP+.EX+account assets:checking+account expenses:food ; atag:++2025\-01\-01 groceries ; ttag:+ assets:checking ; p1tag:+ expenses:food $1 ; p2tag:+.EE+.PP+.TS+tab(@);+lw(13.3n) lw(13.8n) lw(43.0n).+T{+data part+T}@T{+has tags+T}@T{+explanation+T}+_+T{+assets:checking\ account+T}@T{+T}@T{+no tags attached+T}+T{+expenses:food account+T}@T{+atag+T}@T{+atag: in comment+T}+T{+assets:checking posting+T}@T{+p1tag, ttag+T}@T{+p1tag: in comment, ttag acquired from transaction+T}+T{+expenses:food posting+T}@T{+p2tag, atag, ttag+T}@T{+p2tag: in comment, atag from account, ttag from transaction+T}+T{+groceries transaction+T}@T{+ttag, p1tag, p2tag, atag+T}@T{+ttag: in comment, p1tag from first posting, p2tag and atag from second+posting+T}+.TE+.SS Displaying tags+You can use the \f[CR]tags\f[R] command to list tag names or values.+.PP+The \f[CR]print\f[R] command also shows tags.+.PP+You can use \-\-pivot to display tag values in other reports, in various+ways (eg appended to account names, like pseudo subaccounts).+.SS When to use tags ?+Tags provide more dimensions of categorisation, complementing accounts+and transaction descriptions.+When to use each of these is somewhat a matter of taste.+Accounts have the most built\-in support, and regex queries on+descriptions are also quite powerful.+So you may not need tags at all.+But if you want to track multiple cross\-cutting categories, they can be+a good fit.+For example, you could tag trip\-related transactions with+\f[CR]trip: YEAR:PLACE\f[R], without disturbing your usual account+categories.+.SS Tag names+What is allowed in a tag name ?+Any sequence of non\-whitespace non\-newline characters.+Eg \f[CR]😀:\f[R] is a valid tag.+.PP+For extra error checking, you can declare valid tag names with the+\f[CR]tag\f[R] directive, and then enforce these with the+\f[CR]check\f[R] command.+But note that tags are detected quite loosely at present, sometimes+where you didn\(aqt intend them.+Eg a comment like \f[CR]; see https://foo.com\f[R] adds a+\f[CR]https\f[R] tag.+.PP+There are several tag names which have special significance to hledger.+They are explained elsewhere, but here\(aqs a quick reference:+.IP+.EX+ type \-\- declares an account\(aqs type+ alias \-\- declares an account\(aqs or commodity\(aqs alias+ lots \-\- declares an account\(aqs or commodity\(aqs lot tracking (cost basis method)+ date \-\- overrides a posting\(aqs date+ date2 \-\- overrides a posting\(aqs secondary date+ assert \-\- appears on txns generated by close \-\-assert+ retain \-\- appears on txns generated by close \-\-retain+ start \-\- appears on txns generated by close \-\-migrate/\-\-close/\-\-open/\-\-assign+ t \-\- appears on postings generated from timedot letters++ generated\-transaction \-\- appears on txns generated by a periodic rule+ modified\-transaction \-\- appears on txns which have had auto postings added+ generated\-posting \-\- appears on generated postings+ cost\-posting \-\- appears on postings which have (or could have) a cost,+ and which have equivalent conversion postings in the transaction+ conversion\-posting \-\- appears on postings which are to a V/Conversion account+ and which have an equivalent cost posting in the transaction+ ptype \-\- appears on lot postings, with their type (acquire, dispose, etc.)+ feesplit\-posting \-\- appears on fee parts split off a lot transfer posting+ lotsplit\-posting \-\- appears on the parts of a posting split across several lots (with \-\-lots)+ lot\-parent\-assertion \-\- appears on postings carrying a balance assertion moved+ from a posting that was split across several lots+.EE+.PP+The second group above (generated\-transaction, etc.)+are normally hidden, with a \f[CR]_\f[R] prefix added.+This means \f[CR]print\f[R] doesn\(aqt show them by default; but you can+still use them in queries.+You can add the \f[CR]\-\-verbose\-tags\f[R] flag to make them visible+in \f[CR]print\f[R] output, which can be useful for troubleshooting.+.SS Tag values+What is allowed in a tag value ?+Any sequence of non\-comma non\-newline characters, with surrounding+whitespace removed.+.PP+Note a tag can have multiple values, if the tag is repeated.+Eg \f[CR]; foo:a, foo:b\f[R].+.SS Directives+You can add directives to a \f[CR]journal\f[R] file, to add error+checking, improve parsing, et cetera.+Directives begin with a keyword, not a date.+Some of them can have indented subdirectives.+hledger\(aqs directives are broadly similar to Ledger\(aqs, though with+differences.+.SS Directive scopes+Directives differ in which entries they affect.+Some affect only the following entries, others affect both preceding and+following entries; and some reach only the current file and its+subfiles, others reach every file.+Assuming this command and file layout:+.IP+.EX+hledger \-f main.journal \-f other.journal++main.journal ; the parent file+ include a.journal ; a child of main.journal+ include aa.journal ; a child of a.journal+ include b.journal ; a child of main.journal, and a sibling of a.journal++other.journal ; a separate file tree+.EE+.PP+here are the possible scopes, for a directive written in+\f[CR]a.journal\f[R]:+.PP+.TS+tab(@);+lw(14.7n) lw(55.3n).+T{+scope+T}@T{+affects+T}+_+T{+\f[B]rest of file + subfiles\f[R]+T}@T{+following entries in or below \f[CR]a.journal\f[R] (including+\f[CR]aa.journal\f[R] if it is included after the directive)+T}+T{+\f[B]rest of file tree\f[R]+T}@T{+as above, plus following entries in parent files+(\f[CR]main.journal\f[R] entries after the \f[CR]include a.journal\f[R]+directive, including \f[CR]b.journal\f[R])+T}+T{+\f[B]file tree\f[R]+T}@T{+all entries in \f[CR]main.journal\f[R], \f[CR]a.journal\f[R],+\f[CR]aa.journal\f[R] and \f[CR]b.journal\f[R], before and after the+directive+T}+T{+\f[B]all files\f[R]+T}@T{+all entries in all file trees, no matter where the directive is written+T}+.TE+.PP+The limited scopes help keep reports stable and deterministic,+independent of the order of \-f options or include directives.+This is sometimes inconvenient, but there are usually workarounds.+In particular, to have account aliases affect all entries in a file+tree, declare them at the start of the main file, before any+\f[CR]include\f[R]s.+(Or to affect all file trees specified at runtime, use+\f[CR]\-\-alias\f[R] options.)+.SS Combining file trees+When you read several file trees (with several \f[CR]\-f\f[R] options),+hledger reads and processes each one separately, then combines them.+So one file tree can\(aqt change how another\(aqs entries are read:+account and commodity aliases, decimal marks, transaction balancing,+balance assertions and assert directives, auto postings, forecast+transactions and lot tracking all work within each file tree.+.PP+But a few declarations reach all file trees (\(dqall files\(dq in the+table below):+.IP \(bu 2+Account declarations, including account types and display order.+.IP \(bu 2+Commodity declarations, including display styles.+If file trees declare a commodity\(aqs display style differently, the+last one is used.+.IP \(bu 2+Payee and tag declarations.+.IP \(bu 2+\f[CR]P\f[R] market prices, used for valuation.+.IP \(bu 2+Commodity aliases, but only for valuation, and only as a last resort:+when market prices can\(aqt convert an amount, eg if it\(aqs in an alias+declared by another file tree.+If file trees declare an alias differently (for a different commodity,+or with a different quantity), converting to or from it this way is an+error.+.PP+So you can combine file trees that weren\(aqt designed to work together.+The interactions to watch for are conflicting display styles, account+types, and market prices.+.SS Directives summary+.PP+.TS+tab(@);+lw(7.9n) lw(51.6n) lw(10.5n).+T{+directive+T}@T{+what it does+T}@T{+scope+T}+_+T{+T}@T{+\f[B]Affects file reading:\f[R]+T}@T{+T}+T{+\f[B]\f[CB]include\f[B]\f[R]+T}@T{+Includes entries from another file (a \(dqsubfile\(dq), as if they were+written inline.+T}@T{+T}+T{+\f[B]\f[CB]comment\f[B]\f[R]+T}@T{+Ignores following entries and directives, until \f[CR]end comment\f[R].+T}@T{+rest of file + subfiles+T}+T{+\f[B]\f[CB]alias\f[B]\f[R]+T}@T{+Rewrites following matched account names, until \f[CR]end aliases\f[R].+T}@T{+rest of file + subfiles+T}+T{+\f[B]\f[CB]account\f[B]\f[R] \f[CR]alias:\f[R] tag+T}@T{+Rewrites following matched account names to this account\(aqs full name,+until \f[CR]end aliases\f[R].+T}@T{+rest of file + subfiles+T}+T{+\f[B]\f[CB]decimal\-mark\f[B]\f[R]+T}@T{+Declares the decimal mark for parsing following amounts of all+commodities, until the next \f[CR]decimal\-mark\f[R] (subfiles can+override).+T}@T{+rest of file + subfiles+T}+T{+\f[B]\f[CB]commodity\f[B]\f[R] sample amount+T}@T{+Declares the decimal mark for parsing following amounts of this+commodity (\f[CR]decimal\-mark\f[R] can override).+T}@T{+rest of file tree+T}+T{+T}@T{+\f[B]Declares data:\f[R]+T}@T{+T}+T{+\f[B]\f[CB]account\f[B]\f[R]+T}@T{+Declares an account, and its display order.+T}@T{+all files+T}+T{+\f[B]\f[CB]account\f[B]\f[R] \f[CR]type:\f[R] tag+T}@T{+Declares the account\(aqs type.+T}@T{+all files+T}+T{+\f[B]\f[CB]account\f[B]\f[R] \f[CR]lots:\f[R] tag+T}@T{+Declares the account\(aqs cost basis method.+T}@T{+file tree+T}+T{+\f[B]\f[CB]commodity\f[B]\f[R]+T}@T{+Declares a commodity symbol.+T}@T{+all files+T}+T{+\f[B]\f[CB]commodity\f[B]\f[R] sample amount+T}@T{+Declares the commodity\(aqs display style.+T}@T{+all files+T}+T{+\f[B]\f[CB]commodity\f[B]\f[R] \f[CR]alias:\f[R] tag+T}@T{+Declares equivalent or related symbols for this commodity.+T}@T{+file tree+T}+T{+\f[B]\f[CB]commodity\f[B]\f[R] \f[CR]lots:\f[R] tag+T}@T{+Declares that the commodity tracks lots, and optionally their cost basis+method.+T}@T{+file tree+T}+T{+\f[B]\f[CB]payee\f[B]\f[R]+T}@T{+Declares a payee name.+T}@T{+all files+T}+T{+\f[B]\f[CB]tag\f[B]\f[R]+T}@T{+Declares a tag name.+T}@T{+all files+T}+T{+\f[B]\f[CB]P\f[B]\f[R]+T}@T{+Declares a commodity\(aqs market price on some date, for value and gain+reports.+T}@T{+all files+T}+T{+T}@T{+\f[B]Generates data:\f[R]+T}@T{+T}+T{+\f[B]\f[CB]=\f[B]\f[R]+T}@T{+Generates extra postings (after matched postings), with+\f[CR]\-\-auto\f[R].+(Does not see sibling files: #1212.)+T}@T{+file tree+T}+T{+\f[B]\f[CB]\(ti\f[B]\f[R]+T}@T{+Generates future transactions (after latest transaction in file tree, by+default), with \f[CR]\-\-forecast\f[R].+T}@T{+file tree+T}+T{+\f[B]\f[CB]\(ti\f[B]\f[R]+T}@T{+Generates budget goals and actual/goal percentages, with+\f[CR]balance \-\-budget\f[R].+T}@T{+all files+T}+T{+T}@T{+\f[B]Checks data:\f[R]+T}@T{+T}+T{+\f[B]\f[CB]assert\f[B]\f[R]+T}@T{+Declares a standing rule, a query that must match no rows or some rows,+checked like balance assertions.+T}@T{+file tree+T}+T{+T}@T{+\f[B]File reading (legacy/deprecated):\f[R]+T}@T{+T}+T{+\f[CR]apply account\f[R]+T}@T{+Prepends a common parent account to all following account names, until+\f[CR]end apply account\f[R].+T}@T{+rest of file + subfiles+T}+T{+\f[CR]apply year\f[R]+T}@T{+Sets a default year for following yearless dates, until+\f[CR]end apply year\f[R].+T}@T{+rest of file + subfiles+T}+T{+\f[CR]D\f[R]+T}@T{+Sets a default commodity for following no\-symbol amounts.+Also sets its parsing decimal mark (overridden by \f[CR]commodity\f[R]+or \f[CR]decimal\-mark\f[R]) and display style (overridden by+\f[CR]commodity\f[R]).+T}@T{+rest of file + subfiles+T}+T{+\f[CR]Y\f[R]+T}@T{+Sets a default year for following yearless dates.+T}@T{+rest of file + subfiles+T}+T{+other+T}@T{+These other Ledger directives are accepted but ignored.+T}@T{+T}+.TE+.SS \f[CR]account\f[R] directive+\f[CR]account\f[R] directives can be used to declare accounts (ie, the+places that amounts are transferred from and to).+Though not required, these declarations can provide several benefits:+.IP \(bu 2+They can document your intended chart of accounts, providing a+reference.+.IP \(bu 2+They can store additional account information as comments, or as tags+which can be used to filter or pivot reports.+.IP \(bu 2+They can restrict which accounts may be posted to by transactions, eg in+strict mode, which helps prevent errors.+.IP \(bu 2+They influence account display order in reports, allowing+non\-alphabetic sorting (eg Revenues to appear above Expenses).+.IP \(bu 2+They can help hledger know your accounts\(aq types (asset, liability,+equity, revenue, expense), enabling reports like balancesheet and+incomestatement.+.IP \(bu 2+They help with account name completion (in hledger add, hledger\-web,+hledger\-iadd, ledger\-mode, etc.)+.PP+They are written as the word \f[CR]account\f[R] followed by a+hledger\-style account name.+Eg:+.IP+.EX+account assets:bank:checking+.EE+.PP+Any indented subdirectives are ignored, except Ledger\(aqs+\f[CR]alias\f[R] subdirective (see Account aliases).+.SS Account comments+Text following \f[B]two or more spaces\f[R] and \f[CR];\f[R] at the end+of an account directive line, and/or following \f[CR];\f[R] on indented+lines immediately below it, form comments for that account.+.PP+Same\-line account comments require two+ spaces before \f[CR];\f[R]+because that character can appear in account names.+.IP+.EX+account assets:bank:checking ; same\-line comment, at least 2 spaces before the semicolon+ ; next\-line comment+ ; some tags \- type:A, acctnum:12345+.EE+.SS Account tags+An account directive\(aqs comment may contain tags.+These will be inherited by all postings using that account, except where+the posting already has a value for that tag.+(A posting tag overrides an account tag.)+Note, these tags will be queryable but won\(aqt be shown in+\f[CR]print\f[R] output, even with \-\-verbose\-tags.+.SS Account aliases+An \f[CR]alias:\f[R] tag on an account directive declares an alternate,+usually shorter, name for that account.+This could make data entry quicker, and your journal less verbose (but+also adds more names for you to remember).+Eg:+.IP+.EX+account assets:bank:checking ; alias: checking++2024\-01\-01+ expenses:food 5+ checking+.EE+.PP+When hledger reads this, it rewrites \f[CR]checking\f[R] to+\f[CR]assets:bank:checking\f[R].+Reports, queries and \f[CR]print\f[R] output show only the full name.+Subaccounts are rewritten too: \f[CR]checking:pending\f[R] becomes+\f[CR]assets:bank:checking:pending\f[R].+(The alias must match the whole account name or its leading components,+exactly and case sensitively; \f[CR]Checking\f[R],+\f[CR]checkingfoo\f[R] or \f[CR]old:checking\f[R] would not be+affected.)+.PP+To declare multiple aliases, add more \f[CR]alias:\f[R] tags.+A Ledger\-style \f[CR]alias\f[R] subdirective, indented below the+account directive, is also accepted, and treated as an \f[CR]alias:\f[R]+tag.+To list the accounts with their aliases, run+\f[CR]hledger accounts \-\-show\-aliases\f[R]; to find the account(s)+with a certain alias, run+\f[CR]hledger accounts \-\-show\-aliases ALIAS\f[R].+.PP+An alias affects the entries which follow it, in the current file and+any files it includes (see directive scopes), until an+\f[CR]end aliases\f[R] directive.+So it\(aqs best to declare accounts at the start of your main file,+before any \f[CR]include\f[R] directives.+.PP+More powerful aliases, such as regular expression aliases which rewrite+many accounts at once, can be declared with the \f[CR]alias\f[R]+directive, described below.+An alias: tag is equivalent to a basic alias directive written just+after the account directive:+.IP+.EX+account assets:bank:checking ; alias: checking+.EE+.IP+.EX+account assets:bank:checking+alias checking = assets:bank:checking+.EE+.PP+You can also apply aliases at runtime, without editing your files, using+the \f[CR]\-\-alias\f[R] option.+.SS Account error checking+By default, accounts need not be declared; they come into existence when+a posting references them.+This is convenient, but it means hledger can\(aqt warn you when you+mis\-spell an account name in the journal.+Usually you\(aqll find that error later, as an extra account in balance+reports, or an incorrect balance when reconciling.+.PP+In strict mode, enabled with the \f[CR]\-s\f[R]/\f[CR]\-\-strict\f[R]+flag, or when you run \f[CR]hledger check accounts\f[R], hledger will+report an error if any transaction uses an account name that has not+been declared by an account directive.+Some notes:+.IP \(bu 2+The declaration is case\-sensitive; transactions must use the correct+account name capitalisation.+.IP \(bu 2+Account declarations affect all files (see directive scopes).+The position of account directives within the file does not matter,+though it\(aqs usual to put them at the top.+.IP \(bu 2+Accounts can only be declared in \f[CR]journal\f[R] files, but will+affect included files of all types.+.IP \(bu 2+It\(aqs currently not possible to declare \(dqall possible+subaccounts\(dq with a wildcard; every account posted to must be+declared.+.IP \(bu 2+As an exception: lot subaccounts (a final account name component like+\f[CR]:{2026\-01\-15, $50}\f[R]) are always ignored by+\f[CR]check accounts\f[R], and need not be declared.+.IP \(bu 2+Also exempt are the accounts which hledger chooses for the postings it+generates: equity conversion postings (from+\f[CR]\-\-infer\-equity\f[R]), gain postings (in lot disposals), and+imbalance postings (from \f[CR]\-\-infer\-imbalance\f[R]).+Postings which you write to those accounts are checked as usual.+.SS Account display order+Account directives also cause hledger to display accounts in a+particular order, not just alphabetically.+Eg, here is a conventional ordering for the top\-level accounts:+.IP+.EX+account assets+account liabilities+account equity+account revenues+account expenses+.EE+.PP+Now hledger displays them in that order:+.IP+.EX+$ hledger accounts+assets+liabilities+equity+revenues+expenses+.EE+.PP+If there are undeclared accounts, those will be displayed last, in+alphabetical order.+.PP+Sorting is done within each group of sibling accounts, at each level of+the account tree.+Eg, a declaration like \f[CR]account parent:child\f[R] influences+\f[CR]child\f[R]\(aqs position among its siblings.+.PP+Note, it does not affect \f[CR]parent\f[R]\(aqs position; for that, you+need an \f[CR]account parent\f[R] declaration.+.PP+Sibling accounts are always displayed together; hledger won\(aqt display+\f[CR]x:y\f[R] in between \f[CR]a:b\f[R] and \f[CR]a:c\f[R].+.PP+An account directive both declares an account as a valid posting target,+and declares its display order; you can\(aqt easily do one without the+other.+.SS Account types+hledger knows that in accounting there are three main account types:+.PP+.TS+tab(@);+l l l.+T{+\f[CR]Asset\f[R]+T}@T{+\f[CR]A\f[R]+T}@T{+things you own+T}+T{+\f[CR]Liability\f[R]+T}@T{+\f[CR]L\f[R]+T}@T{+things you owe+T}+T{+\f[CR]Equity\f[R]+T}@T{+\f[CR]E\f[R]+T}@T{+owner\(aqs investment, balances the two above+T}+.TE+.PP+and two more representing changes in these:+.PP+.TS+tab(@);+l l l.+T{+\f[CR]Revenue\f[R]+T}@T{+\f[CR]R\f[R]+T}@T{+inflows (also known as \f[CR]Income\f[R])+T}+T{+\f[CR]Expense\f[R]+T}@T{+\f[CR]X\f[R]+T}@T{+outflows+T}+.TE+.PP+hledger also uses a few subtypes:+.PP+.TS+tab(@);+lw(23.3n) lw(23.3n) lw(23.3n).+T{+\f[CR]Cash\f[R]+T}@T{+\f[CR]C\f[R]+T}@T{+liquid assets (subtype of Asset)+T}+T{+\f[CR]Conversion\f[R]+T}@T{+\f[CR]V\f[R]+T}@T{+commodity conversions equity (subtype of Equity)+T}+T{+\f[CR]Gain\f[R]+T}@T{+\f[CR]G\f[R]+T}@T{+realised capital gains/losses (subtype of Revenue)+T}+T{+\f[CR]UnrealisedGain\f[R]+T}@T{+\f[CR]U\f[R]+T}@T{+accumulated unrealised capital gains (subtype of Equity)+T}+T{+\f[CR]Imbalance\f[R]+T}@T{+\f[CR]M\f[R]+T}@T{+transactions\(aq tolerated imbalances, shown by+\f[CR]\-\-infer\-imbalance\f[R] (subtype of Equity)+T}+.TE+.PP+As a convenience, hledger will detect these types automatically from+english account names.+But it\(aqs better to declare them explicitly by adding a+\f[CR]type:\f[R] tag in the account directives.+The tag\(aqs value can be any of the types or one\-letter abbreviations+above.+.PP+Here is a typical set of account type declarations.+Subaccounts will inherit their parent\(aqs type, or can override it:+.IP+.EX+account assets ; type: A+account liabilities ; type: L+account equity ; type: E+account revenues ; type: R+account expenses ; type: X++account assets:bank ; type: C+account assets:cash ; type: C++account equity:conversion ; type: V+account equity:unrealised\-gain ; type: U++account revenues:gain ; type: G+.EE+.PP+This enables the easy balancesheet, balancesheetequity, cashflow and+incomestatement reports, and querying by type:.+.PP+Tips:+.IP \(bu 2+You can list accounts and their types, for troubleshooting:+.RS 2+.IP+.EX+$ hledger accounts \-\-types [ACCTPAT] [type:TYPECODES] [\-DEPTH] [\-\-locations]+.EE+.RE+.IP \(bu 2+It\(aqs a good idea to declare at least one account for each account+type.+Having some types declared and some inferred can disrupt certain+reports.+.IP \(bu 2+The rules for inferring types from account names are as follows (using+Regular expressions).+.PD 0+.P+.PD+If they don\(aqt work for you, just ignore them and declare your types+with \f[CR]type:\f[R] tags.+.RS 2+.IP+.EX+If account\(aqs name contains this case insensitive regular expression | its type is+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-|\-\-\-\-\-\-\-\-\-\-\-\-\-+\(haassets?(:.+)?:(cash|bank|che(ck|que?)(ing)?|savings?|current)(:|$) | Cash+\(haassets?(:|$) | Asset+\(ha(debts?|liabilit(y|ies))(:|$) | Liability+\(haequity:(trad(e|ing)|conversion)s?(:|$) | Conversion+\(haequity:unreali[sz]ed([\- ](capital[\- ])?gains?)?(:|$) | UnrealisedGain+\(haequity:imbalances?(:|$) | Imbalance+\(haequity(:|$) | Equity+\(ha(income|revenue)s?:(capital[\- ]?)?(gains?|loss(es)?)(:|$) | Gain+\(ha(income|revenue)s?(:|$) | Revenue+\(haexpenses?(:|$) | Expense+.EE+.RE+.IP \(bu 2+As mentioned above, subaccounts will inherit a type from their parent+account.+To be precise, an account\(aqs type is decided by the first of these+that exists:+.RS 2+.IP "1." 3+A \f[CR]type:\f[R] declaration for this account.+.IP "2." 3+A \f[CR]type:\f[R] declaration in the parent accounts above it,+preferring the nearest.+.IP "3." 3+An account type inferred from this account\(aqs name.+.IP "4." 3+An account type inferred from a parent account\(aqs name, preferring the+nearest parent.+.IP "5." 3+Otherwise, it will have no type.+.RE+.IP \(bu 2+Account aliases can disrupt account types.+.SS \f[CR]alias\f[R] directive+(Note: this section is about account aliases, not commodity aliases or+command aliases.)+.PP+\f[CR]alias\f[R] directives are a more general and powerful form of the+account aliases tags described above.+(There is also a runtime variant, defined with the \f[CR]\-\-alias\f[R]+option.)+.PP+Account alias rules rewrite your account names, or parts of them, after+reading the journal (affecting both directives and transactions), before+generating reports.+They do not affect account names being entered via hledger add or+hledger\-web.+.PP+Account aliases can be useful for:+.IP \(bu 2+expanding shorthand account names to their full form, allowing easier+data entry and a less verbose journal+.IP \(bu 2+adapting old journals to your current chart of accounts+.IP \(bu 2+experimenting with new account organisations, like a new hierarchy+.IP \(bu 2+combining two accounts into one, eg to see their sum or difference on+one line+.IP \(bu 2+customising reports+.SS Basic aliases+To set an account alias, use the \f[CR]alias\f[R] directive in your+journal file.+This affects all subsequent journal entries in the current file or its+included files (but note: not sibling or parent files; see directive+scopes).+The spaces around the = are optional:+.IP+.EX+alias OLD = NEW+.EE+.PP+Or, you can use \f[CR]\-\-alias \(aqOLD=NEW\(aq\f[R] on the command+line.+.PP+Or, for a declared account, you can write the alias as an+\f[CR]alias:\f[R] tag on its account directive.+.PP+OLD and NEW are case sensitive full account names.+hledger will replace any occurrence of the old account name with the new+one.+Subaccounts are also affected.+Eg:+.IP+.EX+alias checking = assets:bank:wells fargo:checking+; rewrites \(dqchecking\(dq to \(dqassets:bank:wells fargo:checking\(dq, or \(dqchecking:a\(dq to \(dqassets:bank:wells fargo:checking:a\(dq+.EE+.SS Regex aliases+There is also a more powerful variant that uses a regular expression,+indicated by wrapping the pattern in forward slashes.+(This is the only place where hledger requires forward slashes around a+regular expression.)+.PP+Eg:+.IP+.EX+alias /REGEX/ = REPLACEMENT+.EE+.PP+or:+.IP+.EX+$ hledger \-\-alias \(aq/REGEX/=REPLACEMENT\(aq ...+.EE+.PP+Any part of an account name matched by REGEX will be replaced by+REPLACEMENT.+REGEX is case\-insensitive as usual.+.PP+If you need to match a forward slash, escape it with a backslash, eg+\f[CR]/\(rs/=:\f[R].+.PP+If REGEX contains parenthesised match groups, these can be referenced by+the usual backslash and number in REPLACEMENT:+.IP+.EX+alias /\(ha(.+):bank:([\(ha:]+):(.*)/ = \(rs1:\(rs2 \(rs3+; rewrites \(dqassets:bank:wells fargo:checking\(dq to \(dqassets:wells fargo checking\(dq+.EE+.PP+REPLACEMENT continues to the end of line (or on command line, to end of+option argument), so it can contain trailing whitespace.+.SS \f[CR]\-\-alias\f[R] option+The \f[CR]\-\-alias\f[R] command line option defines an account alias,+using the same syntax as an \f[CR]alias\f[R] directive (basic or regex),+without editing your files.+Eg:+.IP+.EX+$ hledger bal \-\-alias checking=assets:bank:checking+$ hledger bal \-\-alias \(aq/\(haexpenses:(food|dining)/=expenses:food\(aq+.EE+.PP+It can be repeated to define more aliases.+These aliases affect all entries in all files (including CSV, timeclock+and timedot files), wherever the option appears on the command line; and+they are applied after any \f[CR]alias\f[R] directives or+\f[CR]alias:\f[R] tags (see Combining aliases).+They are not cleared by \f[CR]end aliases\f[R].+This makes \f[CR]\-\-alias\f[R] useful for trying out aliases+interactively, or for customising particular reports.+You can also put \f[CR]\-\-alias\f[R] options in a config file.+.SS Combining aliases+You can define as many aliases as you like, using journal directives+and/or command line options.+.PP+Recursive aliases \- where an account name is rewritten by one alias,+then by another alias, and so on \- are allowed.+Each alias sees the effect of previously applied aliases.+.PP+In such cases it can be important to understand which aliases will be+applied and in which order.+For (each account name in) each journal entry, we apply:+.IP "1." 3+\f[CR]alias\f[R] directives preceding the journal entry, most recently+parsed first (ie, reading upward from the journal entry, bottom to top)+.IP "2." 3+then any parent account from \f[CR]apply account\f[R] directives is+prepended+.IP "3." 3+then \f[CR]\-\-alias\f[R] options, in the order they appeared on the+command line (left to right).+.PP+In other words, for (an account name in) a given journal entry:+.IP \(bu 2+the nearest alias declaration before/above the entry is applied first+.IP \(bu 2+the next alias before/above that will be applied next, and so on+.IP \(bu 2+aliases defined after/below the entry do not affect it.+.PP+This gives nearby aliases precedence over distant ones, and helps+provide semantic stability \- aliases will keep working the same way+independent of which files are being read and in which order.+.PP+In case of trouble, adding \f[CR]\-\-debug=6\f[R] to the command line+will show which aliases are being applied when.+.SS Aliases and multiple files+As explained at Directive scopes, \f[CR]alias\f[R] directives (and+\f[CR]alias:\f[R] tags) do not affect parent or sibling files.+Eg in this command,+.IP+.EX+hledger \-f a.aliases \-f b.journal+.EE+.PP+account aliases defined in a.aliases will not affect b.journal.+Including the aliases doesn\(aqt work either:+.IP+.EX+include a.aliases++2023\-01\-01 ; not affected by a.aliases+ foo 1+ bar+.EE+.PP+This means that account aliases should usually be declared at the start+of your top\-most file, like this:+.IP+.EX+alias foo=Foo+alias bar=Bar++2023\-01\-01 ; affected by aliases above+ foo 1+ bar++include c.journal ; also affected+.EE+.PP+To affect all files read, whether they are included, or referenced by+\f[CR]\-f\f[R] or the \f[CR]import\f[R] command, use+\f[CR]\-\-alias\f[R] options (which could be in a config file).+Eg here the alias affects both a.journal and b.journal:+.IP+.EX+hledger \-f a.journal \-f b.journal \-\-alias foo=Foo+.EE+.SS \f[CR]end aliases\f[R] directive+This directive clears (forgets) all account aliases from+\f[CR]alias\f[R] directives and account \f[CR]alias:\f[R] tags seen so+far (but not aliases from command line \f[CR]\-\-alias\f[R] options):+.IP+.EX+end aliases+.EE+.SS Aliases can generate bad account names+Be aware that account aliases can produce malformed account names, which+could cause confusing reports or invalid \f[CR]print\f[R] output.+For example, you could erase all account names:+.IP+.EX+2021\-01\-01+ a:aa 1+ b+.EE+.IP+.EX+$ hledger print \-\-alias \(aq/.*/=\(aq+2021\-01\-01+ 1+.EE+.PP+The above \f[CR]print\f[R] output is not a valid journal.+Or you could insert an illegal double space, causing \f[CR]print\f[R]+output that would give a different journal when reparsed:+.IP+.EX+2021\-01\-01+ old 1+ other+.EE+.IP+.EX+$ hledger print \-\-alias old=\(dqnew USD\(dq | hledger \-f\- print+2021\-01\-01+ new USD 1+ other+.EE+.SS Aliases and account types+If an account with a type declaration (see Declaring accounts > Account+types) is renamed by an alias, normally the account type remains in+effect.+.PP+However, renaming in a way that reshapes the account tree (eg renaming+parent accounts but not their children, or vice versa) could prevent+child accounts from inheriting the account type of their parents.+.PP+Secondly, if an account\(aqs type is being inferred from its name,+renaming it by an alias could prevent or alter that.+.PP+If you are using account aliases and the \f[CR]type:\f[R] query is not+matching accounts as you expect, try troubleshooting with the accounts+command, eg something like:+.IP+.EX+$ hledger accounts \-\-types \-1 \-\-alias assets=bassetts+.EE+.SS \f[CR]assert\f[R] directive+In addition to the point\-in\-time balance assertions in transaction+entries, you can use \f[CR]assert\f[R] directives to declare more+general \f[B]journal assertions\f[R].+These are special queries asserting that certain report results do or do+not exist at specified times.+Like balance assertions, hledger checks these each time it reads the+journal, unless you use \f[CR]\-\-ignore\-assertions\f[R] or+\f[CR]\-I\f[R].+You can declare conditions or goals that you want to be upheld, and+whenever hledger reads the journal, if any rule is broken, it will+report an error.+Think \(dqguard rails for your finances\(dq.+(Note, a rule is only as good as its query, so test your new rules.)+.PP+The syntax is:+.IP+.EX+assert (none|some)[ PERIODEXPR][ QUERY]+.EE+.PP+Ie, the \f[CR]assert\f[R] keyword followed by \f[CR]none\f[R] or+\f[CR]some\f[R], then an optional period expression specifying when to+check the assertion, then a two\-or\-more\-spaces delimiter and a query+specifying which postings or report rows to look for.+The query is written as on the command line, with quotes around terms+containing spaces.+A \f[CR];\f[R] comment can follow.+.PP+A rule with a report interval can be followed by indented+\f[CR]skip\f[R] lines, each naming a date or period whose checks should+be skipped, with an optional comment (useful for recording the reason).+These skip checks, not data: postings in a skipped period still count in+later balances.+As usual, a range\(aqs end date is exclusive.+Eg:+.IP+.EX+assert none daily type:A balance:<0 ; no asset account is ever negative+ skip 2026\-03\-04..2026\-03\-08 ; transfer delayed by the bank holiday+ skip 2026\-05 ; moving house+.EE+.PP+A check is skipped if a date in a \f[CR]skip\f[R] line is among the+dates it examines.+For a rule with a \f[CR]balance:\f[R] term and no \f[CR]change:\f[R]+term, that is the period\(aqs last day (where its balance is tested);+for other rules, it\(aqs any day in the period.+.PP+Here are some examples.+(Aligning is optional; just remember to put at least two spaces before+each query.):+.IP+.EX+assert none ; no postings exist+assert some ; some postings exist++; journal maintenance+assert some desc:\(aqopening balances\(aq ; the journal has an opening balances entry+assert none assets:oldbank date:2025\- ; nothing is posted to a closed account+assert some assets:checking date:\(aq\-7 days..\(aq ; bank data has been imported/added recently++; income+assert some monthly to this month income:salary ; there\(aqs a salary transaction in each past month+assert none monthly to this month income:salary change:<2000 ; at least this much was earned in each past month+assert none monthly to this month income:salary change:>\-2000 ; a more careful signed test, handling contrabalances & sign typos+assert some monthly to this month desc:invoice any:\(aqreceivable amt:>0\(aq ; an invoice was sent in each past month+assert some monthly to this month desc:\(aqpayment for.*invoice\(aq ; an invoice payment was received in each past month+assert none assets:receivable balance:>15000 ; unpaid invoices are less than this, currently++; assets+assert none daily type:A balance:<0 ; no asset account is ever negative (at end of day), in any commodity+assert none daily assets:savings balance:<+10000 ; savings never drop below this much+assert some assets:savings balance:>=+20000 ; savings hold at least this much, currently+assert some monthly to this month not:tag:clopen assets:investments depth:2 change:>300 ; at least this much was invested in each past month (ignoring closing/opening entries)++; assets and liabilities+assert some taxes type:AL depth:0 balance:>0 ; estimated tax savings exceed estimated tax due, currently++; liabilities+assert some monthly to this month liabilities:card amt:>0 any:\(aqassets amt:<0\(aq ; a credit card payment was made in each past month+assert none monthly liabilities:card balance:<\-3000 ; no month ends with more than this much owed on the credit card+assert none liabilities:card balance:<\-500 ; current credit card balance is less than this++; expenses+assert none expenses:misc amt:>+10 ; no single misc expense is larger than this (in any currency)+assert none monthly expenses:dining change:>+$300 ; no month has more than this much $ dining expense+assert none monthly expenses:dining depth:2 change:>+$300 ; the same, but include subaccounts like expenses:dining:fine+.EE+.PP+Most query terms, like \f[CR]desc:\f[R], \f[CR]acct:\f[R], or+\f[CR]amt:\f[R], select postings.+\f[CR]balance:\f[R] and \f[CR]change:\f[R] terms instead test the+balance or change of the accounts those postings are in.+.SS How assert rules work+Assert rules are checked whenever the journal is read: by every command,+and by hledger\-ui and hledger\-web when they reload (unless disabled+with \f[CR]\-I\f[R]/\f[CR]\-\-ignore\-assertions\f[R], eg while you work+on a failing rule).+This happens after the journal is fully processed (after auto postings,+transaction balancing, balance assertions and lot calculation), so rules+see generated postings and lot subaccounts, and forecast transactions+when \f[CR]\-\-forecast\f[R] is used.+Rules are checked in the order they were read, and the first rule that+fails stops reading, with an error.+.PP+Their scope is the file tree: an assert rule sees all entries in the+main file and its included files, before and after it, but not entries+read by other \f[CR]\-f\f[R] options.+To check some extra rules without adding them to the journal, give them+to the check command as quoted arguments: eg+\f[CR]hledger check \(aqassert none daily type:A balance:<0\(aq\f[R].+.PP+Each rule is checked as if by a balance report,+\f[CR]hledger bal \-E QUERY\f[R], in four steps:+.IP "1." 3+\f[B]Select postings.\f[R] The query\(aqs ordinary terms select and+prepare postings as \f[CR]balance\f[R] would: costs are ignored (amounts+are summed in their original commodities), and \f[CR]depth:\f[R] clips+account names, merging subaccounts into their parent.+\f[CR]date:\f[R] terms don\(aqt select postings; they limit the report+period, like \f[CR]\-b\f[R]/\f[CR]\-e\f[R].+.IP "2." 3+\f[B]Calculate report rows.\f[R] The selected postings are summed by+account.+Each row has the account\(aqs change during the period, and its balance+at the end of the period (including all earlier postings, like+\f[CR]bal \-H\f[R]).+The rows are the accounts with selected postings in the period, plus,+when the query has a \f[CR]balance:\f[R] term, accounts with only+earlier postings (their change is zero but their balance may not be).+.IP "3." 3+\f[B]Filter rows.\f[R] \f[CR]change:\f[R] terms test each row\(aqs+change, and \f[CR]balance:\f[R] terms test its end balance; a query can+have both.+Without these terms every row matches, so the rule is simply about+whether any postings were selected.+.IP "4." 3+\f[B]Test.\f[R] \f[CR]none\f[R] passes if no row matches, and+\f[CR]some\f[R] passes if at least one does.+.PP+These steps are done at one or more checkpoints, in date order:+.IP \(bu 2+With no period expression, there is one checkpoint, covering the whole+journal (or the \f[CR]date:\f[R] terms\(aq span).+So \f[CR]balance:\f[R] tests the balances at the end of the journal, and+\f[CR]change:\f[R] tests the total change.+.IP \(bu 2+With a period expression, each of its periods is a checkpoint, and the+rule must pass at every one.+The periods are those \f[CR]bal\f[R] would show with that report+interval and \f[CR]\-b START \-e END\f[R].+Eg \f[CR]daily\f[R] checks each day\(aqs end balances or changes;+\f[CR]monthly from 2024\f[R] checks each month from 2024 on.+.IP \(bu 2+A period with no rows passes a \f[CR]none\f[R] rule and fails a+\f[CR]some\f[R] rule.+.IP \(bu 2+Relative dates in the period expression and query are resolved from+today\(aqs date, so a rule like+\f[CR]assert some assets:checking date:\(aq\-7 days..\(aq\f[R] can+start failing just because time passes.+.IP \(bu 2+Daily is the smallest checking interval (\f[CR]assert\f[R] does not+check after every transaction).+.PP+So you can check \(dqno asset account is ever negative (at end of+day)\(dq with \f[CR]assert none daily type:A balance:<0\f[R].+Without \f[CR]daily\f[R], only the final balances would be checked.+.PP+When a rule fails, the error shows the rule, every period in which it+failed, and up to 10 of the rows (or postings) which matched in those+periods.+Only the first failing rule is reported; others may be failing too.+.PP+These assertions have a cost: each rule makes reading the journal+slightly slower.+Rules matching few postings cost less, and \f[CR]balance:\f[R] rules+checked daily across many accounts cost more.+.SS Tips for writing assert rules+.IP \(bu 2+\f[B]\f[CB]none\f[B] gives more useful errors.\f[R] When you have a+choice, prefer \f[CR]none\f[R], because when it fails it shows the+offending rows, whereas a failing \f[CR]some\f[R] rule can only say+nothing matched.+.IP \(bu 2+\f[B]For more precise amount tests, add a sign and/or commodity.\f[R] A+plain number, as in \f[CR]balance:>100\f[R], ignores sign, and matches+if any commodity\(aqs amount does.+Often that is enough, but if you want to handle contrabalances or sign+typos, add a sign: \f[CR]balance:>+100\f[R].+And to limit the test to one commodity, add its symbol, as in+\f[CR]balance:<\-$5000\f[R], or add a \f[CR]cur:\f[R] term.+.IP \(bu 2+\f[B]Subaccounts are not included by default.\f[R] Each row\(aqs amount+is the account\(aqs own exclusive change or balance (like \f[CR]=\f[R]+in a balance assertion).+To include subaccount balances, limit the depth: eg+\f[CR]expenses:dining depth:2\f[R] folds \f[CR]expenses:dining\f[R]\(aqs+subaccounts into it.+(To fold just some accounts, use \f[CR]depth:REGEX=N\f[R].)+.IP \(bu 2+\f[B]\f[CB]depth:0\f[B] folds all matched accounts into one row.\f[R]+This lets you test two accounts of opposite sign against each other.+Eg \(dqsavings always cover the credit card debt\(dq is+\f[CR]assert none daily acct:\(aq\(ha(assets:savings|liabilities:card)\(aq depth:0 balance:<0\f[R].+.IP \(bu 2+\f[B]\f[CB]date:\f[B] terms combine with the period expression\(aqs+span.\f[R] Eg+\f[CR]assert none monthly assets date:2026\- balance:<0\f[R] means the+same as \f[CR]assert none monthly from 2026 assets balance:<0\f[R].+\f[CR]to thismonth\f[R] is useful for \(dqevery past month\(dq rules,+excluding the current incomplete month.+.IP \(bu 2+\f[B]Avoid \f[CB]not:date:\f[B] in rules with a \f[CB]balance:\f[B]+term.\f[R] It does not skip that date\(aqs check, it removes that+date\(aqs postings from all later balances.+Use \f[CR]skip\f[R] lines instead.+.IP \(bu 2+\f[B]Account names are matched after account aliases have been+applied\f[R], as in reports.+.SS \f[CR]comment\f[R] directive+A line containing just \f[CR]comment\f[R] causes all following lines to+be ignored, until an end comment directive or file end.+.SS \f[CR]end comment\f[R] directive+A line containing just \f[CR]end comment\f[R] ends the effect of a+preceding comment directive.+.SS \f[CR]commodity\f[R] directive+\f[CR]commodity\f[R] directives declare commodity symbols (for error+checking) and their preferred display style (digit group marks, decimal+digits, and symbol position).+Eg:+.IP+.EX+commodity $1,000.00+commodity 1000,00 EUR+commodity ₹ 1,00,00,000.00+commodity 1000. ; the no\-symbol commodity+.EE+.PP+The sample amount must include a decimal mark (even if there are no+decimal digits after it).+This tells the parser which decimal mark (period or comma) is used for+this commodity in the journal file, which can be useful in case of+ambiguous digit group marks.+This affects subsequent entries in the current file, its included files,+and the rest of any parent files (see directive scopes), and it can be+overridden by a \f[CR]decimal\-mark\f[R] directive.+.SS Commodity directive syntax+In more detail.+A commodity directive is normally the word \f[CR]commodity\f[R] followed+by a sample amount (only its format is significant), and optionally a+comment.+Eg:+.IP+.EX+commodity $1000.00+commodity 1.000,00 EUR+commodity 1 000 000.0000 ; the no\-symbol commodity+.EE+.PP+A commodity directive\(aqs sample amount must always include a decimal+mark (period or comma).+If you don\(aqt want to show any decimal digits, write the decimal mark+at the end:+.IP+.EX+commodity 1000. AAAA ; show AAAA with no decimals+.EE+.PP+Commodity symbols containing spaces, numbers, or punctuation must be+enclosed in double quotes, as usual:+.IP+.EX+commodity 1.0000 \(dqAAAA 2023\(dq+.EE+.PP+Commodity directives normally include a sample amount, but can declare+only a symbol (ie, just function 1 above):+.IP+.EX+commodity $+commodity INR+commodity \(dqAAAA 2023\(dq+commodity \(dq\(dq ; the no\-symbol commodity+.EE+.PP+Commodity directives may also be written with an indented+\f[CR]format\f[R] subdirective, as in Ledger.+The symbol is repeated and must be the same in both places.+Other subdirectives are ignored:+.IP+.EX+; display indian rupees with currency name on the left,+; thousands, lakhs and crores comma\-separated,+; period as decimal point, and two decimal places.+commodity INR+ format INR 1,00,00,000.00+ other subdirective ; ignored+.EE+.PP+A commodity can be declared more than once, eg in a main file and an+included file, or in several files read with \f[CR]\-f\f[R].+The later declaration will override or add to the earlier one, as+follows: its display style (if it has one) replaces the earlier style,+its tags take precedence over the earlier tags, and its aliases are+added to the earlier aliases.+(\(dqLater\(dq means later in the order hledger reads them: through each+file and its included files, then the next \f[CR]\-f\f[R] file.)+\f[CR]\-\-debug=1\f[R] shows any commodities which files read with+\f[CR]\-f\f[R] declare with different display styles.+.SS Commodity tags+A commodity directive\(aqs comment may contain tags.+These will be inherited by all postings using that commodity in their+main amount, except where the posting already has a value for that tag.+(A posting tag or an account tag overrides a commodity tag.)+Note, these tags will be queryable but won\(aqt be shown in+\f[CR]print\f[R] output, even with \-\-verbose\-tags.+.SS Commodity aliases+An \f[CR]alias:\f[R] tag on a commodity directive declares another+symbol/name for that commodity.+You can add several (quoting any that contain spaces or other special+characters, as usual):+.IP+.EX+commodity USD 1.00 ; alias: $, alias: US$, alias: \(dqus dollars\(dq+.EE+.PP+When hledger reads the journal, amounts written with an alias are+converted to the canonical commodity.+So they combine with it in reports, and a transaction can balance across+them.+This helps when, eg, your bank data, manual entries and downloaded+market prices use different symbols for the same currency.+Declare the symbol you want reports to show, and the others as its+aliases.+.PP+Some details:+.IP \(bu 2+\f[CR]print\f[R] shows amounts as they were written;+\f[CR]print \-x\f[R] shows them converted to the canonical commodity.+.IP \(bu 2+\f[CR]cur:\f[R] queries match the canonical symbol, not the aliases+(with the above declaration, \f[CR]$5\f[R] would be matched by+\f[CR]cur:USD\f[R], and not by \f[CR]cur:\(aq\(rs$\(aq\f[R]).+.IP \(bu 2+An alias can\(aqt have aliases of its own, and the same alias can\(aqt+be declared on two different commodities.+.SS Commodity units+A commodity alias can also specify a quantity.+Amounts written with the alias are divided by this quantity (and their+unit costs and market prices are multiplied by it).+This is useful for expressing differently\-sized units of a commodity.+Eg:+.IP+.EX+commodity 1.00 hrs ; alias: 60 min+commodity $1.00 ; alias: 0.001 K, alias: 0.000001 M+.EE+.PP+(Avoid decimal commas here, which would end the tag\(aqs value; use+\f[CR].\f[R], or exponential notation, \f[CR]alias: 1E\-6 M\f[R].)+.PP+You can report in any of these units, eg with \f[CR]\-X min\f[R] or+\f[CR]\-X M\f[R] (valuation, described later).+.PP+Note, these units keep the symbol placement they were declared with, but+inherit the canonical commodity\(aqs number format and+display/transaction\-balancing precisions.+If you want them to have a different display style, eg more decimals to+make small quantities visible, give them a \f[CR]commodity\f[R]+directive too:+.IP+.EX+commodity $1.00 ; alias: 0.001 K, alias: 0.000001 M+commodity 1.000 K+commodity 1.000000 M+.EE+.PP+When the conversion gives a repeating decimal (like 1/60 hour per+minute), it is stored internally at maximum precision (255 decimals, see+Amount arithmetic).+To keep costs and balance assertions exact, a unit cost on such an+amount is replaced by the exact total cost (\f[CR]10 min \(at $1\f[R]+becomes \f[CR]0.1666... hrs \(at\(at $10\f[R]), and balance assertions+add up the alias amounts before converting them (so three+\f[CR]10 min\f[R] amounts satisfy a \f[CR]= 0.5 hrs\f[R] assertion).+.SS Commodity aliases or market prices?+Both let you convert between symbols.+When should you use one or the other ?+.PP+Use a commodity alias when the symbols mean the same thing in different+names or units (\f[CR]$\f[R] and \f[CR]USD\f[R], \f[CR]min\f[R] and+\f[CR]hrs\f[R]).+The conversion happens always and automatically.+.PP+Use a \f[CR]P\f[R] directive when they are different things with an+exchange rate, even a fixed one.+The conversion happens only when you ask for it.+.SS Commodity alias scope+Commodity aliases (with or without a quantity) work in two ways, with+different scopes:+.IP \(bu 2+When hledger reads the journal, they convert the amounts written with+them, in their own file tree only (before or after the directive).+A file read with another \f[CR]\-f\f[R] option is a separate file tree,+so its amounts are not converted.+To share aliases between journals, put the \f[CR]commodity\f[R]+directives in a file which they all \f[CR]include\f[R] (or which+includes them all).+.IP \(bu 2+With \f[CR]\-X\f[R], they also act as fixed exchange rates in all file+trees, as a last resort when market prices can\(aqt do the conversion+(see Finding market price).+Eg \f[CR]\-X USD\f[R] can convert \f[CR]$\f[R] amounts in another file+tree that didn\(aqt declare that alias.+.SS Commodity error checking+In strict mode (\f[CR]\-s\f[R]/\f[CR]\-\-strict\f[R]) (or when you run+\f[CR]hledger check commodities\f[R]), hledger will report an error if+an undeclared commodity symbol is used (aliases count as declared).+There\(aqs one exception: zero amounts are always allowed to have no+commodity symbol.+.SS \f[CR]decimal\-mark\f[R] directive+You can use a \f[CR]decimal\-mark\f[R] directive to declare+unambiguously which character (period or comma) represents a decimal+mark, for all subsequent amounts in the current file and its included+files (see directive scopes).+This helps when parsing ambiguous numbers (like \f[CR]1.000\f[R] or+\f[CR]1,000\f[R] where you mean one thousand, not one).+It also makes hledger check that numbers use that decimal mark and no+other, which catches some typos and misparsed numbers.+With \f[CR]decimal\-mark ,\f[R], a number like \f[CR]1,000.00\f[R] is+reported as an error; and with \f[CR]decimal\-mark .\f[R], a number like+\f[CR]1.2.34\f[R] is reported as an error, instead of being read as+\f[CR]1234\f[R].+.PP+Eg, at the top of each journal file:+.IP+.EX+decimal\-mark .+.EE+.PP+or+.IP+.EX+decimal\-mark ,+.EE+.PP+This directive only affects parsing, and it takes precedence over+\f[CR]commodity\f[R] directives.+So you can declare preferred decimal marks for display, which may be+different from the decimal mark(s) used in the data files.+(The amounts in \f[CR]commodity\f[R] and \f[CR]D\f[R] directives are+allowed to use a different decimal mark.)+.PP+Without a \f[CR]decimal\-mark\f[R] directive, a \f[CR]commodity\f[R]+directive\(aqs decimal mark is used to interpret that commodity\(aqs+ambiguous numbers, but it is not enforced: numbers like+\f[CR]1.2.34\f[R] or \f[CR]1.000,00\f[R] (when the format is+\f[CR]1,000.00\f[R]) are accepted.+So if you want these checks, use \f[CR]decimal\-mark\f[R].+.SS \f[CR]include\f[R] directive+You can pull in the content of additional files by writing an include+directive, like this:+.IP+.EX+include SOMEFILE+.EE+.PP+This has the same effect as if SOMEFILE\(aqs content was inlined at this+point.+(With any include directives in SOMEFILE processed similarly,+recursively.)+.PP+Only journal files can include other files.+They can include journal, timeclock, timedot, CSV/SSV/TSV, or CSV rules+files.+.PP+When a CSV file is included, its rules file is \f[CR]FILE.rules\f[R]+alongside it, as usual; the \f[CR]\-\-rules\f[R] option is not used+here.+To use a different rules file, or a data file located elsewhere (eg in+your downloads directory), include a rules file which has a source rule+instead.+Transactions generated from included CSV data are treated like inlined+journal entries: they are placed at this point, any account aliases in+effect are applied to them, and their balance assertions are checked+along with the rest of the journal (unlike when reading a CSV file+directly, where balance assertions are ignored).+Other directives which affect journal parsing (like \f[CR]Y\f[R],+\f[CR]D\f[R], \f[CR]decimal\-mark\f[R], \f[CR]apply account\f[R]) do not+affect CSV data.+Note that if you include a CSV file in your main journal, you should not+also import it, or its transactions would be duplicated.+.PP+If the file path begins with a tilde, that means your home directory:+\f[CR]include \(ti/main.journal\f[R].+.PP+If it begins with a slash, it is an absolute path:+\f[CR]include /home/user/main.journal\f[R].+Otherwise it is relative to the including file\(aqs folder:+\f[CR]include ../finances/main.journal\f[R].+.PP+Also, the path may have a file type prefix to force a specific file+format, overriding the file extension(s) (as described in Data formats):+\f[CR]include timedot:notes/2023.md\f[R].+.PP+The path may contain glob patterns to match multiple files.+hledger\(aqs globs are similar to zsh\(aqs: \f[CR]?\f[R] to match any+character; \f[CR][a\-z]\f[R] to match any character in a range;+\f[CR]*\f[R] to match zero or more characters that aren\(aqt a path+separator (like \f[CR]/\f[R]); \f[CR]**\f[R] to match zero or more+subdirectories and/or zero or more characters at the start of a file+name; etc.+For convenience, \f[CR]include\f[R] always excludes the current file.+So, you can do+.IP \(bu 2+\f[CR]include *.journal\f[R] to include all other journal files in the+current directory (excluding dot files)+.IP \(bu 2+\f[CR]include **.journal\f[R] to include all other journal files in this+directory and below (excluding dot files and top\-level dot directories)+.IP \(bu 2+\f[CR]include timelogs/2???.timedot\f[R] to include all timedot files+named like a year number.+.PP+Note \f[CR]*\f[R] and \f[CR]**\f[R] usually won\(aqt match dot files or+dot directories, with one exception: \f[CR]**\f[R] does search+non\-top\-level dot directories.+If this causes problems, make your glob pattern more specific (eg+\f[CR]**.journal\f[R] instead of \f[CR]**\f[R]).+.PP+To see all the files being read, and which file includes each one, run+\f[CR]hledger files \-\-tree\f[R].+.PP+If you are using many, or deeply nested, include files, and have an+error that\(aqs hard to pinpoint: a good troubleshooting command is+\f[CR]hledger files \-\-debug=6\f[R] (or 7).+.SS \f[CR]P\f[R] directive+The \f[CR]P\f[R] directive declares a market price, which is a+conversion rate between two commodities on a certain date.+This allows value reports to convert amounts of one commodity to their+value in another, on or after that date.+These prices are often obtained from a stock exchange, cryptocurrency+exchange, or the foreign exchange market.+.PP+The format is:+.IP+.EX+P DATE COMMODITY1SYMBOL COMMODITY2AMOUNT+.EE+.PP+DATE is a simple date, COMMODITY1SYMBOL is the symbol of the commodity+being priced, and COMMODITY2AMOUNT is the amount (symbol and quantity)+of commodity 2 that one unit of commodity 1 is worth on this date.+Examples:+.IP+.EX+# one euro was worth $1.35 from 2009\-01\-01 onward:+P 2009\-01\-01 € $1.35++# and $1.40 from 2010\-01\-01 onward:+P 2010\-01\-01 € $1.40+.EE+.PP+The \f[CR]\-V\f[R], \f[CR]\-X\f[R] and \f[CR]\-\-value\f[R] flags use+these market prices to show amount values in another commodity.+See Value reporting.+.PP+.SS \f[CR]payee\f[R] directive+\f[CR]payee PAYEE NAME\f[R]+.PP+This directive can be used to declare a limited set of payees which may+appear in transaction descriptions.+The \(dqpayees\(dq check will report an error if any transaction refers+to a payee that has not been declared.+(This is quite a strict check, and not often used.)+.PP+Eg:+.IP+.EX+payee Whole Foods ; a comment+.EE+.PP+To declare the empty payee name, use \f[CR]\(dq\(dq\f[R].+.IP+.EX+payee \(dq\(dq+.EE+.PP+Payees do not support tags.+Any indented subdirectives are ignored.+.SS \f[CR]tag\f[R] directive+\f[CR]tag TAGNAME\f[R]+.PP+This directive can be used to declare a limited set of tag names allowed+in tags.+TAGNAME should be a valid tag name (no spaces).+Eg:+.IP+.EX+tag item\-id+.EE+.PP+Any indented subdirectives are ignored.+.PP+The \(dqtags\(dq check will report an error if any undeclared tag name+is used.+It is quite easy to accidentally create a tag through normal use of+colons in comments; if you want to prevent this, you can declare and+check your tags.+.SS Periodic transactions+The \f[CR]\(ti\f[R] directive declares a \(dqperiodic rule\(dq which+generates temporary extra transactions, usually recurring at some+interval, when hledger is run with the \f[CR]\-\-forecast\f[R] flag.+These \(dqforecast transactions\(dq are useful for forecasting future+activity.+They exist only at report time, when \f[CR]\-\-forecast\f[R] is used;+they are not saved in the journal file.+.PP+Periodic rules also have a second use: with the \f[CR]\-\-budget\f[R]+flag they set budget goals for budgeting.+.PP+Periodic rules can be a little tricky, so before you use them, read this+whole section, or at least the following tips:+.IP "1." 3+Two spaces accidentally added or omitted in the rule will cause you+trouble \- see below.+.IP "2." 3+For troubleshooting, show the generated transactions with+\f[CR]hledger print \-\-forecast tag:generated\f[R] or+\f[CR]hledger register \-\-forecast tag:generated\f[R].+.IP "3." 3+Forecasted transactions will begin only after the last non\-forecasted+transaction\(aqs date.+.IP "4." 3+Forecasted transactions will end 6 months from today, by default.+See below for the exact start/end rules.+.IP "5." 3+Period expressions with report intervals can be tricky; note how they+make start/end date adjustments.+.SS Periodic rule syntax+A periodic transaction rule looks like a normal journal entry, with the+date replaced by a tilde (\f[CR]\(ti\f[R]) followed by a period+expression (mnemonic: \f[CR]\(ti\f[R] looks like a recurring sine+wave.):+.IP+.EX+# every first of month+\(ti monthly+ expenses:rent $2000+ assets:bank:checking++# every 15th of month in 2023\(aqs second quarter:+\(ti monthly from 2023\-04\-15 to 2023\-06\-16+ expenses:utilities $400+ assets:bank:checking+.EE+.PP+The period expression is the same syntax used for specifying+multi\-period reports, just interpreted differently; there, it specifies+report periods; here it specifies recurrence dates (the periods\(aq+start dates).+.SS Periodic rules and relative dates+Partial or relative dates (like \f[CR]12/31\f[R], \f[CR]25\f[R],+\f[CR]tomorrow\f[R], \f[CR]last week\f[R], \f[CR]next quarter\f[R]) are+usually not recommended in periodic rules, since the results will change+as time passes.+If used, they will be interpreted relative to, in order of preference:+.IP "1." 3+the first day of the default year specified by a recent \f[CR]Y\f[R]+directive+.IP "2." 3+or the date specified with \f[CR]\-\-today\f[R]+.IP "3." 3+or the date on which you are running the report.+.PP+They will not be affected at all by report period or forecast period+dates.+.SS Two spaces between period expression and description!+If the period expression is followed by a transaction description, these+must be separated by \f[B]two or more spaces\f[R].+This helps hledger know where the period expression ends, so that+descriptions can not accidentally alter their meaning, as in this+example:+.IP+.EX+; 2 or more spaces needed here, so the period is not understood as \(dqevery 2 months in 2023\(dq+; ||+; vv+\(ti every 2 months in 2023, we will review+ assets:bank:checking $1500+ income:acme inc+.EE+.PP+So,+.IP \(bu 2+Do write two spaces between your period expression and your transaction+description, if any.+.IP \(bu 2+Don\(aqt accidentally write two spaces in the middle of your period+expression.+.SS Auto postings+The \f[CR]=\f[R] directive declares an \(dqauto posting rule\(dq, which+adds extra postings to existing transactions.+(Remember, postings are the account name & amount lines below a+transaction\(aqs date & description.)+.PP+In the journal, an auto posting rule looks quite like a transaction, but+instead of date and description it has \f[CR]=\f[R] (mnemonic:+\(dqmatch\(dq) and a query, like this:+.IP+.EX+= QUERY+ ACCOUNT AMOUNT+ ...+.EE+.PP+Queries are just like command line queries; an account name substring is+most common.+Query terms containing spaces should be enclosed in single or double+quotes.+.PP+Each \f[CR]=\f[R] rule works like this: when hledger is run with the+\f[CR]\-\-auto\f[R] flag, wherever the QUERY matches a posting in the+journal, the rule\(aqs postings are added to that transaction,+immediately below the matched posting.+Note these generated postings are temporary, existing only for the+duration of the report, and only when \f[CR]\-\-auto\f[R] is used; they+are not saved in the journal file by hledger.+.PP+The postings can contain the special string \f[CR]%account\f[R] which+will be expanded to the account name of the matched account.+.PP+Generated postings\(aq amounts can depend on the matched posting\(aqs+amount.+So auto postings can be useful for, eg, adding tax postings with a+standard percentage.+AMOUNT can be:+.IP \(bu 2+a number with no commodity symbol, like \f[CR]2\f[R].+The matched posting\(aqs commodity symbol will be added to this.+.IP \(bu 2+a normal amount with a commodity symbol, like \f[CR]$2\f[R].+This will be used as\-is.+.IP \(bu 2+an asterisk followed by a number, like \f[CR]*2\f[R].+This will multiply the matched posting\(aqs amount (and total price, if+any) by the number.+.IP \(bu 2+an asterisk followed by an amount with commodity symbol, like+\f[CR]*$2\f[R].+This multiplies and also replaces the commodity symbol with this new+one.+.PP+Some examples:+.IP+.EX+; every time I buy food, schedule a dollar donation+= expenses:food+ (liabilities:charity) $\-1++; when I buy a gift, also deduct that amount from a budget envelope subaccount+= expenses:gifts+ assets:checking:gifts *\-1+ assets:checking *1++2017/12/1+ expenses:food $10+ assets:checking++2017/12/14+ expenses:gifts $20+ assets:checking+.EE+.IP+.EX+$ hledger print \-\-auto+2017\-12\-01+ expenses:food $10+ assets:checking+ (liabilities:charity) $\-1++2017\-12\-14+ expenses:gifts $20+ assets:checking+ assets:checking:gifts \-$20+ assets:checking $20+.EE+.PP+Note that depending fully on generated data such as this has some+drawbacks \- it\(aqs less portable, less future\-proof, less auditable+by others, and less robust (eg your balance assertions will depend on+whether you use or don\(aqt use \f[CR]\-\-auto\f[R]).+An alternative is to use auto postings in \(dqone time\(dq fashion \-+use them to help build a complex journal entry, view it with+\f[CR]hledger print \-\-auto\f[R], and then copy that output into the+journal file to make it permanent.+.SS Auto postings and multiple files+An auto posting rule can affect any transaction in the current file, or+in any parent file or child file.+Note, currently it will not affect sibling files (when multiple+\f[CR]\-f\f[R]/\f[CR]\-\-file\f[R] are used \- see #1212).+.SS Auto postings and dates+A posting date (or secondary date) in the matched posting, or (taking+precedence) a posting date in the auto posting rule itself, will also be+used in the generated posting.+.SS Auto postings and transaction balancing / inferred amounts / balance assertions+Currently, auto postings are added:+.IP \(bu 2+after missing amounts are inferred, and transactions are checked for+balancedness,+.IP \(bu 2+but before balance assertions are checked.+.PP+Note this means that journal entries must be balanced both before and+after auto postings are added.+.PP+This also means that you cannot have more than one auto\-posting with a+missing amount applied to a given transaction, as it will be unable to+infer amounts.+.SS Auto posting tags+Automated postings will have some extra tags:+.IP \(bu 2+\f[CR]generated\-posting:= QUERY\f[R] \- shows this was generated by an+auto posting rule, and the query+.IP \(bu 2+\f[CR]_generated\-posting:= QUERY\f[R] \- a hidden tag, which does not+appear in hledger\(aqs output.+This can be used to match postings generated \(dqjust now\(dq, rather+than generated in the past and saved to the journal.+.PP+Also, any transaction that has been changed by auto posting rules will+have these tags added:+.IP \(bu 2+\f[CR]modified:\f[R] \- this transaction was modified+.IP \(bu 2+\f[CR]_modified:\f[R] \- a hidden tag not appearing in the comment; this+transaction was modified \(dqjust now\(dq.+.SS Auto postings on forecast transactions only+Tip: you can can make auto postings that will apply to forecast+transactions but not recorded transactions, by adding+\f[CR]tag:_generated\-transaction\f[R] to their QUERY.+This can be useful when generating new journal entries to be saved in+the journal.+.SS Other syntax+hledger journal format supports quite a few other features, mainly to+make interoperating with or converting from Ledger easier.+Note some of the features below are powerful and can be useful in+special cases, but in general, features in this section are considered+less important or even not recommended for most users.+Downsides are mentioned to help you decide if you want to use them.+.SS Amount expressions+AKA \(dqinline math\(dq.+\f[I]Since 1.99.6\f[R]+.PP+A posting amount can also be a simple arithmetic expression, which+hledger calculates when reading the journal.+This saves doing sums by hand, and records how an amount was arrived at:+.IP+.EX+2026\-03\-02 groceries, two receipts+ assets:checking+ expenses:food $50.20 + $16.54 ; $66.74++2026\-03\-05 laptop, plus 5% sales tax+ liabilities:card+ expenses:equipment $800.00+ expenses:tax $800.00 * 0.05 ; $40.00++2026\-03\-07 hardware store, 3 boxes of screws less a $2 coupon+ liabilities:card+ expenses:supplies 3 * $4.99 \- $2 ; $12.97+.EE+.PP+Downsides: Complicates standard bookkeeping notation; could obscure a+posting\(aqs true amount.+Makes it harder for other apps to read your journal.+.SS Amount expression syntax+.IP \(bu 2+You can use \f[CR]+\f[R], \f[CR]\-\f[R], \f[CR]*\f[R], \f[CR]/\f[R] and+parentheses.+\f[CR]*\f[R] and \f[CR]/\f[R] are done before \f[CR]+\f[R] and+\f[CR]\-\f[R]; otherwise it\(aqs left to right.+A minus sign can also go before parentheses, eg \f[CR]\-($1 + $2)\f[R].+.IP \(bu 2+Spaces around the operators are optional, except that a \f[CR]/\f[R]+right after a commodity symbol needs a space before it:+\f[CR]10 EUR / 4\f[R] works, \f[CR]10 EUR/4\f[R] is an error.+.IP \(bu 2+\f[CR]+\f[R] and \f[CR]\-\f[R] need amounts in the same commodity.+You can write the commodity just once, since a plain number takes the+other side\(aqs commodity: \f[CR]$10 + 5\f[R] is $15.+.IP \(bu 2+\f[CR]*\f[R] and \f[CR]/\f[R] need a plain number on at least one side,+eg \f[CR]$800.00 * 0.05\f[R], \f[CR]3 * $4.99\f[R] or+\f[CR]$100.00 / 3\f[R].+The result is in the other side\(aqs commodity.+So a plain number divided by an amount is in that amount\(aqs commodity,+as in Ledger; this is handy for inverting an exchange rate:+\f[CR]1 / 1.25 EUR\f[R] is 0.80 EUR.+.IP \(bu 2+A cost, lot annotation or balance assertion can follow an expression,+and applies to its result: \f[CR]10 EUR + 5 EUR \(at $1.10\f[R] is 15+EUR, costing $1.10 each.+.IP \(bu 2+A cost can be an expression too, eg \f[CR]1 GBP \(at (1 / 1.14 EUR)\f[R]+or \f[CR]3 AAPL \(at\(at $450 + $5\f[R].+.IP \(bu 2+Expressions can be used only in posting amounts (in journal format, or+in CSV rules) and transacted costs, not in cost basis annotations,+balance assertions, directives, or auto posting rule multipliers+(\f[CR]*AMT\f[R]).+.SS Amount expression rounding+The result of \f[CR]+\f[R] or \f[CR]\-\f[R] is exact, and shows as many+decimal places as the more precise of the two amounts.+.PP+The result of \f[CR]*\f[R] or \f[CR]/\f[R] is rounded, using banker\(aqs+rounding, to the entry\(aqs decimal places for that commodity: the most+decimal places written in that commodity\(aqs amounts in the entry,+including amounts inside expressions or balance assignments, but not+cost amounts, or the plain numbers used with \f[CR]*\f[R] or+\f[CR]/\f[R].+These are the same decimal places hledger uses to check that the entry+balances (see Transaction balancing).+So:+.IP \(bu 2+\f[CR]$100/3\f[R] is $33.33 in an entry that also has+\f[CR]$\-100.00\f[R], but $33 when all of the entry\(aqs dollar amounts+are whole numbers.+.IP \(bu 2+\f[CR]$10 * 0.15\f[R] on its own is $2; write \f[CR]$10.00 * 0.15\f[R]+to get $1.50.+.IP \(bu 2+For more decimal places, write more: \f[CR]$100.0000 / 3\f[R] is+$33.3333.+.IP \(bu 2+In periodic transaction rules and auto posting rules, a result is+rounded to its own decimal places, eg \f[CR]$100/3\f[R] is $33 and+\f[CR]$100.00/3\f[R] is $33.33.+.IP \(bu 2+A result with no commodity gets the default commodity from a+\f[CR]D\f[R] directive, if any, as usual.+It is then like any other plain number after a \f[CR]D\f[R] directive,+whose decimal places count: after \f[CR]D $1,000.00\f[R],+\f[CR]5 / 2\f[R] is $2.50.+.PP+A cost calculated with \f[CR]*\f[R] or \f[CR]/\f[R] is not rounded,+since a rounded rate could be far off (\f[CR]$10 / 1.14\f[R] would be+$9).+hledger keeps it exact, and shows it with all its decimal places, or 8+if it\(aqs a repeating decimal (more if written), eg+\f[CR]1 GBP \(at $10 / 1.14\f[R] prints as+\f[CR]1 GBP \(at $8.77192982\f[R].+.PP+The rounded amount is what hledger stores (see also Where hledger+divides).+So a split that doesn\(aqt divide evenly leaves the entry unbalanced,+and the error message says that such amounts are rounded.+To fix it, leave one amount blank, and hledger will give it the+remainder:+.IP+.EX+2026\-03\-09 dinner with Ana and Raj, split three ways+ liabilities:card $\-107.00+ assets:receivable:ana ($92.00 + $15.00) / 3 ; $35.67+ assets:receivable:raj ($92.00 + $15.00) / 3 ; $35.67+ expenses:food ; $35.66+.EE+.SS Amount expressions are not kept+hledger keeps only an expression\(aqs result.+\f[CR]print\f[R] (including \f[CR]\-\-export\f[R], and all its output+formats), other reports and error messages show the result, eg+\f[CR]$66.74\f[R], not \f[CR]$50.20 + $16.54\f[R].+If you need to keep the parts visible, write them in a comment too.+.SS Balance assignments+Ledger\-style balance assignments are also supported.+These are like balance assertions, but with no posting amount on the+left side of the equals sign; instead it is calculated automatically so+as to satisfy the assertion.+This can be a convenience during data entry, eg when setting opening+balances:+.IP+.EX+; starting a new journal, set asset account balances+2016/1/1 opening balances+ assets:checking = $409.32+ assets:savings = $735.24+ assets:cash = $42+ equity:opening balances+.EE+.PP+or when adjusting a balance to reality:+.IP+.EX+; no cash left; update balance, record any untracked spending as a generic expense+2016/1/15+ assets:cash = $0+ expenses:misc+.EE+.PP+The calculated amount depends on the account\(aqs balance in the+commodity at that point (which depends on the previously\-dated postings+of the commodity to that account since the last balance assertion or+assignment).+.PP+Downsides: using balance assignments makes your journal less explicit;+to know the exact amount posted, you have to run hledger or do the+calculations yourself, instead of just reading it.+Also balance assignments\(aq forcing of balances can hide errors.+These things make your financial data less portable, less future\-proof,+and less trustworthy in an audit.+.SS Balance assignments and costs+A cost in a balance assignment will cause the calculated amount to have+that cost attached:+.IP+.EX+2019/1/1+ (a) = $1 \(at €2+.EE+.IP+.EX+$ hledger print \-\-explicit+2019\-01\-01+ (a) $1 \(at €2 = $1 \(at €2+.EE+.SS Balance assignments and subaccounts+Subaccount\-inclusive balance assignments (\f[CR]=*\f[R] or+\f[CR]==*\f[R]) are also supported.+The calculated amount is posted to the account named, making its balance+including subaccounts equal the assigned balance; the subaccounts\(aq+balances are not changed.+\f[CR]=*\f[R] sets the balance in just the assigned commodity, while+\f[CR]==*\f[R] also clears any other commodities.+.IP+.EX+2026\-01\-01+ liabilities:card $\-30+ liabilities:loan $\-200+ expenses++2026\-01\-15 a windfall pays off all liabilities+ liabilities ==* $0+ income:windfall+.EE+.IP+.EX+$ hledger print \-\-explicit date:2026\-01\-15+2026\-01\-15 a windfall pays off all liabilities+ liabilities $230 ==* $0+ income:windfall $\-230++$ hledger bal liabilities+ $230 liabilities+ $\-30 liabilities:card+ $\-200 liabilities:loan+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ 0 +.EE+.SS Balance assignments and multiple files+Balance assignments handle multiple files like balance assertions.+They see balance from other files previously included from the current+file, but not from previous sibling or parent files.+.SS Bracketed posting dates+For setting posting dates and secondary posting dates, Ledger\(aqs+bracketed date syntax is also supported: \f[CR][DATE]\f[R],+\f[CR][DATE=DATE2]\f[R] or \f[CR][=DATE2]\f[R] in posting comments.+hledger will attempt to parse any square\-bracketed sequence of the+\f[CR]0123456789/\-.=\f[R] characters in this way.+With this syntax, DATE infers its year from the transaction and DATE2+infers its year from DATE.+.PP+Downsides: another syntax to learn, redundant with hledger\(aqs+\f[CR]date:\f[R]/\f[CR]date2:\f[R] tags, and confusingly similar to+Ledger\(aqs lot date syntax.+.SS \f[CR]D\f[R] directive+\f[CR]D AMOUNT\f[R]+.PP+This directive sets a default commodity, to be used for any subsequent+commodityless amounts (ie, plain numbers) seen while parsing the+journal.+This affects subsequent entries until the next \f[CR]D\f[R] directive,+or the end of the current file (including its included files; see+directive scopes).+.PP+For compatibility/historical reasons, \f[CR]D\f[R] also acts like a+\f[CR]commodity\f[R] directive (setting the commodity\(aqs decimal mark+for parsing and display style for output).+So its argument is not just a commodity symbol, but a full amount+demonstrating the style.+The amount must include a decimal mark (either period or comma).+Eg:+.IP+.EX+; commodity\-less amounts should be treated as dollars+; (and displayed with the dollar sign on the left, thousands separators and two decimal places)+D $1,000.00++1/1+ a 5 ; <\- commodity\-less amount, parsed as $5 and displayed as $5.00+ b+.EE+.PP+Interactions with other directives:+.PP+For setting a commodity\(aqs display style, a \f[CR]commodity\f[R]+directive has highest priority, then a \f[CR]D\f[R] directive.+.PP+For detecting a commodity\(aqs decimal mark during parsing,+\f[CR]decimal\-mark\f[R] has highest priority, then+\f[CR]commodity\f[R], then \f[CR]D\f[R].+.PP+For checking commodity symbols with the check command, a+\f[CR]commodity\f[R] directive is required+(\f[CR]hledger check commodities\f[R] ignores \f[CR]D\f[R] directives).+.PP+Downsides: omitting commodity symbols makes your financial data less+explicit, less portable, and less trustworthy in an audit.+It is usually an unsustainable shortcut; sooner or later you will want+to track multiple commodities.+D is overloaded with functions redundant with \f[CR]commodity\f[R] and+\f[CR]decimal\-mark\f[R].+And it works differently from Ledger\(aqs \f[CR]D\f[R].+.SS \f[CR]apply account\f[R] directive+This directive sets a default parent account, which will be prepended to+all accounts in following entries, until an \f[CR]end apply account\f[R]+directive or end of current file.+Eg:+.IP+.EX+apply account home++2010/1/1+ food $10+ cash++end apply account+.EE+.PP+is equivalent to:+.IP+.EX+2010/01/01+ home:food $10+ home:cash $\-10+.EE+.PP+(If the parent account name ends with a colon+(\f[CR]apply account home:\f[R]), it is ignored, as in Ledger.)+.PP+\f[CR]account\f[R] directives are also affected, and so is any+\f[CR]include\f[R]d content.+.PP+Account names entered via hledger add or hledger\-web are not affected.+.PP+Account aliases from \f[CR]alias\f[R] directives are applied before the+parent account is prepended (as in Ledger), so they match the account+names as written.+This means a file\(aqs aliases keep working when it is included under+\f[CR]apply account\f[R].+(Before hledger 2, they were applied after.)+\f[CR]\-\-alias\f[R] options are applied after the parent account is+prepended, so they match the full account names.+.PP+Downsides: this can make your financial data less explicit, less+portable, and less trustworthy in an audit.+.SS \f[CR]Y\f[R] directive+\f[CR]Y YEAR\f[R]+.PP+or (deprecated backward\-compatible form):+.PP+\f[CR]year YEAR\f[R]+.PP+The space is optional.+This sets a default year to be used for subsequent dates which don\(aqt+specify a year.+Eg:+.IP+.EX+Y2009 ; set default year to 2009++12/15 ; equivalent to 2009/12/15+ expenses 1+ assets++year 2010 ; change default year to 2010++2009/1/30 ; specifies the year, not affected+ expenses 1+ assets++1/31 ; equivalent to 2010/1/31+ expenses 1+ assets+.EE+.PP+Downsides: omitting the year (from primary transaction dates, at least)+makes your financial data less explicit, less portable, and less+trustworthy in an audit.+Such dates can get separated from their corresponding Y directive, eg+when evaluating a region of the journal in your editor.+A missing Y directive makes reports dependent on today\(aqs date.+.SS \f[CR]apply year\f[R] directive+\f[CR]apply year YEAR\f[R] sets a default year like \f[CR]Y\f[R], but+only until a matching \f[CR]end apply year\f[R] directive (or the end of+the current file).+\f[CR]end apply year\f[R] restores the default year that was in effect+before the matching \f[CR]apply year\f[R].+These blocks can be nested, as in Ledger (which also lets a bare+\f[CR]end\f[R] or \f[CR]end apply\f[R] close them; hledger requires+\f[CR]end apply year\f[R]).+Eg:+.IP+.EX+Y 2009++apply year 2010+1/31 ; 2010\-01\-31+ expenses 1+ assets+end apply year++2/28 ; 2009\-02\-28+ expenses 1+ assets+.EE+.PP+An \f[CR]end apply year\f[R] with no matching \f[CR]apply year\f[R] is+an error.+(Before hledger 2, \f[CR]apply year\f[R] worked like \f[CR]Y\f[R], and+\f[CR]end apply year\f[R] was ignored.)+.SS Secondary dates+A secondary date is written after the primary date, following an equals+sign: \f[CR]DATE1=DATE2\f[R].+If the year is omitted, the primary date\(aqs year is assumed.+When running reports, the primary (left side) date is used by default,+but with the \f[CR]\-\-date2\f[R] flag (\f[CR]\-\-aux\-date\f[R]+or\f[CR]\-\-effective\f[R] also work, for Ledger users), the secondary+(right side) date will be used instead.+.PP+The meaning of secondary dates is up to you.+Eg it could be \(dqprimary is the bank\(aqs clearing date, secondary is+the date the transaction was initiated, if different\(dq.+.PP+In practice, this feature usually adds confusion:+.IP \(bu 2+You have to remember the primary and secondary dates\(aq meaning, and+follow that consistently.+.IP \(bu 2+It splits your bookkeeping into two modes, and you have to remember+which mode is appropriate for a given report.+.IP \(bu 2+Usually your balance assertions will work with only one of these modes.+.IP \(bu 2+It makes your financial data more complicated, less portable, and less+clear in an audit.+.IP \(bu 2+It interacts with every feature, creating an ongoing cost for+implementors.+.IP \(bu 2+It distracts new users and supporters.+.IP \(bu 2+Posting dates are simpler and work better.+.PP+So secondary dates are officially deprecated in hledger, remaining only+as a Ledger compatibility aid; we recommend using posting dates instead.+.SS Star comments+Lines beginning with \f[CR]*\f[R] (star/asterisk) are also comment+lines, for Ledger compatibility.+Emacs users can use these as foldable org headings.+(But it\(aqs usually better to use ledger\-mode, and add outshine minor+mode for org\-like folding.)+.SS Valuation expressions+Ledger allows a valuation function or value to be written in double+parentheses after an amount.+hledger ignores these.+.SS Virtual postings+A posting with parentheses around the account name, like+\f[CR](some:account) 10\f[R], is called an \f[I]unbalanced virtual+posting\f[R].+These postings do not participate in transaction balancing.+(And if you write them without an amount, a zero amount is always+inferred.)+These can occasionally be convenient for special circumstances, but they+violate double entry bookkeeping and make your data less portable across+applications, so many people avoid using them at all.+.PP+A posting with brackets around the account name+(\f[CR][some:account]\f[R]) is called a \f[I]balanced virtual+posting\f[R].+The balanced virtual postings in a transaction must add up to zero, just+like ordinary postings, but separately from them.+These are not part of double entry bookkeeping either, but they are at+least balanced.+An example:+.IP+.EX+2022\-01\-01 buy food with cash, update budget envelope subaccounts, & something else+ assets:cash $\-10 ; <\- these balance each other+ expenses:food $7 ; <\-+ expenses:food $3 ; <\-+ [assets:checking:budget:food] $\-10 ; <\- and these balance each other+ [assets:checking:available] $10 ; <\-+ (something:else) $5 ; <\- this is not required to balance+.EE+.PP+Ordinary postings, whose account names are neither parenthesised nor+bracketed, are called \f[I]real postings\f[R].+You can exclude virtual postings from reports with the+\f[CR]\-R/\-\-real\f[R] flag or a \f[CR]real:1\f[R] query.+.SS Other Ledger directives+These other Ledger directives are currently accepted but ignored.+This allows hledger to read more Ledger files, but be aware that+hledger\(aqs reports may differ from Ledger\(aqs if you use these.+.IP+.EX+apply fixed COMM AMT+apply tag TAG+bucket / A ACCT+capture ACCT REGEX+check EXPR+define VAR=EXPR+end apply fixed+end apply tag+end tag+eval / expr EXPR+python+ PYTHONCODE+tag NAME+value EXPR+\-\-command\-line\-flags+.EE+.PP+Ledger\(aqs \f[CR]assert EXPR\f[R] directive is not supported:+\f[CR]assert\f[R] is hledger\(aqs assert directive, which has a+different syntax, so a Ledger\-style \f[CR]assert\f[R] line is an error.+.PP+See also https://hledger.org/ledger.html for a detailed hledger/Ledger+syntax comparison.+.SS Ledger virtual costs+In Ledger, \f[CR](\(at) UNITCOST\f[R] and+\f[CR](\(at\(at) TOTALCOST\f[R] are virtual costs, which do not generate+market prices.+In hledger, these are equivalent to \f[CR]\(at\f[R] and+\f[CR]\(at\(at\f[R].+.SS Ledger cost basis+In Ledger, these annotations after an amount help specify or select a+lot\(aqs cost basis: \f[CR]{LOTUNITCOST}\f[R] or+\f[CR]{{LOTTOTALCOST}}\f[R], \f[CR][LOTDATE]\f[R], and/or+\f[CR](LOTNOTE)\f[R].+hledger will read these, as an alternative to its own cost basis syntax.+.PP+We also read Ledger\(aqs fixed price syntax, \f[CR]{=LOTUNITCOST}\f[R]+or \f[CR]{{=LOTTOTALCOST}}\f[R], treating it as equivalent to+\f[CR]{LOTUNITCOST}\f[R] or \f[CR]{{LOTTOTALCOST}}\f[R].+.PP+.SH CSV+hledger can read transactions from CSV (comma\-separated values) files.+More precisely, it can read DSV (delimiter\-separated values), from a+file or standard input.+Comma\-separated, semicolon\-separated and tab\-separated are the most+common variants, and hledger recognises these three automatically from+the file extension.+.PP+(To learn about producing CSV or TSV \f[I]output\f[R], see Output+format.)+.PP+Each CSV file must be described by a corresponding \f[I]rules file\f[R].+This contains rules describing the CSV data (header line, fields layout,+date format etc.), how to construct hledger transactions from it, and+how to categorise transactions based on description or other attributes.+.PP+By default, hledger expects this rules file to be named like the CSV+file, with an extra \f[CR].rules\f[R] extension added, in the same+directory.+Eg when asked to read \f[CR]foo/FILE.csv\f[R], hledger looks for+\f[CR]foo/FILE.csv.rules\f[R].+You can specify a different rules file with the \f[CR]\-\-rules\f[R]+option (for CSV files specified on the command line; not for ones+included by a journal file).+.PP+At minimum, the rules file must identify the date and amount fields, and+often it also specifies the date format and how many header lines there+are.+Here\(aqs a simple CSV file and a rules file for it:+.IP+.EX+Date, Description, Id, Amount+12/11/2019, Foo, 123, 10.23+.EE+.IP+.EX+# basic.csv.rules+skip 1+fields date, description, , amount+date\-format %d/%m/%Y+.EE+.IP+.EX+$ hledger print \-f basic.csv+2019\-11\-12 Foo+ expenses:unknown 10.23+ income:unknown \-10.23+.EE+.PP+Or you can read the rules file itself, if it has a \f[CR]source\f[R]+rule saying where the data is (eg \f[CR]source ./basic.csv\f[R]):+\f[CR]hledger print \-f basic.csv.rules\f[R].+This is the usual setup for regular importing; see Finding the data.+.PP+There\(aqs an introductory Tutorial: Import CSV data on hledger.org, and+more CSV rules examples below, and a larger collection at+https://github.com/hledgerorg/hledger/tree/main/examples/csv.+.SS CSV rules cheatsheet+The following kinds of rule can appear in the rules file, in any order.+(Blank lines and lines beginning with \f[CR]#\f[R] or \f[CR];\f[R] are+ignored.)+.PP+.TS+tab(@);+lw(24.7n) lw(45.3n).+T{+\f[B]\f[CB]source\f[B]\f[R]+T}@T{+optionally declare which file to read data from+T}+T{+\f[B]\f[CB]archive\f[B]\f[R]+T}@T{+optionally enable an archive of imported files+T}+T{+\f[B]\f[CB]separator\f[B]\f[R]+T}@T{+declare the field separator, instead of relying on file extension+T}+T{+\f[B]\f[CB]encoding\f[B]\f[R]+T}@T{+optionally declare which text encoding the data has+T}+T{+\f[B]\f[CB]skip\f[B]\f[R]+T}@T{+skip header line(s) at start of file, or (inside an if rule) the current+record(s)+T}+T{+\f[B]\f[CB]date\-format\f[B]\f[R]+T}@T{+declare how to parse CSV dates/date\-times+T}+T{+\f[B]\f[CB]timezone\f[B]\f[R]+T}@T{+declare the time zone of ambiguous CSV date\-times+T}+T{+\f[B]\f[CB]decimal\-mark\f[B]\f[R]+T}@T{+declare the decimal mark used in CSV amounts, when ambiguous+T}+T{+\f[B]\f[CB]newest\-first\f[B]\f[R]+T}@T{+improve txn order when: there are multiple records, newest first, all+with the same date+T}+T{+\f[B]\f[CB]intra\-day\-reversed\f[B]\f[R]+T}@T{+improve txn order when: same\-day txns are in opposite order to the+overall file+T}+T{+\f[B]\f[CB]fields\f[B]\f[R]+T}@T{+name CSV fields for easy reference, and optionally assign their values+to hledger fields+T}+T{+\f[B]Field assignment\f[R]+T}@T{+assign a CSV value or interpolated text value to a hledger field+T}+T{+\f[B]\f[CB]balance\-type\f[B]\f[R]+T}@T{+select which type of balance assertions/assignments to generate+T}+T{+\f[B]\f[CB]if\f[B]\f[R]+T}@T{+conditionally assign values to hledger fields, or skip one or more+records+T}+T{+\f[B]\f[CB]ifs\f[B]\f[R]+T}@T{+declare multiple if rules in a compact table format+T}+T{+\f[B]\f[CB]end\f[B]\f[R]+T}@T{+(inside an if rule) skip the current and all remaining records+T}+T{+\f[B]\f[CB]merge\f[B]\f[R]+T}@T{+combine this record with the next one(s), to be converted to a single+transaction+T}+T{+\f[B]\f[CB]include\f[B]\f[R]+T}@T{+inline another CSV rules file+T}+.TE+.PP+Working with CSV tips and How CSV rules are evaluated can be found+below.+.SS Finding the data+You can name a CSV file on the command line, as in+\f[CR]hledger \-f foo.csv CMD\f[R], and hledger will use the rules file+named like it (\f[CR]foo.csv.rules\f[R]).+.PP+Or you can name the rules file, as in+\f[CR]hledger \-f foo.csv.rules CMD\f[R].+The rules file must then have a \f[CR]source\f[R] rule (described+below), saying which data file to read (perhaps in your web browser\(aqs+download directory), or which command to run to get the data.+.PP+The second way is more powerful.+This and the archive rule below, and the default behaviour of the get+and import commands, help remove the busywork of managing CSV downloads.+Ideally, you can periodically+.IP "1." 3+Download new CSVs from your banks (perhaps by just running+\f[CR]hledger get\f[R]).+.IP "2." 3+Import new transactions from all the CSVs specified by rules files in+\f[CR]rules/\f[R], by just running \f[CR]hledger import\f[R].+.PP+Or, do both with one command: \f[CR]hledger import \-g\f[R]+.PP+After import, you can discard the CSV immediately, or leave it where it+is for a while, or archive it automatically (to+\f[CR]data/archive/\f[R]) with the archive rule.+.PP+It\(aqs also possible to include a CSV file or rules file in your+journal, in which case there\(aqs no import step at all; instead, the+whole CSV is reconverted on each run.+.SS \f[CR]source\f[R]+When hledger reads a rules file (\f[CR]\-f foo.csv.rules\f[R]), the+\f[CR]source\f[R] rule says which data file to read (it is ignored if+you name the data file instead, as in \f[CR]\-f foo.csv\f[R]):+.IP+.EX+source ./Checking1.csv+.EE+.PP+If the file does not exist, it is just considered empty, without raising+an error.+.PP+A rules file (and any included rules file) can have only one+\f[CR]source\f[R] rule.+To read several data files, use a rules file for each; they can include+their common rules.+.PP+The file path is resolved this way:+.IP \(bu 2+Absolute paths and \f[CR]\(ti\f[R]\-prefixed paths are used as\-is.+.IP \(bu 2+A path beginning with \f[CR]./\f[R] or \f[CR]../\f[R]+(\f[CR]source ./Checking1.csv\f[R]) is anchored relative to the rules+file\(aqs directory (as in hledger 1).+.IP \(bu 2+Any other relative path (\f[CR]source bank/Checking1.csv\f[R]), or a+bare file name (\f[CR]source Checking1.csv\f[R]), is searched for first+in a \f[CR]data/\f[R] directory next to the main journal file (also used+by the \f[CR]archive\f[R] rule and the \f[CR]get\f[R] command), then in+your \f[CR]\(ti/Downloads\f[R] folder.+.PP+You can use a glob pattern, to avoid specifying the file name exactly:+.IP+.EX+source Checking1*.csv+.EE+.PP+A glob pattern has another benefit: if it matches multiple files,+hledger reads just one of them: the newest, so stale copies are ignored;+or when importing with \f[CR]archive\f[R], the oldest, which is then+archived, so that successive imports process the copies in order.+.SS Data cleaning / data generating commands+After \f[CR]source\f[R]\(aqs file pattern, you can write \f[CR]|\f[R]+(pipe) and a data cleaning command (or command pipeline) (since hledger+1.50).+If hledger\(aqs CSV rules aren\(aqt enough, you can pre\-process the+downloaded data here with a shell command or script, to make it more+suitable for conversion.+The command will be executed by your default shell, in the directory of+the rules file, will receive the data file\(aqs content as standard+input, and should output zero or more lines of+character\-separated\-values, suitable for conversion by the CSV rules.+.PP+Examples:+.IP+.EX+source ./paypal.json | paypalcsv+source data/simplefin.json | simplefincsv \- \(aqchase.*card\(aq+source OfxDownload*.csv | grep \-vE \(aq\(ha(([\(ha,]*,){6}[\(ha,]*|)$\(aq | sort \-t, \-n +2+source History_for_Account_Z20144832*.csv # | grep \-E \(aq\(ha([\(ha,]*,){12}[\(ha,]*$\(aq | sed \-E \-e \(aqs/\(ha //\(aq \-e \(aqs/\(rs.([0\-9]),/.\(rs10,/g\(aq \-e \(aqs/,([0\-9]+),/,\(rs1.00,/g\(aq+.EE+.PP+Or, after \f[CR]source\f[R] you can write \f[CR]|\f[R] and a data+generating command (with no file pattern before the \f[CR]|\f[R]).+This command receives no input, and should output zero or more lines of+character\-separated values, suitable for conversion by the CSV rules.+.PP+Examples:+.IP+.EX+source | paypaljson | paypalcsv+source | paypalcsv data/paypal.json +source | simplefinjson >data/simplefin.json && simplefincsv data/simplefin.json \(aqchase.*card\(aq+source | simplefincsv data/simplefin.json \(aqunify.*checking\(aq+.EE+.PP+(\f[CR]paypal*\f[R] and \f[CR]simplefin*\f[R] scripts are in bin/)+.PP+Whenever hledger runs one of these commands, it will echo the command on+stderr, prefixed by the rules file\(aqs name.+If the command produces error output, but exits successfully, hledger+will show the error output as a warning.+If a data cleaning command fails, hledger will fail and show the error+output in the error message.+If a data generating command fails, hledger will show the error as a+warning and continue, treating this as if no data was found.+.PP+These commands run in an \f[CR]import \-\-dry\-run\f[R] too, since their+output is needed to preview the data.+So they should be safe to run repeatedly: a data cleaning command should+be a pure filter, and a data generating command should not consume or+change anything that the real import will need.+A fetch that isn\(aqt safe to repeat belongs in the get command\(aqs+\f[CR]getdata\f[R] script instead (which \f[CR]get \-\-dry\-run\f[R] and+\f[CR]import \-\-dry\-run \-g\f[R] don\(aqt run), with a file pattern to+read its output.+.SS \f[CR]archive\f[R]+With \f[CR]archive\f[R] added to a rules file, the \f[CR]import\f[R]+command will archive each successfully processed data file or data+command output in an \f[CR]archive/\f[R] subdirectory of the+\f[CR]data/\f[R] directory next to the main journal file.+The archive file name will be based on the rules file and the data+file\(aqs modification date and extension (or for a data\-generating+command, the current date and the \(dq.csv\(dq extension).+The original data file, once archived, will be removed.+.PP+Also, in this mode \f[CR]import\f[R] will prefer the oldest file matched+by the \f[CR]source\f[R] rule\(aqs glob pattern, not the newest.+(So if there are multiple downloads, they will be imported and archived+oldest first.)+.PP+Archiving is optional, but it can be useful for troubleshooting your CSV+rules, regenerating entries with improved rules, checking for variations+in your bank\(aqs CSV, etc.+.SS File Extension+To help hledger choose the CSV file reader and show the right error+messages (and choose the right field separator character by default),+it\(aqs best if CSV/SSV/TSV files are named with a \f[CR].csv\f[R],+\f[CR].ssv\f[R] or \f[CR].tsv\f[R] filename extension.+(More about this at Data formats.)+.PP+When reading files with the \(dqwrong\(dq extension, you can ensure the+CSV reader (and the default field separator) by prefixing the file path+with \f[CR]csv:\f[R], \f[CR]ssv:\f[R] or \f[CR]tsv:\f[R]: Eg:+.IP+.EX+$ hledger \-f ssv:foo.dat print+.EE+.PP+You can also override the default field separator with a separator rule+if needed.+.SS Reading CSV from standard input+You\(aqll need the file format prefix when reading CSV from stdin also,+since hledger assumes journal format by default.+Eg:+.IP+.EX+$ cat foo.dat | hledger \-f ssv:\- print+.EE+.SS Reading multiple CSV files+If you use multiple \f[CR]\-f\f[R] options to read multiple CSV files at+once, hledger will look for a correspondingly\-named rules file for each+CSV file.+But if you specify a rules file with \f[CR]\-\-rules\f[R], that rules+file will be used for all the CSV files.+.PP+Alternatively, a journal file can include CSV files (or rules files).+In this case each CSV file always uses its correspondingly\-named rules+file; \f[CR]\-\-rules\f[R] has no effect.+.SS Reading the data+These tips and rules help hledger read the CSV data correctly: check+that it\(aqs valid, choose its separator, decode its text, skip any+header lines, parse its dates and numbers, and put its records in the+right order.+.SS Valid CSV+Note that hledger will only accept valid CSV conforming to RFC 4180, and+equivalent SSV and TSV formats (like RFC 4180 but with semicolon or tab+as separators).+This means, eg:+.IP \(bu 2+Values may be enclosed in double quotes, or not.+Enclosing in single quotes is not allowed.+(Eg \f[CR]\(aqA\(aq,\(aqB\(aq\f[R] is rejected.)+.IP \(bu 2+When values are enclosed in double quotes, spaces outside the quotes are+not allowed.+(Eg \f[CR]\(dqA\(dq, \(dqB\(dq\f[R] is rejected.)+.IP \(bu 2+When values are not enclosed in quotes, they may not contain double+quotes.+(Eg \f[CR]A\(dqA, B\f[R] is rejected.)+.PP+If your CSV/SSV/TSV is not valid in this sense, you\(aqll need to+transform it before reading with hledger.+Try using sed, or a more permissive CSV parser like python\(aqs csv lib.+.SS \f[CR]separator\f[R]+You can use the \f[CR]separator\f[R] rule to read other kinds of+character\-separated data.+The argument is any single separator character, or the words+\f[CR]tab\f[R] or \f[CR]space\f[R] (case insensitive).+Eg, for comma\-separated values (CSV):+.IP+.EX+separator ,+.EE+.PP+or for semicolon\-separated values (SSV):+.IP+.EX+separator ;+.EE+.PP+or for tab\-separated values (TSV):+.IP+.EX+separator TAB+.EE+.PP+If the input file has a \f[CR].csv\f[R], \f[CR].ssv\f[R] or+\f[CR].tsv\f[R] file extension (or a \f[CR]csv:\f[R], \f[CR]ssv:\f[R],+\f[CR]tsv:\f[R] prefix), the appropriate separator will be inferred+automatically, and you won\(aqt need this rule.+.SS \f[CR]encoding\f[R]+.IP+.EX+encoding ENCODING+.EE+.PP+hledger normally expects non\-ascii text to be using the system+locale\(aqs text encoding.+If you need to read CSV files which have some other encoding, you can do+it by adding \f[CR]encoding ENCODING\f[R] to your CSV rules.+Eg: \f[CR]encoding iso\-8859\-1\f[R].+.PP+The supported encodings are: \f[CR]ascii\f[R], \f[CR]utf\-8\f[R],+\f[CR]utf\-16\f[R], \f[CR]utf\-32\f[R], \f[CR]iso\-8859\-1\f[R] to+\f[CR]iso\-8859\-11\f[R] and \f[CR]iso\-8859\-13\f[R] to+\f[CR]iso\-8859\-16\f[R], \f[CR]cp1250\f[R] to \f[CR]cp1258\f[R],+\f[CR]koi8\-r\f[R], \f[CR]koi8\-u\f[R], \f[CR]gb18030\f[R],+\f[CR]macintosh\f[R], \f[CR]jis\-x\-0201\f[R], \f[CR]jis\-x\-0208\f[R],+\f[CR]iso\-2022\-jp\f[R], \f[CR]shift\-jis\f[R], \f[CR]cp437\f[R],+\f[CR]cp737\f[R], \f[CR]cp775\f[R], \f[CR]cp850\f[R], \f[CR]cp852\f[R],+\f[CR]cp855\f[R], \f[CR]cp857\f[R], \f[CR]cp860\f[R] to+\f[CR]cp866\f[R], \f[CR]cp869\f[R], \f[CR]cp874\f[R], and+\f[CR]cp932\f[R].+.SS \f[CR]skip\f[R]+.IP+.EX+skip N+.EE+.PP+The word \f[CR]skip\f[R] followed by a number (or no number, meaning 1)+tells hledger to ignore this many non\-empty lines at the start of the+input data.+You\(aqll need this whenever your CSV data contains header lines.+Note, empty and blank lines are skipped automatically, so you don\(aqt+need to count those.+.PP+\f[CR]skip\f[R] has a second meaning: it can be used inside an+\f[CR]if\f[R] rule (described below), to skip one or more records+whenever the condition is true.+Records skipped in this way are ignored, except they are still required+to be valid CSV.+.SS \f[CR]date\-format\f[R]+.IP+.EX+date\-format DATEFMT+.EE+.PP+This is a helper for the \f[CR]date\f[R] (and \f[CR]date2\f[R]) fields.+If your CSV dates are not formatted like \f[CR]YYYY\-MM\-DD\f[R],+\f[CR]YYYY/MM/DD\f[R] or \f[CR]YYYY.MM.DD\f[R], you\(aqll need to add a+date\-format rule describing them with a strptime\-style date parsing+pattern \- see+https://hackage.haskell.org/package/time/docs/Data\-Time\-Format.html#v:formatTime.+The pattern must parse the CSV date value completely.+Some examples:+.IP+.EX+# MM/DD/YY+date\-format %m/%d/%y+.EE+.IP+.EX+# D/M/YYYY+# The \- makes leading zeros optional.+date\-format %\-d/%\-m/%Y+.EE+.IP+.EX+# YYYY\-Mmm\-DD+date\-format %Y\-%h\-%d+.EE+.IP+.EX+# M/D/YYYY HH:MM AM some other junk+# Note the time and junk must be fully parsed, though only the date is used.+date\-format %\-m/%\-d/%Y %l:%M %p some other junk+.EE+.PP+Note currently there is no locale awareness for things like+\f[CR]%b\f[R], and setting LC_TIME won\(aqt help.+.SS \f[CR]timezone\f[R]+.IP+.EX+timezone TIMEZONE+.EE+.PP+When CSV contains date\-times that are implicitly in some time zone+other than yours, but containing no explicit time zone information, you+can use this rule to declare the CSV\(aqs native time zone, which helps+prevent off\-by\-one dates.+.PP+When the CSV date\-times do contain time zone information, you don\(aqt+need this rule; instead, use \f[CR]%Z\f[R] in \f[CR]date\-format\f[R]+(or \f[CR]%z\f[R], \f[CR]%EZ\f[R], \f[CR]%Ez\f[R]; see the formatTime+link above).+.PP+In either of these cases, hledger will do a time\-zone\-aware+conversion, localising the CSV date\-times to your current system time+zone.+If you prefer to localise to some other time zone, eg for+reproducibility, you can (on unix at least) set the output timezone with+the TZ environment variable, eg:+.IP+.EX+$ TZ=\-1000 hledger print \-f foo.csv # or TZ=\-1000 hledger import foo.csv+.EE+.PP+\f[CR]timezone\f[R] currently does not understand timezone names, except+\(dqUTC\(dq, \(dqGMT\(dq, \(dqEST\(dq, \(dqEDT\(dq, \(dqCST\(dq,+\(dqCDT\(dq, \(dqMST\(dq, \(dqMDT\(dq, \(dqPST\(dq, or \(dqPDT\(dq.+For others, use numeric format: +HHMM or \-HHMM.+.SS \f[CR]decimal\-mark\f[R]+.IP+.EX+decimal\-mark .+.EE+.PP+or:+.IP+.EX+decimal\-mark ,+.EE+.PP+hledger automatically accepts either period or comma as a decimal mark+when parsing numbers (cf Amounts).+However if any numbers in the CSV contain digit group marks, such as+thousand\-separating commas, you should declare the decimal mark+explicitly with this rule, to avoid misparsed numbers.+Like the \f[CR]decimal\-mark\f[R] directive, this also makes hledger+report numbers using a different decimal mark, or repeating the declared+one (like \f[CR]1.2.34\f[R]), as errors.+This applies to amounts from the CSV fields and to amounts written in+the rules.+.SS \f[CR]newest\-first\f[R]+hledger tries to ensure that the generated transactions will be ordered+chronologically, including same\-day transactions.+Usually it can auto\-detect how the CSV records are ordered.+But if it encounters CSV where all records are on the same date, it+assumes that the records are oldest first.+If in fact the CSV\(aqs records are normally newest first, like:+.IP+.EX+2022\-10\-01, txn 3...+2022\-10\-01, txn 2...+2022\-10\-01, txn 1...+.EE+.PP+you can add the \f[CR]newest\-first\f[R] rule to help hledger generate+the transactions in correct order.+.IP+.EX+# same\-day CSV records are newest first+newest\-first+.EE+.SS \f[CR]intra\-day\-reversed\f[R]+If CSV records within a single day are ordered opposite to the overall+record order, you can add the \f[CR]intra\-day\-reversed\f[R] rule to+improve the order of journal entries.+Eg, here the overall record order is newest first, but same\-day records+are oldest first:+.IP+.EX+2022\-10\-02, txn 3...+2022\-10\-02, txn 4...+2022\-10\-01, txn 1...+2022\-10\-01, txn 2...+.EE+.IP+.EX+# transactions within each day are reversed with respect to the overall date order+intra\-day\-reversed+.EE+.PP+.SS CSV fields and hledger fields+The main task of CSV rules is to convert \f[B]CSV fields\f[R] to+\f[B]hledger fields\f[R].+It\(aqs important to know which is which, when you are creating rules:+.IP "1." 3+CSV fields+.RS 4+.IP \(bu 2+are the parts of the records (lines) in your CSV data+.IP \(bu 2+are referenced by their position or assigned name, with a \f[CR]%\f[R]+prefix (eg \f[CR]%1\f[R] or \f[CR]%date\f[R])+.IP \(bu 2+are read\-only.+.RE+.IP "2." 3+hledger fields+.RS 4+.IP \(bu 2+are the parts of a hledger journal entry (see hledger fields) (eg+\f[CR]date\f[R], \f[CR]description\f[R], \f[CR]account1\f[R],+\f[CR]amount1\f[R])+.IP \(bu 2+are assigned to by rules, to construct a journal entry+.IP \(bu 2+can be referenced by their name, without a \f[CR]%\f[R] prefix, inside a+\f[CR]%{...}\f[R] expression (eg \f[CR]%{description}\f[R]; see+Referencing other fields).+.RE+.PP+CSV rules can\(aqt make new fields; you can\(aqt define your own+variables in a rules file.+(But you could add new CSV fields to the data before running rules, with+a preprocessing script.)+.PP+It\(aqs ok for a CSV field and a hledger field to have the same name; in+a \f[CR]fields\f[R] list, this causes the CSV field\(aqs value to be+assigned to the hledger field (\(dqfield name punning\(dq).+hledger knows which kind of field is meant from the context: in field+values and matchers, \f[CR]%NAME\f[R] is a CSV field, and a bare+\f[CR]HLEDGERFIELDNAME\f[R] inside \f[CR]%{...}\f[R] is a hledger field.+Some examples:+.IP+.EX+# set the journal entry\(aqs date to the value of CSV field 1+date %1+.EE+.IP+.EX+# name the CSV fields, and use the first as the entry\(aqs date+fields date, bankamt++# test the value of the CSV date field+if %date 2026+ ...+.EE+.IP+.EX+# add a tag to the hledger comment field, keeping any comment assigned before+comment %{join(\(dq, \(dq, comment, \(dqimported:\(dq)}+.EE+.PP+.SS \f[CR]fields\f[R]+.IP+.EX+fields FIELDNAME1, FIELDNAME2, ...+.EE+.PP+A \f[CR]fields\f[R] list (the word \f[CR]fields\f[R] followed by+comma\-separated field names) is optional, but convenient.+It does two things:+.IP "1." 3+It names the CSV field in each column.+This can be convenient if you are referencing them in other rules, so+you can say \f[CR]%SomeField\f[R] instead of remembering \f[CR]%13\f[R].+.IP "2." 3+Whenever you use one of the special hledger field names (described+below), it assigns the CSV value in this position to that hledger field.+This is the quickest way to populate hledger\(aqs fields and build a+transaction.+.PP+Here\(aqs an example that says \(dquse the 1st, 2nd and 4th fields as+the transaction\(aqs date, description and amount; name the last two+fields for later reference; and ignore the others\(dq:+.IP+.EX+fields date, description, , amount, , , somefield, anotherfield+.EE+.PP+In \f[CR]fields\f[R], the names are always separated by commas; this is+unrelated to the CSV file\(aqs separator.+Also:+.IP \(bu 2+There must be least two items in the list (at least one comma).+.IP \(bu 2+Field names may not contain spaces.+Spaces before/after field names are optional.+.IP \(bu 2+Field names may contain \f[CR]_\f[R] (underscore) or \f[CR]\-\f[R]+(hyphen).+.IP \(bu 2+Fields you don\(aqt care about can be given a dummy name or an empty+name.+.PP+If the CSV contains column headings, it\(aqs convenient to use these for+your field names, suitably modified (eg lower\-cased with spaces+replaced by underscores).+.PP+Sometimes you may want to alter a CSV field name to avoid assigning to a+hledger field with the same name.+Eg you could call the CSV\(aqs \(dqbalance\(dq field \f[CR]balance_\f[R]+to avoid directly setting hledger\(aqs \f[CR]balance\f[R] field (and+generating a balance assertion).+.SS Field assignment+.IP+.EX+HLEDGERFIELD FIELDVALUE+.EE+.PP+Field assignments are the more flexible way to assign CSV values to+hledger fields.+They can be used instead of or in addition to a \f[CR]fields\f[R] list+(see above).+.PP+To assign a value to a hledger field, write the field name (any of the+standard hledger field/pseudo\-field names, defined below), a space,+followed by a text value on the same line.+This text value may interpolate CSV fields, referenced either by their+1\-based position in the CSV record (\f[CR]%N\f[R]) or by the name they+were given by \f[CR]fields\f[R] (\f[CR]%CSVFIELD\f[R]), and regular+expression match groups (\f[CR]\(rsN\f[R]), and can transform them with+functions (\f[CR]%{upper(%CSVFIELD)}\f[R]) or use other hledger+fields\(aq values (\f[CR]%{description}\f[R]; see Referencing other+fields).+You can also write \f[CR]%(CSVFIELD)\f[R] to delimit the field name from+adjacent text (eg \f[CR]%(field)suffix\f[R]).+When CSV records have been combined by a \f[CR]merge\f[R] rule, a+\f[CR]_ROWNUM\f[R] suffix (eg \f[CR]%amt_2\f[R], \f[CR]%4_2\f[R])+references the later rows\(aq fields.+Interpolation strips outer whitespace (so a CSV value like+\f[CR]\(dq 1 \(dq\f[R] becomes \f[CR]1\f[R] when interpolated) (#1051).+.PP+Some examples:+.IP+.EX+# set the amount to the 4th CSV field, with \(dq USD\(dq appended+amount %4 USD++# combine three fields to make a comment, containing note: and date: tags+comment note: %somefield \- %anotherfield, date: %1++# use parenthesised form when the field name would run into adjacent text+account1 assets:%(type)checking+.EE+.SS Functions+\f[I]Since 1.99.6; experimental\f[R]+.PP+To transform a value while interpolating it, write a \f[CR]%{...}\f[R]+expression calling one of the built\-in functions below.+Eg:+.IP+.EX+# upper\-case the description+description %{upper(%desc)}++# use the category in lower case, or \(dqmisc\(dq if it\(aqs empty+account2 expenses:%{lower(default(%category, \(dqmisc\(dq))}++# remove a reference number from the description+description %{replace(%desc, \(dq *ref#[0\-9]+\(dq, \(dq\(dq)}++# put the date\(aqs year and month in a tag+comment month:%{substr(%date, 1, 7)}++# show the last four digits of the card number+comment card:%{substr(%card, \-4)}+.EE+.PP+Function arguments can be CSV field references (\f[CR]%summary\f[R] or+\f[CR]%3\f[R]), hledger field names (\f[CR]comment\f[R]), match group+references (\f[CR]\(rs1\f[R]), double\-quoted text+(\f[CR]\(dqmisc\(dq\f[R]), numbers, or other function calls.+Use \f[CR]\(rs\(dq\f[R] for a double quote inside double\-quoted text.+Each expression\(aqs result has outer whitespace removed, like other+interpolated values.+.PP+.TS+tab(@);+lw(18.8n) lw(51.2n).+T{+function+T}@T{+result+T}+_+T{+\f[CR]upper(TEXT)\f[R]+T}@T{+TEXT in upper case+T}+T{+\f[CR]lower(TEXT)\f[R]+T}@T{+TEXT in lower case+T}+T{+\f[CR]capitalize(TEXT)\f[R]+T}@T{+TEXT with each word\(aqs first letter in upper case and the rest in+lower case (\f[CR]capitalise\f[R] also works)+T}+T{+\f[CR]trim(TEXT)\f[R]+T}@T{+TEXT without outer whitespace+T}+T{+\f[CR]negate(AMOUNT)\f[R]+T}@T{+AMOUNT with its sign flipped, eg \f[CR]5\f[R] \-> \f[CR]\-5\f[R],+\f[CR]\-5\f[R] or \f[CR](5)\f[R] \-> \f[CR]5\f[R]+T}+T{+\f[CR]abs(AMOUNT)\f[R]+T}@T{+AMOUNT without a minus sign, eg \f[CR]\-5\f[R] or \f[CR](5)\f[R] \->+\f[CR]5\f[R]+T}+T{+\f[CR]concat(TEXT, ...)\f[R]+T}@T{+all the arguments joined together+T}+T{+\f[CR]join(SEP, TEXT, ...)\f[R]+T}@T{+the TEXTs that aren\(aqt empty, joined with SEP between them+T}+T{+\f[CR]default(TEXT, ...)\f[R]+T}@T{+the first argument that\(aqs not empty+T}+T{+\f[CR]replace(TEXT, REGEX, REPL)\f[R]+T}@T{+TEXT with each match of REGEX replaced by REPL+T}+T{+\f[CR]substr(TEXT, START, LENGTH)\f[R]+T}@T{+LENGTH characters of TEXT, starting at position START (1 is the first,+\-1 the last); LENGTH is optional+T}+.TE+.PP+For \f[CR]replace\f[R], REGEX must be double\-quoted text, and is a+case\-insensitive regular expression.+REPL can use \f[CR]\(rs1\f[R], \f[CR]\(rs2\f[R] etc.+to insert REGEX\(aqs match groups.+(Unquoted \f[CR]\(rs1\f[R] etc.+outside double quotes refer to the match groups of an enclosing+\f[CR]if\f[R] rule instead.)+For \f[CR]substr\f[R], START and LENGTH must be numbers.+A negative START counts from the end, so eg+\f[CR]substr(%card, \-4)\f[R] gives the last four characters.+Positions before the start or after the end of TEXT are treated as the+start or end.+.PP+For \f[CR]negate\f[R] and \f[CR]abs\f[R], AMOUNT is a number, optionally+with a commodity symbol before or after it, and optionally with a sign:+\f[CR]\-\f[R] or \f[CR]+\f[R] before it, or parentheses meaning negative+around it.+The sign can be before or after a commodity symbol written in front of+the number.+Eg these are all negative amounts: \f[CR]\-5\f[R], \f[CR](5)\f[R],+\f[CR]\-$5\f[R], \f[CR]$\-5\f[R], \f[CR]$(5)\f[R], \f[CR]USD \-5\f[R],+\f[CR]\-5 USD\f[R], \f[CR](5 USD)\f[R].+The number itself isn\(aqt parsed, so its decimal mark and digit group+marks don\(aqt matter.+\f[CR]negate\f[R] converts \f[CR]5\f[R] to \f[CR]\-5\f[R] and+\f[CR]$\-1,000.50\f[R] to \f[CR]$1,000.50\f[R], and \f[CR]abs\f[R]+converts any of the above to the unsigned form.+A sign after the number (\f[CR]5\-\f[R]), or parentheses around just the+number when the symbol comes after it (\f[CR](5) USD\f[R]), are not+supported.+.PP+\f[CR]join\f[R] is useful for combining parts which may be empty,+without stray separators.+Eg \f[CR]comment %{join(\(dq, \(dq, %note, %ref)}\f[R].+.PP+Mistakes in an expression, like an unknown function or the wrong number+of arguments, are reported when the rules file is read.+Text beginning with \f[CR]%{\f[R] is always taken as an expression.+.SS Referencing other fields+To use a hledger field\(aqs value, write its name (without \f[CR]%\f[R])+inside a \f[CR]%{...}\f[R] expression.+\f[CR]%NAME\f[R] always means a CSV field, even when a hledger field has+the same name:+.IP+.EX+# name the third CSV field \(dqamount1\(dq+fields date, description, amount1+# set hledger\(aqs amount1 to the CSV amount1 field, followed by USD+amount1 %amount1 USD+# the CSV amount1 field, eg \(dq5\(dq+comment %amount1+# hledger\(aqs amount1 field, eg \(dq5 USD\(dq+comment1 %{amount1}+.EE+.PP+When there are multiple field assignments to the same hledger field,+only the last one takes effect (though it can include the earlier value,+see below).+Here, comment\(aqs value will be B, or C if \(dqsomething\(dq is+matched, but never A:+.IP+.EX+comment A+comment B+if something+ comment C+.EE+.PP+In an assignment to the same field, a hledger field\(aqs name gives the+field\(aqs value from its previous assignment, so you can add to it.+This is handy for appending to a comment:+.IP+.EX+fields date, description, comment, amount+if refund+ # add a refund tag+ comment %{comment}, refund:+ # or, avoiding a redundant separator when comment is empty:+ #comment %{join(\(dq, \(dq, comment, \(dqrefund:\(dq)}+.EE+.PP+\(dqPrevious assignment\(dq here means the one before this one, in this+order: top\-level assignments (including those made by+\f[CR]fields\f[R]), then assignments in matched \f[CR]if\f[R] rules,+each in the order written.+(So a top\-level assignment comes before any \f[CR]if\f[R] rule\(aqs,+even if written after it.)+.PP+In an assignment to a different field, a hledger field\(aqs name gives+that field\(aqs final value, wherever it is assigned.+Eg here, comment is set to the final value of the hledger description:+.IP+.EX+comment %{description}+.EE+.PP+When interpolating a hledger field, the value is the text assigned to+the field by these rules, before further processing by hledger.+Eg \f[CR]%{amount1}\f[R] is the amount text before any sign+simplification, and \f[CR]%{account2}\f[R] is empty if account2 isn\(aqt+assigned (not \f[CR]expenses:unknown\f[R]).+.PP+.SS hledger fields+Here are all the hledger fields you can assign to.+They correspond to parts of a journal entry, or in some cases they are+pseudo\-fields which have a special effect.+You can also interpolate their values in \f[CR]%{...}\f[R] expressions,+except for the \f[CR]\-in\f[R]/\f[CR]\-out\f[R] amount fields.+.SS date field+Assigning to \f[CR]date\f[R] sets the transaction date.+This is required.+If the CSV dates aren\(aqt like \f[CR]YYYY\-MM\-DD\f[R], see+\f[CR]date\-format\f[R] (and \f[CR]timezone\f[R]).+.SS date2 field+\f[CR]date2\f[R] sets the transaction\(aqs secondary date, if any.+.SS status field+\f[CR]status\f[R] sets the transaction\(aqs status, if any.+.SS code field+\f[CR]code\f[R] sets the transaction\(aqs code, if any.+.PP+Journal format can\(aqt represent a right parenthesis in a code (when+reparsed, it would end the code early).+So any right parentheses here will be replaced with \f[CR]]\f[R], with a+warning.+.SS description field+\f[CR]description\f[R] sets the transaction\(aqs description, if any.+.PP+Journal format can\(aqt represent a semicolon in a description (when+reparsed, it would start a comment, truncating the description).+So any semicolons here will be replaced with \f[CR].,\f[R] (a semicolon+on its side), and a warning is printed.+.SS comment field+\f[CR]comment\f[R] sets the transaction\(aqs comment, if any.+.PP+\f[CR]commentN\f[R], where N is a number, sets the Nth posting\(aqs+comment.+.PP+You can assign multi\-line comments by writing literal \f[CR]\(rsn\f[R]+in the code.+A comment starting with \f[CR]\(rsn\f[R] will begin on a new line.+.PP+Comments can contain tags, as usual.+.PP+Posting comments can also contain a posting date.+A secondary date, or a year\-less date, will be ignored.+.SS account field+Assigning to \f[CR]accountN\f[R], where N is 1 to 99, sets the account+name of the Nth posting, and causes that posting to be generated.+.PP+Most often there are two postings, so you\(aqll want to set+\f[CR]account1\f[R] and \f[CR]account2\f[R].+Typically \f[CR]account1\f[R] is associated with the CSV file, and is+set once with a top\-level assignment, while \f[CR]account2\f[R] is set+based on each transaction\(aqs description, in \f[CR]if\f[R] rules.+.PP+If a posting\(aqs account name is left unset but its amount is set, the+account name will be set to \f[CR]expenses:unknown\f[R] or+\f[CR]income:unknown\f[R] (depending on the amount\(aqs sign).+.SS amount field+There are several ways to set posting amounts from CSV, useful in+different situations.+.IP "1." 3+\f[B]\f[CB]amount\f[B]\f[R] is the oldest and simplest.+Assigning to this sets the amount of the first and second postings.+In the second posting, the amount will be negated; also, if it has a+cost attached, it will be converted to cost.+.IP "2." 3+\f[B]\f[CB]amount\-in\f[B]\f[R] and \f[B]\f[CB]amount\-out\f[B]\f[R]+work exactly like the above, but should be used when the CSV has two+amount fields (such as \(dqDebit\(dq and \(dqCredit\(dq, or+\(dqInflow\(dq and \(dqOutflow\(dq).+Whichever field has a non\-zero value will be used as the amount of the+first and second postings.+Here are some tips to avoid confusion:+.RS 4+.IP \(bu 2+It\(aqs not \(dqamount\-in for posting 1 and amount\-out for posting+2\(dq, it is \(dqextract a single amount from the amount\-in or+amount\-out field, and use that for posting 1 and (negated) for posting+2\(dq.+.IP \(bu 2+Don\(aqt use both \f[CR]amount\f[R] and+\f[CR]amount\-in\f[R]/\f[CR]amount\-out\f[R] in the same rules file;+choose based on whether the amount is in a single CSV field or spread+across two fields.+.IP \(bu 2+In each record, at most one of the two CSV fields should contain a+non\-zero amount; the other field must contain a zero or nothing.+.IP \(bu 2+hledger assumes both CSV fields contain unsigned numbers, and it+automatically negates the amount\-out values.+.IP \(bu 2+If the data doesn\(aqt fit these requirements, you\(aqll probably need+an if rule (see Setting amounts).+.RE+.IP "3." 3+\f[B]\f[CB]amountN\f[B]\f[R] (where N is a number from 1 to 99) sets the+amount of only a single posting: the Nth posting in the transaction.+You\(aqll usually need at least two such assignments to make a balanced+transaction.+You can also generate more than two postings, to represent more complex+transactions.+The posting numbers don\(aqt have to be consecutive; with if rules,+higher posting numbers can be useful to ensure a certain order of+postings.+.IP "4." 3+\f[B]\f[CB]amountN\-in\f[B]\f[R] and \f[B]\f[CB]amountN\-out\f[B]\f[R]+work exactly like the above, but should be used when the CSV has two+amount fields.+This is analogous to \f[CR]amount\-in\f[R] and \f[CR]amount\-out\f[R],+and those tips also apply here.+.IP "5." 3+Remember that \f[CR]fields\f[R] can also do assignments.+So if you name a CSV field \(dqamount\(dq in \f[CR]fields\f[R], that+counts as assigning to \f[CR]amount\f[R].+(If you don\(aqt want that, call it something else there, like+\(dqamount_\(dq.)+.IP "6." 3+The above don\(aqt handle every situation; if you need more flexibility,+use an \f[CR]if\f[R] rule to set amounts conditionally.+See Setting amounts below for more on this and on amount\-setting+generally.+.PP+If the CSV numbers have digit group marks (like \f[CR]1,000.00\f[R]),+see \f[CR]decimal\-mark\f[R].+.PP+An amount value can be an amount expression, eg+\f[CR]amount1 %price + %fee\f[R] (see Amount signs for how this+interacts with sign handling).+.SS Setting amounts+Which amount fields to use depends on how the CSV shows amounts:+.IP "1." 3+\f[B]If the amount is in a single CSV field:\f[R]+.PD 0+.P+.PD+.RS 4+.IP "a." 3+\f[B]If its sign indicates direction of flow:\f[R]+.PD 0+.P+.PD+Assign it to \f[CR]amountN\f[R], to set the Nth posting\(aqs amount.+N is usually 1 or 2 but can go up to 99.+.IP "b." 3+\f[B]If another field indicates direction of flow:\f[R]+.PD 0+.P+.PD+Use one or more \f[CR]if\f[R] rules to set the appropriate amount sign.+Eg:+.IP+.EX+# assume a withdrawal unless Type contains \(dqdeposit\(dq:+amount1 \-%Amount+if %Type deposit+ amount1 %Amount+.EE+.RE+.IP "2." 3+\f[B]If the amount is in two CSV fields (such as Debit and Credit, or In+and Out):\f[R]+.PD 0+.P+.PD+.RS 4+.IP "a." 3+\f[B]If both fields are unsigned:\f[R]+.PD 0+.P+.PD+Assign one field to \f[CR]amountN\-in\f[R] and the other to+\f[CR]amountN\-out\f[R].+hledger will automatically negate the \(dqout\(dq field, and will use+whichever field value is non\-zero as posting N\(aqs amount.+.IP "b." 3+\f[B]If either field is signed:\f[R]+.PD 0+.P+.PD+You will probably need to override hledger\(aqs sign for one or the+other field, as in the following example:+.IP+.EX+# Negate the \-out value, but only if it is not empty:+fields date, description, amount1\-in, amount1\-out+if %amount1\-out [1\-9]+ amount1\-out \-%amount1\-out+.EE+.PP+c.+\f[B]If both fields can contain a non\-zero value (or both can be+empty):\f[R]+.PD 0+.P+.PD+The \-in/\-out rules normally choose the value which is+non\-zero/non\-empty.+Some value pairs can be ambiguous, such as \f[CR]1\f[R] and+\f[CR]none\f[R].+For such cases, use \f[CR]if\f[R] rules to help select the amount.+Eg, to handle the above you could select the value containing non\-zero+digits:+\f[CR]rules fields date, description, in, out if %in [1\-9] amount1 %in if %out [1\-9] amount1 %out\f[R]+.RE+.IP "3." 3+\f[B]If you want posting 2\(aqs amount converted to cost:\f[R]+.PD 0+.P+.PD+Use the unnumbered \f[CR]amount\f[R] (or \f[CR]amount\-in\f[R] and+\f[CR]amount\-out\f[R]) syntax.+.IP "4." 3+\f[B]If the CSV has only balance amounts, not transaction amounts:\f[R]+.PD 0+.P+.PD+Assign to \f[CR]balanceN\f[R], to set a balance assignment on the Nth+posting, causing the posting\(aqs amount to be calculated automatically.+\f[CR]balance\f[R] with no number is equivalent to \f[CR]balance1\f[R].+In this situation hledger is more likely to guess the wrong default+account name, so you may need to set that explicitly.+.SS Amount signs+There is some special handling making it easier to parse and to reverse+amount signs.+(This only works for whole amounts, not for cost amounts such as COST in+\f[CR]amount1 AMT \(at COST\f[R]):+.IP \(bu 2+\f[B]If an amount value begins with a plus sign:\f[R]+.PD 0+.P+.PD+that will be removed: \f[CR]+AMT\f[R] becomes \f[CR]AMT\f[R]+.IP \(bu 2+\f[B]If an amount value is parenthesised:\f[R]+.PD 0+.P+.PD+it will be de\-parenthesised and sign\-flipped: \f[CR](AMT)\f[R] becomes+\f[CR]\-AMT\f[R]+.IP \(bu 2+\f[B]If an amount value has two minus signs (or two sets of parentheses,+or a minus sign and parentheses):\f[R]+.PD 0+.P+.PD+they cancel out and will be removed: \f[CR]\-\-AMT\f[R] or+\f[CR]\-(AMT)\f[R] becomes \f[CR]AMT\f[R]+.IP \(bu 2+\f[B]If an amount value contains just a sign (or just a set of+parentheses):\f[R]+.PD 0+.P+.PD+that is removed, making it an empty value.+\f[CR]\(dq+\(dq\f[R] or \f[CR]\(dq\-\(dq\f[R] or \f[CR]\(dq()\(dq\f[R]+becomes \f[CR]\(dq\(dq\f[R].+.PP+These rules don\(aqt apply to a value containing an arithmetic operator+(\f[CR]*\f[R], \f[CR]/\f[R], or a \f[CR]+\f[R] or \f[CR]\-\f[R] which is+not a leading sign or an exponent sign as in \f[CR]1e\-5\f[R]), which is+read as an amount expression instead.+In an expression, parentheses group rather than negate:+\f[CR]\-(%price + %fee)\f[R] is minus the sum.+.PP+To set an amount to its absolute value, ie discard its sign, use the+\f[CR]abs\f[R] function, eg \f[CR]amount1 %{abs(%amt)}\f[R].+.SS Amount decimal places+When you are reading CSV data, eg with a command like+\f[CR]hledger \-f foo.csv print\f[R], hledger will infer each+commodity\(aqs decimal precision (and other commodity display styles)+from the amounts \- much as when reading a journal file without+\f[CR]commodity\f[R] directives (see the link).+.PP+Note, the commodity styles are not inferred from the numbers in the+original CSV data; rather, they are inferred from the amounts generated+by the CSV rules.+.PP+When you are importing CSV data with the \f[CR]import\f[R] command, eg+\f[CR]hledger import foo.csv\f[R], there\(aqs another step:+\f[CR]import\f[R] tries to make the new entries conform to the+journal\(aqs existing styles.+So for each commodity \- let\(aqs say it\(aqs EUR \- \f[CR]import\f[R]+will choose:+.IP "1." 3+the style declared for EUR by a \f[CR]commodity\f[R] directive in the+journal+.IP "2." 3+otherwise, the style inferred from EUR amounts in the journal+.IP "3." 3+otherwise, the style inferred from EUR amounts generated by the CSV+rules.+.PP+TLDR: if \f[CR]import\f[R] is not generating the precisions or styles+you want, add a \f[CR]commodity\f[R] directive to specify them.+.SS currency field+\f[CR]currency\f[R] sets a default commodity symbol, to be used for any+posting (or balance) amounts which don\(aqt have one.+You can use this if the CSV amounts do not have a currency symbol, eg if+it is in a separate column.+(You can also set the symbol within an amount assignment, like+\f[CR]amount %amt USD\f[R], but sometimes it\(aqs more convenient to set+it this way.)+The value can be:+.IP \(bu 2+a commodity symbol, like \f[CR]USD\f[R] or \f[CR]$\f[R] or+\f[CR]\(dqSome Fund\(dq\f[R]; this is placed on the left of the number,+with no space (\f[CR]USD5\f[R]).+.IP \(bu 2+or a dummy amount with that symbol, like \f[CR]1 USD\f[R] or+\f[CR]USD 1\f[R] or \f[CR]1USD\f[R], showing the symbol\(aqs position+and spacing to use.+(The amount\(aqs number style, if any, like \f[CR]1.000,00 EUR\f[R], is+also used as a default display style for that commodity.)+.PP+Note the symbol\(aqs placement and display style don\(aqt matter much+when using \f[CR]import\f[R], since that command applies the+journal\(aqs existing commodity styles to the new entries (see Amount+decimal places).+.PP+\f[CR]currencyN\f[R] does the same for just the Nth posting\(aqs amount.+.SS Setting currency/commodity+If the currency/commodity symbol is included in the CSV\(aqs amount+field(s):+.IP+.EX+2023\-01\-01,foo,$123.00+.EE+.PP+you don\(aqt have to do anything special for the commodity symbol, it+will be assigned as part of the amount.+Eg:+.IP+.EX+fields date,description,amount+.EE+.IP+.EX+2023\-01\-01 foo+ expenses:unknown $123.00+ income:unknown $\-123.00+.EE+.PP+If the currency is provided as a separate CSV field:+.IP+.EX+2023\-01\-01,foo,USD,123.00+.EE+.PP+You can name that field \f[CR]currency\f[R]; this is a special rule,+which sets the commodity of every amount in the transaction which+doesn\(aqt have one (placing the symbol on the left, with no separating+space):+.IP+.EX+fields date,description,currency,amount+.EE+.IP+.EX+2023\-01\-01 foo+ expenses:unknown USD123.00+ income:unknown USD\-123.00+.EE+.PP+To put the symbol on the right, separated by a space, give the+\f[CR]currency\f[R] rule a dummy amount showing that:+.IP+.EX+fields date,description,cur,amt+currency 1 %cur+amount %amt+.EE+.IP+.EX+2023\-01\-01 foo+ expenses:unknown 123.00 USD+ income:unknown \-123.00 USD+.EE+.PP+Or, you can use a field assignment to construct the amount yourself:+\f[CR]amount %amt %cur\f[R].+.SS balance field+\f[CR]balanceN\f[R] sets a balance assertion amount (or if the posting+amount is left empty, a balance assignment) on posting N.+.PP+\f[CR]balance\f[R] is a compatibility spelling for hledger <1.17; it is+equivalent to \f[CR]balance1\f[R].+.PP+You can adjust the type of assertion/assignment with the+\f[CR]balance\-type\f[R] rule (see below).+If the CSV has only balances, not transaction amounts, see Setting+amounts.+.SS \f[CR]balance\-type\f[R]+Balance assertions generated by assigning to balanceN are of the simple+\f[CR]=\f[R] type by default, which is a single\-commodity,+subaccount\-excluding assertion.+You may find the subaccount\-including variants more useful, eg if you+have created some virtual subaccounts of checking to help with+budgeting.+You can select a different type of assertion with the+\f[CR]balance\-type\f[R] rule:+.IP+.EX+# balance assertions will consider all commodities and all subaccounts+balance\-type ==*+.EE+.PP+Here are the balance assertion types for quick reference:+.IP+.EX+= single commodity, exclude subaccounts+=* single commodity, include subaccounts+== multi commodity, exclude subaccounts+==* multi commodity, include subaccounts+.EE+.SS \f[CR]if\f[R]+Rules can be applied conditionally, depending on patterns in the CSV+data.+This is how you can categorise transactions, selecting an appropriate+account based on their description (eg).+.PP+An \f[CR]if\f[R] rule is the word \f[CR]if\f[R], followed by one or more+\(dqmatcher\(dq expressions starting on the same line or the next line,+followed by one or more indented rules.+Eg,+.IP+.EX+if MATCHER+ RULE+.EE+.PP+or+.IP+.EX+if+MATCHER+MATCHER+MATCHER+ RULE+ RULE+.EE+.PP+Comment lines can appear anywhere within an \f[CR]if\f[R] rule, and+blank lines can also appear among the indented rules; these do not end+the rule.+(One exception: a matcher on the same line as \f[CR]if\f[R] can begin+with a comment character (eg \f[CR]if #groceries\f[R] matches records+containing \(dq#groceries\(dq); but on the lines below \f[CR]if\f[R],+such a line would be read as a comment.+There, escape the comment character with a backslash, eg+\f[CR]\(rs#groceries\f[R].)+.PP+If any of the matchers succeeds, all of the indented rules will be+applied.+The rules are usually field assignments, but the following special rules+may also be used within an \f[CR]if\f[R] rule:+.IP \(bu 2+\f[CR]skip\f[R] \- skips the matched CSV record (generating no+transaction from it) (described above).+.IP \(bu 2+\f[CR]end\f[R] \- skips the rest of the current CSV file (described+below).+.IP \(bu 2+\f[CR]merge\f[R] \- combines the matched CSV record and the next+record(s) into one record (described below).+.PP+Some examples:+.IP+.EX+# if the record contains \(dqgroceries\(dq, set account2 to \(dqexpenses:groceries\(dq+if groceries+ account2 expenses:groceries+.EE+.IP+.EX+# if the record contains any of these phrases, set account2 and a transaction comment as shown+if+monthly service fee+atm transaction fee+banking thru software+ account2 expenses:business:banking+ comment XXX deductible ? check it+.EE+.SS Matchers+There are two kinds of matcher:+.IP "1." 3+A whole record matcher is simplest: it is just a word, single\-line text+fragment, or other regular expression, which hledger will try to match+case\-insensitively anywhere within the CSV record.+.PD 0+.P+.PD+Eg: \f[CR]whole foods\f[R].+.IP "2." 3+A field matcher has a percent\-prefixed CSV field number or name before+the pattern.+.PD 0+.P+.PD+Eg: \f[CR]%3 whole foods\f[R] or \f[CR]%description whole foods\f[R].+.PD 0+.P+.PD+hledger will try to match the pattern just within the named CSV field.+(In records combined by a \f[CR]merge\f[R] rule, a \f[CR]_ROWNUM\f[R]+suffix selects a later row\(aqs field, eg \f[CR]%description_2\f[R].)+.PP+When using these, there\(aqs two things to be aware of:+.IP "1." 3+Whole record matchers don\(aqt see the exact original record; they see a+reconstruction of it, in which values are comma\-separated, and quotes+enclosing values and whitespace outside those quotes are removed.+.PD 0+.P+.PD+Eg when reading an SSV record like:+\f[CR]2023\-01\-01 ; \(dqAcme, Inc. \(dq ; 1,000\f[R]+.PD 0+.P+.PD+the whole record matcher sees instead:+\f[CR]2023\-01\-01,Acme, Inc. ,1,000\f[R]+.IP "2." 3+Field matchers expect either a CSV field number, or a CSV field name+declared with \f[CR]fields\f[R].+Anything else will cause it to match against the empty string, and+probably fail silently (this makes it easier to reuse common rules with+different CSV files).+Don\(aqt use a hledger field name here (see CSV fields and hledger+fields).+.PP+You can also prefix a matcher line with \f[CR]!\f[R] to negate it (at+the start of the line; you can\(aqt negate individual terms within the+line).+Eg \f[CR]! whole foods\f[R], \f[CR]! %3 whole foods\f[R],+\f[CR]!%description whole foods\f[R] will match if \(dqwhole foods\(dq+is NOT present.+.PP+The pattern is, as usual in hledger, a POSIX extended regular expression+that also supports GNU word boundaries (\f[CR]\(rsb\f[R],+\f[CR]\(rsB\f[R], \f[CR]\(rs<\f[R], \f[CR]\(rs>\f[R]) and nothing else.+For more details and tips, see Regular expressions in CSV rules below.+.SS Multiple matchers+When an \f[CR]if\f[R] rule has multiple matchers, each on its own line,+.IP \(bu 2+By default they are OR\(aqd (any of them can match).+.IP \(bu 2+Matcher lines beginning with \f[CR]&\f[R] (or \f[CR]&&\f[R]) are+AND\(aqed with the matcher above (all in the AND\(aqed group must+match).+.IP \(bu 2+Matcher lines beginning with \f[CR]& !\f[R] (or \f[CR]&& !\f[R]) are+first negated and then AND\(aqed with the matcher above.+.PP+You can also combine multiple matchers on the same line separated by+\f[CR]&&\f[R] (AND) or \f[CR]&& !\f[R] (AND NOT).+Eg \f[CR]%description amazon && %date 2025\-01\-01\f[R] will match only+when the description field contains \(dqamazon\(dq and the date field+contains \(dq2025\-01\-01\(dq.+.SS Match groups+Matchers can define match groups: parenthesised portions of the regular+expression which are available for reference in field assignments.+Groups are enclosed in regular parentheses (\f[CR](\f[R] and+\f[CR])\f[R]) and can be nested.+Each group is available in field assignments using the token+\f[CR]\(rsN\f[R], where N is an index into the match groups for this+\f[CR]if\f[R] rule (e.g.+\f[CR]\(rs1\f[R], \f[CR]\(rs2\f[R], etc.).+.PP+Example: Warp credit card payment postings to the beginning of the+billing period (Month start), to match how they are presented in+statements, using posting dates:+.IP+.EX+if %date (....\-..)\-..+ comment2 date:\(rs1\-01+.EE+.PP+Another example: Read the expense account from the CSV field, but throw+away a prefix:+.IP+.EX+if %account1 liabilities:family:(expenses:.*)+ account1 \(rs1+.EE+.SS Regular expressions in CSV rules+Regular expressions in \f[CR]if\f[R] conditions (AKA matchers) are POSIX+extended regular expressions, that also support GNU word boundaries+(\f[CR]\(rsb\f[R], \f[CR]\(rsB\f[R], \f[CR]\(rs<\f[R],+\f[CR]\(rs>\f[R]), and nothing else.+(For more detail, see Regular expressions.)+.PP+Here are some examples that might be useful in CSV rules:+.IP \(bu 2+Is field \(dqfoo\(dq truly empty ?+\f[CR]if %foo \(ha$\f[R]+.IP \(bu 2+Is it empty or containing only whitespace ?+\f[CR]if %foo \(ha *$\f[R]+.IP \(bu 2+Is it non\-empty ?+\f[CR]if %foo .\f[R]+.IP \(bu 2+Does it contain non\-whitespace ?+\f[CR]if %foo [\(ha ]\f[R]+.PP+Testing the value of numeric fields is a little harder.+You can\(aqt use hledger queries like \f[CR]amt:0\f[R] or+\f[CR]amt:>10\f[R] in CSV rules.+But you can often achieve the same thing with a regular expression.+.PP+Note the content and layout of number fields in CSV varies, and can+change over time (eg if you switch data providers).+So numeric regexps are always somewhat specific to your particular CSV+data; and it\(aqs a good idea to make them defensive and robust if you+can.+.PP+Here are some examples:+.IP \(bu 2+Does foo contain a non\-zero number ?+\f[CR]if %foo [1\-9]\f[R]+.IP \(bu 2+Is it negative ?+\f[CR]if %foo \-\f[R]+.IP \(bu 2+Is it non\-negative ?+\f[CR]if ! %foo \-\f[R]+.IP \(bu 2+Is it >= 10 ?+\f[CR]if %foo [1\-9][0\-9]+\(rs.\f[R] (assuming a decimal period and no+leading zeros)+.IP \(bu 2+Is it >= 10 and < 20 ?+\f[CR]if %foo \(rsb1[0\-9]\(rs.\f[R]+.PP+.SS \f[CR]ifs\f[R]+An \(dqifs table\(dq is a more compact way to write many if rules.+.IP \(bu 2+The first line begins with \f[CR]ifs\f[R], then one or more hledger+field names, all separated by a delimiter character (any punctuation+character, your choice) plus optional whitespace.+(An older form is also supported for backward compatibility:+\f[CR]if\f[R] followed by the delimiter with no space between them.)+.IP \(bu 2+The following lines begin with a matcher, then values to assign to each+of those hledger fields.+.IP \(bu 2+Comment lines, beginning with \f[CR];\f[R] or \f[CR]#\f[R] (optionally+indented), are also allowed.+.IP \(bu 2+A blank line (or the end of the file) ends the table.+.PP+Eg:+.IP+.EX+ifs | HLEDGERFIELD1 | HLEDGERFIELD2 | ...+MATCHER | VALUE | VALUE | ...+MATCHER | VALUE | VALUE | ...+MATCHER | VALUE | VALUE | ...+<empty line>+.EE+.PP+This means: for each line in turn, if the matcher matches the current+CSV record, assign all of the non\-blank values on that line, without+their surrounding whitespace, to the corresponding hledger fields.+All of the lines are processed, so later lines may override earlier+ones.+Except for the blank/whitespace handling, it\(aqs equivalent to writing+these if rules:+.IP+.EX+if MATCHER+ HLEDGERFIELD1 VALUE+ HLEDGERFIELD2 VALUE+ ...++if MATCHER+ HLEDGERFIELD1 VALUE+ HLEDGERFIELD2 VALUE+ ...++if MATCHER+ HLEDGERFIELD1 VALUE+ HLEDGERFIELD2 VALUE+ ...+.EE+.PP+Because every matching row is applied in order, the last one that+matches wins.+To supply a default, set the field before the table (or put a catch\-all+matcher such as \f[CR].*\f[R] as the first row); later, more\-specific+rows will override it when they match.+.IP+.EX+account2 expenses:unknown++ifs | account2+WHOLE FOODS | expenses:food+WHOLE FOODS.*organic | expenses:food:organic+.EE+.PP+In this example a transaction whose description contains \(dqWHOLE FOODS+organic\(dq matches both WHOLE FOODS rows; the last assignment is the+one that remains.+.PP+The \f[CR]skip\f[R], \f[CR]end\f[R] and \f[CR]merge\f[R] actions can+also be table columns.+Write a number in the cell on lines where the action should happen, and+leave it blank on other lines.+For \f[CR]skip\f[R] and \f[CR]merge\f[R] the number is how many records+to skip or merge (1 or more); for \f[CR]end\f[R], write 1 (any+non\-blank value will end).+Eg:+.IP+.EX+ifs | account2 | skip+atm withdrawal fee | expenses:banking |+transfer to savings | | 1+.EE+.PP+The delimiter must appear the same number of times in each line of the+table, and it must not appear in the field names, matchers, or values+used in the table (though inside \f[CR]%{...}\f[R] expressions is ok).+You cannot escape it with a backslash.+.PP+Note, the delimiter in an ifs table is unrelated to the one used in the+data file (consider avoiding \f[CR],\f[R] or \f[CR];\f[R], because they+look confusing).+.PP+In fact, it\(aqs hard to find a delimiter character that never clashes+with anything, so the flexibility can be useful.+Some examples:+.IP+.EX+# | as delimiter; can use a leading !, can\(aqt use regex | operator+ifs | account2 | comment+! %amount [0\-9][0\-9]+\(rs. | expenses:misc |+%desc amazon | expenses:shopping |+%desc amzn | expenses:shopping |+%amount [0\-9]{4,} | | TODO: large amount, check it+.EE+.IP+.EX+# ! as delimiter; can\(aqt use leading !, can use regex |+ifs ! account2+%desc amazon|amzn ! expenses:shopping+.EE+.IP+.EX+# \(ga as delimiter; can use both leading ! and regex |+ifs \(ga account2+! %amount [0\-9][0\-9]+\(rs. \(ga expenses:misc+%desc amazon|amzn \(ga expenses:shopping+.EE+.SS \f[CR]end\f[R]+The word \f[CR]end\f[R], used inside an \f[CR]if\f[R] or \f[CR]ifs\f[R]+rule, tells hledger to skip the current record and remaining records in+the current CSV file, whenever the condition is true.+Eg:+.IP+.EX+# if an empty record is seen (assuming five fields), ignore the rest of the CSV file+if ,,,,+ end+.EE+.SS \f[CR]merge\f[R]+.IP+.EX+if MATCHER+ merge N+.EE+.PP+Some banks and brokers export a single transaction as multiple CSV+records \- eg a currency conversion or stock trade, with each side of+the trade on its own row.+The \f[CR]merge\f[R] rule combines such related records, so that they+can generate a single journal transaction.+.PP+When a record matches an \f[CR]if\f[R] rule containing+\f[CR]merge N\f[R] (the word \f[CR]merge\f[R] followed by a number, or+no number, meaning 1), the next N records are joined onto the matched+record, forming a group of rows.+Conversion then proceeds as usual, with the whole group generating one+transaction.+.PP+Fields of the later rows are referenced by adding a \f[CR]_ROWNUM\f[R]+suffix (row number 2 or greater) to the usual field name or number:+\f[CR]%amt_2\f[R] or \f[CR]%4_2\f[R] is row 2\(aqs \f[CR]amt\f[R]/fourth+field.+Unsuffixed references (\f[CR]%amt\f[R], \f[CR]%4\f[R]) always mean the+first row, so the same \f[CR]fields\f[R] list describes every row.+A reference to a row that isn\(aqt there (eg in an unmerged record) just+has an empty value.+And if you have declared a field name that looks like+\f[CR]NAME_ROWNUM\f[R], it keeps its declared meaning; the suffix+interpretation is only a fallback.+.PP+For example, to convert this two\-row currency conversion:+.IP+.EX+2026\-09\-01,PAYMENT,coffee,\-3.50,USD+2026\-09\-02,CONVERT,converted USD to EUR,\-100.00,USD+2026\-09\-02,CONVERT,converted USD to EUR,90.00,EUR+.EE+.IP+.EX+fields date, type, desc, amt, cur+description %desc+account1 assets:bank:%cur+amount1 %amt %cur++# a conversion\(aqs second row holds the amount received; make it posting 2+if %type CONVERT+ merge+ account2 assets:bank:%cur_2+ amount2 %amt_2 %cur_2++if %type PAYMENT+ account2 expenses:unknown+.EE+.IP+.EX+$ hledger print \-f conversion.csv+2026\-09\-01 coffee+ assets:bank:USD \-3.50 USD+ expenses:unknown++2026\-09\-02 converted USD to EUR+ assets:bank:USD \-100.00 USD+ assets:bank:EUR 90.00 EUR+.EE+.PP+Things to note:+.IP \(bu 2+\f[CR]merge\f[R] can also be used as a top\-level rule+(unconditionally), useful for files where every transaction is exactly+N+1 rows.+.IP \(bu 2+\f[CR]skip\f[R] and \f[CR]end\f[R] rules are applied before row merging+\- skipped records don\(aqt count toward a merge group.+.IP \(bu 2+The rows of a group must be consecutive in the file (ignoring skipped+records), and the merging record must be the first of them.+.IP \(bu 2+Matchers which (if successful) will trigger a \f[CR]merge\f[R] rule, can+only usefully reference the first row\(aqs fields \- the other row+fields will be empty at this stage.+.IP \(bu 2+But once a \f[CR]merge\f[R] rule has been evaluated, later \f[CR]if\f[R]+rules can see the whole group; eg a whole\-record matcher will see all+of its rows combined as one, and field matchers can use+\f[CR]%FIELD_ROWNUM\f[R] references.+.IP \(bu 2+If fewer than N records remain in the file, just those are merged.+.SS \f[CR]include\f[R]+.IP+.EX+include RULESFILE+.EE+.PP+This includes the contents of another CSV rules file at this point.+\f[CR]RULESFILE\f[R] is an absolute file path or a path relative to the+current file\(aqs directory.+This can be useful for sharing common rules between several rules files,+eg:+.IP+.EX+# someaccount.csv.rules++## someaccount\-specific rules+fields date,description,amount+account1 assets:someaccount+account2 expenses:misc++## common rules+include categorisation.rules+.EE+.PP+Since included rules are effectively inlined, and since for most rules+the last declaration wins, you can override an included file\(aqs rules+by writing rules after the \f[CR]include\f[R] line.+.SS Working with CSV+Some tips for creating rules and importing CSV data regularly:+.SS CSV rules examples+For real\-world rules files for many banks, brokers, exchanges and apps,+see the hledger CSV rules library in the hledger repo.+These aren\(aqt necessarily maintained, and may need adapting, but they+are a good source of ideas and examples.+.SS Rapid feedback+It\(aqs a good idea to get rapid feedback while creating/troubleshooting+CSV rules.+Here\(aqs a good way, using entr from eradman.com/entrproject:+.IP+.EX+$ ls foo.csv* | entr bash \-c \(aqecho \-\-\-\-; hledger \-f foo.csv print desc:SOMEDESC\(aq+.EE+.PP+A desc: query (eg) is used to select just one, or a few, transactions of+interest.+\(dqbash \-c\(dq is used to run multiple commands, so we can echo a+separator each time the command re\-runs, making it easier to read the+output.+.SS Well factored rules+Some things that can help reduce duplication and complexity in rules+files:+.IP \(bu 2+Extracting common rules usable with multiple CSV files into a+\f[CR]common.rules\f[R], and adding \f[CR]include common.rules\f[R] to+each CSV\(aqs rules file.+.IP \(bu 2+Splitting \f[CR]if\f[R] rules into smaller \f[CR]if\f[R] rules,+extracting the frequently used parts.+.SS Deduplicating, importing+When you download a CSV file periodically, eg to get your latest bank+transactions, the new file may overlap with the old one, containing some+of the same records.+.PP+The import command will (a) detect the new transactions, and (b) append+just those transactions to your main journal.+It is idempotent, so you don\(aqt have to remember how many times you+ran it or with which version of the CSV.+(It keeps state in a hidden \f[CR].latest.FILE.csv\f[R] file.)+This is the easiest way to import CSV data.+Eg:+.IP+.EX+# download the latest CSV files, then run this command.+# Note, no \-f flags needed here.+$ hledger import *.csv [\-\-dry]+.EE+.PP+This method works for most CSV files.+(Where records have a stable chronological order, and new records appear+only at the new end.)+.PP+A number of other tools and workflows, hledger\-specific and otherwise,+exist for converting, deduplicating, classifying and managing CSV data.+See:+.IP \(bu 2+https://hledger.org/workflows.html#comparing\-csv\-workflows+.IP \(bu 2+https://hledger.org/doc.html#setups\-and\-workflows+.IP \(bu 2+https://plaintextaccounting.org \-> data import/conversion+.SS Valid transactions+After reading a CSV file, hledger post\-processes and validates the+generated journal entries as it would for a journal file \- balancing+them, applying balance assignments, and canonicalising amount styles.+Any errors at this stage will be reported in the usual way, displaying+the problem entry.+.PP+There is one exception: balance assertions, if you have generated them,+will not be checked, since normally these will work only when the CSV+data is part of the main journal.+If you do need to check balance assertions generated from CSV right+away, pipe into another hledger:+.IP+.EX+$ hledger \-f file.csv print | hledger \-f\- print+.EE+.SS How CSV rules are evaluated+Here\(aqs how to think of CSV rules being evaluated.+If you get a confusing error while reading a CSV file, it may help to+try to understand which of these steps is failing:+.IP "1." 3+Any included rules files are inlined, from top to bottom, depth first+(scanning each included file for further includes, recursively, before+proceeding).+.IP "2." 3+Top level rules (\f[CR]date\-format\f[R], \f[CR]fields\f[R],+\f[CR]newest\-first\f[R], \f[CR]skip\f[R] etc) are read, top to bottom.+\(dqTop level rules\(dq means non\-conditional rules.+If a rule occurs more than once, the last one wins; except for the+\f[CR]skip\f[R] rule, where the first one wins, and the+\f[CR]source\f[R] rule, which may occur only once.+A rule written after an \f[CR]include\f[R] would override the same rule+in the included file.+.IP "3." 3+The CSV file is read as text.+Any non\-ascii characters will be decoded using the text encoding+specified by the \f[CR]encoding\f[R] rule, otherwise the system+locale\(aqs text encoding.+.IP "4." 3+Any top\-level skip or end rule is applied.+\f[CR]skip [N]\f[R] immediately skips the current or next N CSV records;+\f[CR]end\f[R] immediately skips all remaining CSV records (not normally+used at top level).+.IP "5." 3+Now any remaining CSV records are processed.+For each CSV record, in file order:+.RS 4+.IP \(bu 2+Is there a conditional skip/end rule that applies for this record ?+Search the \f[CR]if\f[R] rules, from top to bottom, for a succeeding one+containing a \f[CR]skip\f[R] or \f[CR]end\f[R] rule.+If found, skip the specified number of CSV records, then continue at 5.+.PD 0+.P+.PD+Otherwise...+.IP \(bu 2+Is there a \f[CR]merge\f[R] rule that applies for this record (top level+or conditional) ?+If so, join the next N CSV records onto this record, making one combined+record.+.IP \(bu 2+Do some basic validation on this CSV record (eg, check that it has at+least two fields).+.IP \(bu 2+For each hledger field (\f[CR]date\f[R], \f[CR]description\f[R],+\f[CR]account1\f[R], etc.):+.RS 2+.IP "1." 3+Get the field\(aqs assigned value, first searching top level+assignments, made directly or by the \f[CR]fields\f[R] rule, then+assignments made inside succeeding \f[CR]if\f[R] rules.+If there are more than one, the last one wins (though it can include the+previous one\(aqs value with \f[CR]%{FIELDNAME}\f[R]).+.IP "2." 3+Compute the field\(aqs actual value (as text), by interpolating any+%CSVFIELD references and %{...} expressions within the assigned value+(which may use other hledger fields\(aq values, computing them first);+or by choosing a default value if there was no assignment.+.RE+.IP \(bu 2+Generate a hledger transaction from the hledger field values, parsing+them if needed (eg from text to an amount).+.RE+.PP+This is all done by the CSV reader, one of several readers hledger can+use to read transactions from an input file.+When all input files have been read successfully, their transactions are+passed to whichever hledger command the user specified.+.PP+.SH Timeclock+hledger can read time logs in the timeclock time logging format of+timeclock.el.+As with Ledger, hledger\(aqs timeclock format is a subset/variant of+timeclock.el\(aqs.+.PP+hledger\(aqs timeclock format was updated in hledger 1.43 and 1.50.+If your old time logs are rejected, you should adapt them to modern+hledger; for now, you can restore the pre\-1.43 behaviour with the+\f[CR]\-\-old\-timeclock\f[R] flag.+.PP+Here is the timeclock format (in hledger 1.50+):+.IP+.EX+# Comment lines like these, and blank lines, are ignored:+# comment line+; comment line+* comment line++# Lines beginning with b, h, or capital O are also ignored, for compatibility:+b SIMPLEDATE HH:MM[:SS][+\-ZZZZ][ TEXT]+h SIMPLEDATE HH:MM[:SS][+\-ZZZZ][ TEXT]+O SIMPLEDATE HH:MM[:SS][+\-ZZZZ][ TEXT]++# Lines beginning with i or o are are clock\-in / clock\-out entries:+i SIMPLEDATE HH:MM[:SS][+\-ZZZZ] ACCOUNT[ DESCRIPTION][;COMMENT]]+o SIMPLEDATE HH:MM[:SS][+\-ZZZZ][ ACCOUNT][;COMMENT]+.EE+.PP+The date is a hledger simple date (YYYY\-MM\-DD or similar).+The time parts must use two digits.+The seconds are optional.+A + or \- four\-digit time zone is accepted for compatibility, but+currently ignored; times are always interpreted as a local time.+.PP+In clock\-in entries (\f[CR]i\f[R]), the account name is required.+A transaction description, separated from the account name by 2+ spaces,+is optional.+A transaction comment, beginning with \f[CR];\f[R], is also optional.+(Indented following comment lines are also allowed, as in journal+format.)+.PP+Clock\-out entries (\f[CR]o\f[R]) have no description, but can have a+comment if you wish.+A clock\-in and clock\-out pair form a \(dqtransaction\(dq posting some+number of hours to an account \- also known as a session.+Eg:+.IP+.EX+i 2015/03/30 09:00:00 session1+o 2015/03/30 10:00:00+.EE+.IP+.EX+$ hledger \-f a.timeclock print+2015\-03\-30 * 09:00\-10:00+ (session1) 1.00h+.EE+.PP+Clock\-ins and clock\-outs are matched by their account/session name.+If a clock\-out does not specify a name, the most recent unclosed+clock\-in is closed.+You can have multiple sessions active simultaneously.+Entries are processed in the order they are parsed.+Sessions spanning more than one day are automatically split at day+boundaries.+.PP+Eg, the following time log:+.IP+.EX+i 2015/03/30 09:00:00 some account optional description after 2 spaces ; optional comment, tags:+o 2015/03/30 09:20:00+i 2015/03/31 22:21:45 another:account+o 2015/04/01 02:00:34+i 2015/04/02 12:00:00 another:account ; this demonstrates multiple sessions being clocked in+i 2015/04/02 13:00:00 some account+o 2015/04/02 14:00:00+o 2015/04/02 15:00:00 another:account+.EE+.PP+generates these transactions:+.IP+.EX+$ hledger \-f t.timeclock print+2015\-03\-30 * optional description after 2 spaces ; optional comment, tags:+ (some account) 0.33333333h++2015\-03\-31 * 22:21\-23:59+ (another:account) 1.6375h++2015\-04\-01 * 00:00\-02:00+ (another:account) 2.00944444h++2015\-04\-02 * 12:00\-15:00 ; this demonstrates multiple sessions being clocked in+ (another:account) 3.00h++2015\-04\-02 * 13:00\-14:00+ (some account) 1.00h+.EE+.PP+Here is a sample.timeclock to download and some queries to try:+.IP+.EX+$ hledger \-f sample.timeclock balance # current time balances+$ hledger \-f sample.timeclock register \-p 2009/3 # sessions in march 2009+$ hledger \-f sample.timeclock register \-p weekly \-\-depth 1 \-\-empty # time summary by week+.EE+.PP+To generate time logs, ie to clock in and clock out, you could:+.IP \(bu 2+use these shell aliases at the command line:+.RS 2+.IP+.EX+alias ti=\(aqecho i \(gadate \(dq+%Y\-%m\-%d %H:%M:%S\(dq\(ga $* >>$TIMELOG\(aq+alias to=\(aqecho o \(gadate \(dq+%Y\-%m\-%d %H:%M:%S\(dq\(ga >>$TIMELOG\(aq+.EE+.RE+.IP \(bu 2+or Emacs\(aqs built\-in timeclock.el, or the extended timeclock\-x.el,+and perhaps the extras in ledgerutils.el+.IP \(bu 2+or use the old \f[CR]ti\f[R] and \f[CR]to\f[R] scripts in the ledger 2.x+repository.+These rely on a \(dqtimeclock\(dq executable which I think is just the+ledger 2 executable renamed.+.PP+.SH Timedot+\f[CR]timedot\f[R] format is hledger\(aqs human\-friendly time logging+format.+Compared to \f[CR]timeclock\f[R] format, it is more convenient for+quick, approximate, and retroactive time logging, and more+human\-readable (you can see at a glance where time was spent).+A quick example:+.IP+.EX+2023\-05\-01+hom:errands .... .... ; two hours; the space is ignored+fos:hledger:timedot .. ; half an hour+per:admin:finance ; no time spent yet+.EE+.PP+hledger reads this as a transaction on this day with three (unbalanced)+postings, where each dot represents 0.25 (of an hour, we usually+assume).+.IP+.EX+$ hledger \-f a.timedot print # .timedot file extension (or timedot: prefix) is required+2023\-05\-01 *+ (hom:errands) 2.00 ; two hours; the space is ignored+ (fos:hledger:timedot) 0.50 ; half an hour+ (per:admin:finance) 0.00 ; no time spent yet+.EE+.PP+A timedot file specifies a series of transactions, usually one per day.+(Unlike in a journal file, these \(dqtransactions\(dq don\(aqt need to+balance; time logs use \(dqsingle entry accounting\(dq.)+.PP+Each transaction begins with a \f[B]date line\f[R]: a line whose first+word looks like a simple date, ie three groups of digits separated by+\f[CR]\-\f[R], \f[CR]/\f[R], or \f[CR].\f[R] (if these cannot be parsed+as a valid date, an error is raised).+After the date, on the same line, there can optionally be a transaction+description, and after \f[CR];\f[R], a transaction comment (possibly+containing tags).+.PP+After the date line are zero or more \f[B]posting lines\f[R].+A timedot posting line begins with a hledger\-style account name,+optionally indented.+After the account name there are \f[B]two or more spaces\f[R] and then a+\f[B]timedot amount\f[R].+(Or nothing, which is equivalent to a zero amount.)+.PP+Timedot amounts can be written in several ways:+.IP \(bu 2+One or more \f[B]dots\f[R] (\f[CR].\f[R])+.PD 0+.P+.PD+Each dot represents a quarter hour.+(There\(aqs no commodity symbol, but usually we assume hours.)+Spaces can optionally be used for aligning or grouping dots, eg+\f[CR].... .... ..\f[R] is easy to read as 2.5 hours.+.IP \(bu 2+A \f[B]bare number\f[R] (integer or decimal)+.PD 0+.P+.PD+This can be more precise or more convenient, eg for large durations.+.IP \(bu 2+A \f[B]number followed by a time unit\f[R] (\f[CR]s\f[R], \f[CR]m\f[R],+\f[CR]h\f[R], \f[CR]d\f[R], \f[CR]w\f[R], \f[CR]mo\f[R], or+\f[CR]y\f[R])+.PD 0+.P+.PD+representing seconds, minutes, hours, days, weeks, months or years,+which will be converted to hours using these ratios: 60s = 1m, 60m = 1h,+24h = 1d, 7d = 1w, 30d = 1mo, 365d = 1y.+This allows use of more convenient time units.+.IP \(bu 2+One or more \f[B]timedot letters\f[R]+.PD 0+.P+.PD+These work like dots, except they also generate a posting tag+\f[CR]t:\f[R] (short for \(dqtype\(dq) with the letter as its value, and+a separate posting for each of the letter values.+This adds a second dimension of categorisation \- in addition to account+name, you\(aqll have the \f[CR]t\f[R] tag\(aqs value, which can be shown+in reports with \f[CR]\-\-pivot t\f[R], \f[CR]\-\-pivot acct:t\f[R],+etc.+.PP+Posting lines can end with a hledger\-style posting comment (text after+\f[CR];\f[R]), optionally containing tags.+.PP+Lines beginning with \f[CR]#\f[R] or \f[CR];\f[R] are \f[B]comment+lines\f[R], and ignored.+Blank lines are also ignored.+.PP+There is some additional support for users of Emacs org mode:+.IP \(bu 2+Before the first date line, lines beginning with \f[CR]*\f[R] are also+treated as comments, and ignored.+This allows top\-level org headings in a timedot file.+.IP \(bu 2+From the first date line onward, org heading prefixes (one or more+\f[CR]*\f[R]\(aqs followed by a space) are ignored, with the rest of the+line being parsed normally.+This allows timedot date or posting lines to also be org headings.+.PP+Timedot files don\(aqt support directives like journal files.+So a common pattern is to have a main journal file that contains any+needed directives, and then includes the timedot file+(\f[CR]include time.timedot\f[R]).+.SS Timedot examples+Numbers:+.IP+.EX+2016/2/3+inc:client1 4+fos:hledger 3h+biz:research 60m+.EE+.PP+Dots:+.IP+.EX+# on this day, 6h was spent on client work, 1.5h on haskell FOSS work, etc.+2016/2/1+inc:client1 .... .... .... .... .... ....+fos:haskell .... ..+biz:research .++2016/2/2+inc:client1 .... ....+biz:research .+.EE+.IP+.EX+$ hledger \-f a.timedot print date:2016/2/2+2016\-02\-02 *+ (inc:client1) 2.00+ (biz:research) 0.25+.EE+.IP+.EX+$ hledger \-f a.timedot bal \-\-daily+Balance changes in 2016\-02\-01..2016\-02\-02:++ || 2016\-02\-01 2016\-02\-02 +==============++========================+ biz:research || 0.25 0.25 + fos:haskell || 1.50 0 + inc:client1 || 6.00 2.00 +\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ || 7.75 2.25 +.EE+.PP+Letters:+.IP+.EX+# Activity types:+# c cleanup/catchup/repair+# e enhancement+# s support+# l learning/research++2023\-11\-01+work:adm ccecces+.EE+.IP+.EX+$ hledger \-f a.timedot print+2023\-11\-01 *+ (work:adm) 1.00 ; t:c+ (work:adm) 0.50 ; t:e+ (work:adm) 0.25 ; t:s+.EE+.IP+.EX+$ hledger \-f a.timedot bal+ 1.75 work:adm+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ 1.75 +.EE+.IP+.EX+$ hledger \-f a.timedot bal \-\-pivot t+ 1.00 c+ 0.50 e+ 0.25 s+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ 1.75 +.EE+.PP+Org:+.IP+.EX+* 2023 Work Diary+** Q1+*** 2023\-02\-28+**** DONE+yoga ....+**** BEGUN+hom:chores+ cleaning ...+ water plants+ outdoor \- one full watering can+ indoor \- light watering+**** TODO+adm:planning:trip+*** LATER+.EE+.PP+Using \f[CR].\f[R] as account name separator:+.IP+.EX+2016/2/4+fos.hledger.timedot 4h+fos.ledger ..+.EE+.IP+.EX+$ hledger \-f a.timedot \-\-alias \(aq/\(rs./=:\(aq bal \-t+ 4.50 fos+ 4.00 hledger:timedot+ 0.50 ledger+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ 4.50 +.EE+.SH PART 4: CONCEPTS+.SH Time periods+.SS Report start & end date+Most hledger reports will by default show the full time period+represented by the journal.+The report start date will be the earliest transaction or posting date,+and the report end date will be the latest transaction, posting, or+market price date.+.PP+Often you will want to see a shorter period, such as the current month.+You can specify a start and/or end date with the+\f[CR]\-b/\-\-begin\f[R], \f[CR]\-e/\-\-end\f[R], or+\f[CR]\-p/\-\-period\f[R] options, or a \f[CR]date:\f[R] query argument,+described below.+All of these accept the smart date syntax, also described below.+.PP+End dates are exclusive; specify the day after the last day you want to+see in the report.+.PP+When dates are specified by multiple options, the last (right\-most)+option wins.+And when \f[CR]date:\f[R] queries and date options are combined, the+report period will be their intersection.+.PP+Examples:+.TP+\f[CR]\-b 2016/3/17\f[R]+beginning on St.+Patrick\(cqs day 2016+.TP+\f[CR]\-e 12/1\f[R]+ending at the start of December 1st in the current year+.TP+\f[CR]\-p \(aqthis month\(aq\f[R]+during the current month+.TP+\f[CR]\-p thismonth\f[R]+same as above, spaces are optional+.TP+\f[CR]\-b 2023\f[R]+beginning on the first day of 2023+.TP+\f[CR]date:2023..\f[R] or \f[CR]date:2023\-\f[R]+same as above+.PP+\f[CR]\-b 2024 \-e 2025 \-p \(aq2000 to 2030\(aq date:2020\-01 date:2020\f[R]+:+.PD 0+.P+.PD+during January 2020 (the smallest common period, with the \-p overriding+\-b and \-e)+.SS Smart dates+In hledger\(aqs user interfaces (though not in the journal file), you+can optionally use \(dqsmart date\(dq syntax.+Smart dates can be written with english words, can be relative, and can+have parts omitted.+Missing parts are inferred as 1, when needed.+Smart dates can be interpreted as dates or periods depending on the+context.+.PP+Examples:+.PP+\f[CR]2004\-01\-01\f[R], \f[CR]2004/10/1\f[R], \f[CR]2004.9.1\f[R],+\f[CR]20240504\f[R], \f[CR]2024Q1\f[R] :+.PD 0+.P+.PD+Exact dates.+The year must have at least four digits, the month must be 1\-12, the+day must be 1\-31, the separator can be \f[CR]\-\f[R] or \f[CR]/\f[R] or+\f[CR].\f[R] or nothing.+The q can be upper or lower case and the quarter number must be 1\-4.+.TP+\f[CR]2004\-10\f[R]+start of month+.TP+\f[CR]2004q3\f[R]+start of third quarter of 2004+.TP+\f[CR]q3\f[R]+start of third quarter of current year+.TP+\f[CR]2004\f[R]+start of year+.TP+\f[CR]10/1\f[R] or \f[CR]oct\f[R] or \f[CR]october\f[R]+October 1st in current year+.TP+\f[CR]21\f[R]+21st day in current month+.TP+\f[CR]yesterday, today, tomorrow\f[R]+\-1, 0, 1 days from today+.TP+\f[CR]last/this/next day/week/month/quarter/year\f[R]+\-1, 0, 1 periods from the current period+.TP+\f[CR]last/this/next tuesday\f[R]+the previous occurrence of the named day, or the next occurrence after+today+.TP+\f[CR]last/this/next february\f[R]+the previous occurrence of 1st of the named month, or the next+occurrence after the current month+.TP+\f[CR]in n days/weeks/months/quarters/years\f[R]+n periods from the current period+.TP+\f[CR]n days/weeks/months/quarters/years ahead\f[R]+n periods from the current period+.TP+\f[CR]n days/weeks/months/quarters/years ago\f[R]+\-n periods from the current period+.TP+\f[CR]20181201\f[R]+8 digit YYYYMMDD with valid year month and day+.TP+\f[CR]201812\f[R]+6 digit YYYYMM with valid year and month+.PP+Dates with no separators are allowed but might give surprising results+if mistyped:+.IP \(bu 2+\f[CR]20181301\f[R] (YYYYMMDD with an invalid month) is parsed as an+eight\-digit year+.IP \(bu 2+\f[CR]20181232\f[R] (YYYYMMDD with an invalid day) gives a parse error+.IP \(bu 2+\f[CR]201801012\f[R] (a valid YYYYMMDD followed by additional digits)+gives a parse error+.PP+The meaning of relative dates depends on today\(aqs date.+If you need to test or reproduce old reports, you can use the+\f[CR]\-\-today\f[R] option to override that.+(Except for periodic transaction rules, which are not affected by+\f[CR]\-\-today\f[R].)+.SS Report intervals+A report interval can be specified so that reports like register,+balance or activity become multi\-period, showing each subperiod as a+separate row or column.+.PP+The following standard intervals can be enabled with command\-line+flags:+.IP \(bu 2+\f[CR]\-D/\-\-daily\f[R]+.IP \(bu 2+\f[CR]\-W/\-\-weekly\f[R]+.IP \(bu 2+\f[CR]\-M/\-\-monthly\f[R]+.IP \(bu 2+\f[CR]\-Q/\-\-quarterly\f[R]+.IP \(bu 2+\f[CR]\-Y/\-\-yearly\f[R]+.PP+More complex intervals can be specified using \f[CR]\-p/\-\-period\f[R],+described below.+.SS Date adjustments+.SS Start date adjustment+If you let hledger infer a report\(aqs start date, it will adjust the+date to the previous natural boundary of the report interval, for+convenient periodic reports.+(If you don\(aqt want that, specify a start date.)+.PP+For example, if the journal\(aqs first transaction is on january 10th,+.IP \(bu 2+\f[CR]hledger register\f[R] (no report interval) will start the report+on january 10th.+.IP \(bu 2+\f[CR]hledger register \-\-monthly\f[R] will start the report on the+previous month boundary, january 1st.+.IP \(bu 2+\f[CR]hledger register \-\-monthly \-\-begin 1/5\f[R] will start the+report on january 5th [1].+.PP+The start date of transactions generated by periodic transaction rules+is chosen separately; see Forecast period, in detail.+.SS End date adjustment+A report\(aqs end date is always adjusted to include a whole number of+intervals, so that the last subperiod has the same length as the others.+.PP+For example, if the journal\(aqs last transaction is on february 20th,+.IP \(bu 2+\f[CR]hledger register\f[R] will end the report on february 20th.+.IP \(bu 2+\f[CR]hledger register \-\-monthly\f[R] will end the report at the end+of february.+.IP \(bu 2+\f[CR]hledger register \-\-monthly \-\-end 2/14\f[R] also will end the+report at the end of february (overriding the requested end date).+.IP \(bu 2+\f[CR]hledger register \-\-monthly \-\-begin 1/5 \-\-end 2/14\f[R] will+end the report on march 4th.+.SS Period expressions+The \f[CR]\-p/\-\-period\f[R] option specifies a period expression,+which is a compact way of expressing a start date, end date, and/or+report interval.+.PP+Here\(aqs a period expression with a start and end date (specifying the+first quarter of 2009):+.PP+.TS+tab(@);+l.+T{+\f[CR]\-p \(dqfrom 2009/1/1 to 2009/4/1\(dq\f[R]+T}+.TE+.PP+Several keywords like \(dqfrom\(dq and \(dqto\(dq are supported for+readability; these are optional.+\(dqto\(dq can also be written as \(dq..\(dq or \(dq\-\(dq.+(Except that a lone day number, directly after a \(dq\-\(dq with no+spaces, is not accepted; eg \f[CR]2026\-13\f[R] is more likely a+mistyped date than \(dq2026 to the 13th of this month\(dq, so it\(aqs an+error.+To mean the latter, write \f[CR]2026..13\f[R].)+The spaces are also optional, as long as you don\(aqt run two dates+together.+So the following are equivalent to the above:+.PP+.TS+tab(@);+l.+T{+\f[CR]\-p \(dq2009/1/1 2009/4/1\(dq\f[R]+T}+T{+\f[CR]\-p2009/1/1to2009/4/1\f[R]+T}+T{+\f[CR]\-p2009/1/1..2009/4/1\f[R]+T}+.TE+.PP+Dates are smart dates, so if the current year is 2009, these are also+equivalent to the above:+.PP+.TS+tab(@);+l.+T{+\f[CR]\-p \(dq1/1 4/1\(dq\f[R]+T}+T{+\f[CR]\-p \(dqjan\-apr\(dq\f[R]+T}+T{+\f[CR]\-p \(dqthis year to 4/1\(dq\f[R]+T}+.TE+.PP+If you specify only one date, the missing start or end date will be the+earliest or latest transaction date in the journal:+.PP+.TS+tab(@);+l l.+T{+\f[CR]\-p \(dqfrom 2009/1/1\(dq\f[R]+T}@T{+everything after january 1, 2009+T}+T{+\f[CR]\-p \(dqsince 2009/1\(dq\f[R]+T}@T{+the same, since is a synonym+T}+T{+\f[CR]\-p \(dqfrom 2009\(dq\f[R]+T}@T{+the same+T}+T{+\f[CR]\-p \(dqto 2009\(dq\f[R]+T}@T{+everything before january 1, 2009+T}+.TE+.PP+You can also specify a period by writing a single partial or full date:+.PP+.TS+tab(@);+lw(14.5n) lw(55.5n).+T{+\f[CR]\-p \(dq2009\(dq\f[R]+T}@T{+the year 2009; equivalent to \(lq2009/1/1 to 2010/1/1\(rq+T}+T{+\f[CR]\-p \(dq2009/1\(dq\f[R]+T}@T{+the month of january 2009; equivalent to \(lq2009/1/1 to 2009/2/1\(rq+T}+T{+\f[CR]\-p \(dq2009/1/1\(dq\f[R]+T}@T{+the first day of 2009; equivalent to \(lq2009/1/1 to 2009/1/2\(rq+T}+.TE+.PP+or by using the \(dqQ\(dq quarter\-year syntax (case insensitive):+.PP+.TS+tab(@);+lw(15.3n) lw(54.7n).+T{+\f[CR]\-p \(dq2009Q1\(dq\f[R]+T}@T{+first quarter of 2009, equivalent to \(lq2009/1/1 to 2009/4/1\(rq+T}+T{+\f[CR]\-p \(dqq4\(dq\f[R]+T}@T{+fourth quarter of the current year+T}+.TE+.SS Period expressions with a report interval+A period expression can also begin with a report interval, separated+from the start/end dates (if any) by a space or the word \f[CR]in\f[R]:+.PP+.TS+tab(@);+l.+T{+\f[CR]\-p \(dqweekly from 2009/1/1 to 2009/4/1\(dq\f[R]+T}+T{+\f[CR]\-p \(dqmonthly in 2008\(dq\f[R]+T}+T{+\f[CR]\-p \(dqquarterly\(dq\f[R]+T}+.TE+.SS More complex report intervals+Some more complex intervals can be specified within period expressions,+such as:+.IP \(bu 2+\f[CR]biweekly\f[R] (every two weeks)+.IP \(bu 2+\f[CR]fortnightly\f[R]+.IP \(bu 2+\f[CR]bimonthly\f[R] (every two months)+.IP \(bu 2+\f[CR]every day|week|month|quarter|year\f[R]+.IP \(bu 2+\f[CR]every N days|weeks|months|quarters|years\f[R]+.PP+Weekly on a custom day:+.IP \(bu 2+\f[CR]every Nth day of week\f[R] (\f[CR]th\f[R], \f[CR]nd\f[R],+\f[CR]rd\f[R], or \f[CR]st\f[R] are all accepted after the number)+.IP \(bu 2+\f[CR]every WEEKDAYNAME\f[R] (full or three\-letter english weekday+name, case insensitive)+.PP+Monthly on a custom day:+.IP \(bu 2+\f[CR]every Nth day [of month]\f[R] (\f[CR]31st day\f[R] will be+adjusted to each month\(aqs last day)+.IP \(bu 2+\f[CR]every Nth WEEKDAYNAME [of month]\f[R]+.PP+Yearly on a custom month and day:+.IP \(bu 2+\f[CR]every MM/DD [of year]\f[R] (month number and day of month number)+.IP \(bu 2+\f[CR]every MONTHNAME DDth [of year]\f[R] (full or three\-letter english+month name, case insensitive, and day of month number)+.IP \(bu 2+\f[CR]every DDth MONTHNAME [of year]\f[R] (equivalent to the above)+.PP+Examples:+.PP+.TS+tab(@);+lw(26.8n) lw(43.2n).+T{+\f[CR]\-p \(dqbimonthly from 2008\(dq\f[R]+T}@T{+T}+T{+\f[CR]\-p \(dqevery 2 weeks\(dq\f[R]+T}@T{+T}+T{+\f[CR]\-p \(dqevery 5 months from 2009/03\(dq\f[R]+T}@T{+T}+T{+\f[CR]\-p \(dqevery 2nd day of week\(dq\f[R]+T}@T{+periods will go from Tue to Tue+T}+T{+\f[CR]\-p \(dqevery Tue\(dq\f[R]+T}@T{+same+T}+T{+\f[CR]\-p \(dqevery 15th day\(dq\f[R]+T}@T{+period boundaries will be on 15th of each month+T}+T{+\f[CR]\-p \(dqevery 2nd Monday\(dq\f[R]+T}@T{+period boundaries will be on second Monday of each month+T}+T{+\f[CR]\-p \(dqevery 11/05\(dq\f[R]+T}@T{+yearly periods with boundaries on 5th of November+T}+T{+\f[CR]\-p \(dqevery 5th November\(dq\f[R]+T}@T{+same+T}+T{+\f[CR]\-p \(dqevery Nov 5th\(dq\f[R]+T}@T{+same+T}+.TE+.PP+Show historical balances at end of the 15th day of each month (N is an+end date, exclusive as always):+.IP+.EX+$ hledger balance \-H \-p \(dqevery 16th day\(dq+.EE+.PP+Group postings from the start of wednesday to end of the following+tuesday (N is both (inclusive) start date and (exclusive) end date):+.IP+.EX+$ hledger register checking \-p \(dqevery 3rd day of week\(dq+.EE+.SS Multiple weekday intervals+This special form is also supported:+.IP \(bu 2+\f[CR]every WEEKDAYNAME,WEEKDAYNAME,...\f[R] (full or three\-letter+english weekday names, case insensitive)+.PP+Also, \f[CR]weekday\f[R] and \f[CR]weekendday\f[R] are shorthand for+\f[CR]mon,tue,wed,thu,fri\f[R] and \f[CR]sat,sun\f[R].+.PP+This is mainly intended for use with \f[CR]\-\-forecast\f[R], to+generate periodic transactions on arbitrary days of the week.+It may be less useful with \f[CR]\-p\f[R], since it divides each week+into subperiods of unequal length, which is unusual.+(Related: #1632)+.PP+Examples:+.PP+.TS+tab(@);+lw(17.8n) lw(52.2n).+T{+\f[CR]\-p \(dqevery mon,wed,fri\(dq\f[R]+T}@T{+dates will be Mon, Wed, Fri; periods will be Mon\-Tue, Wed\-Thu,+Fri\-Sun+T}+T{+\f[CR]\-p \(dqevery weekday\(dq\f[R]+T}@T{+dates will be Mon, Tue, Wed, Thu, Fri; periods will be Mon, Tue, Wed,+Thu, Fri\-Sun+T}+T{+\f[CR]\-p \(dqevery weekendday\(dq\f[R]+T}@T{+dates will be Sat, Sun; periods will be Sat, Sun\-Fri+T}+.TE+.SH Queries+Many hledger commands accept query arguments, which restrict their scope+and let you report on a precise subset of your data.+Here\(aqs a quick overview of hledger\(aqs queries:+.IP \(bu 2+By default, a query argument is treated as a case\-insensitive substring+pattern for matching account names.+Eg:+.RS 2+.PP+\f[CR]dining groceries\f[R]+.PD 0+.P+.PD+\f[CR]car:fuel\f[R]+.PD 0+.P+.PD+.RE+.IP \(bu 2+Patterns containing spaces or other special characters must be enclosed+in single or double quotes:+.RS 2+.PP+\f[CR]\(aqpersonal care\(aq\f[R]+.PD 0+.P+.PD+.RE+.IP \(bu 2+Patterns are actually regular expressions, so you can add regexp+metacharacters for more precision (or you may need to backslash\-escape+certain characters; see \(dqRegular expressions\(dq above):+.RS 2+.PP+\f[CR]\(aq\(haexpenses\(rsb\(aq\f[R]+.PD 0+.P+.PD+\f[CR]\(aqfood$\(aq\f[R]+.PD 0+.P+.PD+\f[CR]\(aqfuel|repair\(aq\f[R]+.PD 0+.P+.PD+\f[CR]\(aqaccounts (payable|receivable)\(aq\f[R]+.PD 0+.P+.PD+.RE+.IP \(bu 2+To match something other than the account name, you can add a query type+prefix, such as:+.RS 2+.PP+\f[CR]date:202312\-\f[R]+.PD 0+.P+.PD+\f[CR]status:\f[R]+.PD 0+.P+.PD+\f[CR]desc:amazon\f[R]+.PD 0+.P+.PD+\f[CR]cur:USD\f[R]+.PD 0+.P+.PD+\f[CR]cur:\(rs\(rs$\f[R]+.PD 0+.P+.PD+\f[CR]amt:\(aq>0\(aq\f[R]+.PD 0+.P+.PD+\f[CR]change:\(aq>100\(aq\f[R], \f[CR]balance:\(aq<0\(aq\f[R] (match+report rows or entries by their change or balance, see below)+.PD 0+.P+.PD+\f[CR]acct:groceries\f[R] (but \f[CR]acct:\f[R] is the default, so we+usually don\(aqt bother writing it)+.PD 0+.P+.PD+.RE+.IP \(bu 2+To match in any field, or by date, use the \f[CR]find:\f[R] query type,+or \f[CR]::\f[R] for short:+.RS 2+.PP+\f[CR]::amazon\f[R]+.PD 0+.P+.PD+\f[CR]::2024\f[R]+.PD 0+.P+.PD+\f[CR]::amazon ::2024\f[R] (both must match)+.PD 0+.P+.PD+.RE+.IP \(bu 2+To negate a query, add a \f[CR]not:\f[R] prefix:+.RS 2+.PP+\f[CR]not:status:\(aq*\(aq\f[R]+.PD 0+.P+.PD+\f[CR]not:desc:\(aqopening|closing\(aq\f[R]+.PD 0+.P+.PD+\f[CR]not:cur:USD\f[R]+.PD 0+.P+.PD+.RE+.IP \(bu 2+Multiple query terms can be combined, as space\-separated queries Eg:+\f[CR]hledger print date:2022 desc:amazon desc:amzn\f[R] (show+transactions dated in 2022 whose description contains \(dqamazon\(dq or+\(dqamzn\(dq).+.PD 0+.P+.PD+.IP \(bu 2+Or more flexibly as boolean queries.+Eg:+\f[CR]hledger print expr:\(aqdate:2022 and (desc:amazon or desc:amzn) and not date:202210\(aq\f[R]+.PD 0+.P+.PD+.PP+All hledger commands use the same query language, but different commands+may interpret the query in different ways.+Here\(aqs the gist of it (see PART 2: COMMANDS above for the commands):+.IP \(bu 2+Transaction\-oriented commands (\f[CR]print\f[R], \f[CR]aregister\f[R],+\f[CR]close\f[R], \f[CR]import\f[R], \f[CR]descriptions\f[R]..)+try to match transactions (including the transaction\(aqs postings).+.IP \(bu 2+Posting\-oriented commands (\f[CR]register\f[R], \f[CR]balance\f[R],+\f[CR]balancesheet\f[R], \f[CR]incomestatement\f[R],+\f[CR]accounts\f[R]..)+try to match postings.+Postings inherit their transaction\(aqs attributes for querying+purposes, so transaction fields like date or description can still be+referenced in a posting query.+.IP \(bu 2+A few commands match in more specific ways.+(Eg \f[CR]aregister\f[R], which has a special first argument.)+.SS Query types+Here are the query types available.+.PP+In the ones which take a regular expression, an empty one (eg+\f[CR]desc:\f[R] or \f[CR]::\f[R]) matches anything.+(Except in \f[CR]cur:\f[R], which must match the whole symbol, so an+empty \f[CR]cur:\f[R] matches amounts with no commodity symbol.)+.SS acct: query+\f[B]\f[CB]acct:REGEX\f[B]\f[R], or just \f[B]\f[CB]REGEX\f[B]\f[R]+.PD 0+.P+.PD+Match account names containing this case insensitive regular expression.+.PD 0+.P+.PD+This is the default query type, so we usually don\(aqt bother writing+the \(dqacct:\(dq prefix.+.SS amt: query+\f[B]\f[CB]amt:N, amt:\(aq<N\(aq, amt:\(aq<=N\(aq, amt:\(aq>N\(aq, amt:\(aq>=N\(aq\f[B]\f[R],+optionally with a commodity symbol, eg \f[CR]amt:\(aq>$100\(aq\f[R] or+\f[CR]amt:\(aq>100 EUR\(aq\f[R]+.PD 0+.P+.PD+Match postings with an amount equal to, less than, or greater than N.+\f[CR]amt:\f[R] needs quotes to hide the less than/greater than sign+from the command line shell.+.PP+The comparison has two modes: if N is preceded by a + or \- sign (or is+0), the two signed numbers are compared.+Otherwise, the absolute magnitudes are compared, ignoring sign.+.PP+If N has a commodity symbol (before or after the number, quoted with+\f[CR]\(dq\f[R] if needed), only amounts in that commodity are compared;+a posting with none doesn\(aqt match.+Otherwise, amounts in any commodity are compared.+A posting whose amount has several commodities matches if any one of+them does.+.PP+Keep in mind that \f[CR]amt:\f[R] matches posting amounts, not account+balances.+To match accounts, or periods, by their change or balance, use+\f[CR]change:\f[R] or \f[CR]balance:\f[R].+.SS balance: and change: queries+\f[B]\f[CB]change:N, change:\(aq<N\(aq, change:\(aq<=N\(aq, change:\(aq>N\(aq, change:\(aq>=N\(aq\f[B]\f[R],+\f[B]\f[CB]balance:N, balance:\(aq<N\(aq, balance:\(aq<=N\(aq, balance:\(aq>N\(aq, balance:\(aq>=N\(aq\f[B]\f[R],+optionally with a commodity symbol, eg \f[CR]change:\(aq>$100\(aq\f[R]+or \f[CR]balance:\(aq<0 EUR\(aq\f[R]+.PD 0+.P+.PD+Match report rows (or entries) by their summed amounts:+\f[CR]change:\f[R] by the row\(aqs change, the sum of its postings;+\f[CR]balance:\f[R] by the row\(aqs balance, the sum of all its postings+up to the end of its period.+Unlike \f[CR]amt:\f[R], which tests each posting before postings are+added up, these test the amounts a report shows after adding them up.+Eg:+.IP+.EX+$ hledger bal expenses change:\(aq>100\(aq # expense accounts which changed by more than 100+$ hledger bal assets balance:\(aq<0\(aq # asset accounts with a negative balance+$ hledger reg gifts \-M change:\(aq>100\(aq # months with more than 100 in gift expenses+$ hledger areg checking balance:\(aq<0\(aq # the transactions after which checking was overdrawn+$ hledger print not:change:0 # entries with a tolerated imbalance or unbalanced virtual postings+.EE+.PP+The comparison works as with \f[CR]amt:\f[R]: signed if N has a + or \-+sign (or is 0), otherwise by absolute magnitude.+Like \f[CR]amt:\f[R], these test amounts\(aq real signs, not the signs+they are displayed with (after \f[CR]\-\-invert\f[R], or the sign+normalisation in \f[CR]balancesheet\f[R], \f[CR]incomestatement\f[R]+etc.); so \f[CR]incomestatement change:\(aq<\-1000\(aq\f[R] finds the+large revenues.+If N has a commodity symbol, only that commodity\(aqs part of the amount+is compared, and an amount with none of it doesn\(aqt match.+An amount with several commodities matches if any one of them does.+.PP+\f[CR]balance:\f[R] always means the actual balance, from the start of+the journal (or of the postings matched by the other query terms),+whether or not the report is a historical (\f[CR]\-H\f[R]) one.+So the amounts a report shows are not always the ones tested;+\f[CR]\-H\f[R] shows balances.+A date span (\f[CR]date:2026\f[R], \f[CR]\-p\f[R],+\f[CR]\-b\f[R]/\f[CR]\-e\f[R]) sets the report period and does not limit+the balance, as with \f[CR]\-H\f[R].+But query terms which exclude postings also exclude them from the+balance; this includes \f[CR]not:date:\f[R] and date terms combined with+OR.+.PP+What is tested depends on the kind of item being matched:+.IP \(bu 2+In balance reports (\f[CR]balance\f[R], \f[CR]balancesheet\f[R],+\f[CR]incomestatement\f[R], etc.), each account\(aqs own change over the+report period, or its own balance at the end of the report period, as+shown in list mode (without or with \f[CR]\-H\f[R]).+In a multi\-period report, the change is the row\(aqs Total column, and+the balance is the last column\(aqs (with \f[CR]\-H\f[R]).+Accounts which don\(aqt match are left out, as if excluded by an account+query.+So in tree mode, a parent account is shown if it has matching+subaccounts, with a balance including just those; and the report\(aqs+totals and percentages include just the matching accounts.+To test parent accounts\(aq subaccount\-inclusive amounts instead, limit+the depth, eg \f[CR]bal \-1 change:\(aq>100\(aq\f[R].+An account matched by \f[CR]balance:\f[R] is shown even if it had no+postings in the report period.+.IP \(bu 2+In budget reports (\f[CR]balance \-\-budget\f[R]), rows are hidden if+their actual change or balance (including subaccounts) doesn\(aqt match.+The other rows, and the totals, are unchanged, since budget goals are+often set on parent accounts.+.IP \(bu 2+In \f[CR]register\f[R], \f[CR]change:\f[R] tests each posting\(aqs+amount, or with a report interval, each period\(aqs amount;+\f[CR]balance:\f[R] tests the running total after it (the actual+balance, even without \f[CR]\-H\f[R]).+.IP \(bu 2+In \f[CR]aregister\f[R], \f[CR]change:\f[R] tests each transaction\(aqs+change to the account; \f[CR]balance:\f[R] tests the account\(aqs+balance after it.+.IP \(bu 2+In \f[CR]print\f[R] (and \f[CR]descriptions\f[R], \f[CR]notes\f[R] and+\f[CR]codes\f[R]), both test each entry\(aqs sum of postings (an entry+has no balance), converted to cost as in transaction balancing,+including any unbalanced virtual postings.+Since an entry\(aqs real postings must balance, this will be zero, or a+small tolerated imbalance, plus the amount of any unbalanced virtual+postings.+(To find large transactions, use \f[CR]amt:\f[R] instead, eg+\f[CR]print amt:\(aq>1000\(aq\f[R].)+.IP \(bu 2+In \f[CR]holdings\f[R], each line (one commodity in one account) has two+amounts, its units and its market value.+\f[CR]balance:\f[R] tests the units, or with a commodity symbol,+whichever of them is in that commodity (so+\f[CR]balance:\(aq>$1000\(aq\f[R] tests the value).+\f[CR]change:\f[R] likewise tests the change in units during the report+period, or its value.+Unlike in other reports, \f[CR]\-V\f[R]/\f[CR]\-X\f[R] don\(aqt change+which amount is tested; to test the value, write its commodity symbol.+With \f[CR]\-B\f[R], the cost is tested instead of the value (eg+\f[CR]holdings \-B balance:\(aq>$1000\(aq\f[R]).+The totals cover just the lines shown, but Weight is still relative to+all the holdings.+.IP \(bu 2+Other commands ignore these terms.+.PP+In registers, hidden rows still count in the running total or balance,+which is the account\(aqs real one.+(Unlike \f[CR]amt:\f[R], which excludes the postings themselves, so they+don\(aqt count.)+.PP+\f[CR]change:\f[R] and \f[CR]balance:\f[R] can be combined with other+query terms only by AND, and negated with \f[CR]not:\f[R].+They can\(aqt be used inside OR, a negated group, \f[CR]any:\f[R] or+\f[CR]all:\f[R].+As with other query terms which aren\(aqt OR\(aqd, multiple terms must+all match, so \f[CR]change:\(aq>100\(aq change:\(aq<500\(aq\f[R] selects+a range, and \f[CR]change:\(aq>100\(aq balance:\(aq<0\(aq\f[R] requires+both.+.SS code: query+\f[B]\f[CB]code:REGEX\f[B]\f[R]+.PD 0+.P+.PD+Match by transaction code (eg check number).+.SS cur: query+\f[B]\f[CB]cur:FULLREGEX\f[B]\f[R]+.PD 0+.P+.PD+Match postings or transactions including any amounts whose+currency/commodity symbol is fully matched by REGEX.+(Contrary to hledger\(aqs usual infix matching.+To do infix matching, write \f[CR].*REGEX.*\f[R].)+.PP+To match special characters which are regex\-significant, escape them+with \f[CR]\(rs\f[R].+And at the command line, characters which are shell\-significant need+one more level of escaping \- eg to match the dollar sign, write+\f[CR]cur:\(rs\(rs$\f[R] or \f[CR]cur:\(aq\(rs$\(aq\f[R].+.PP+Amounts written with a commodity alias have been converted to the+commodity, so \f[CR]cur:\f[R] matches them by the commodity\(aqs symbol,+not the alias.+.PD 0+.P+.PD+.SS desc: query+\f[B]\f[CB]desc:REGEX\f[B]\f[R]+.PD 0+.P+.PD+Match transaction descriptions.+.SS date: query+\f[B]\f[CB]date:PERIODEXPR\f[B]\f[R]+.PD 0+.P+.PD+Match dates (or with the \f[CR]\-\-date2\f[R] flag, secondary dates)+within the specified period.+PERIODEXPR is a period expression.+Examples:+.PD 0+.P+.PD+\f[CR]date:2016\f[R], \f[CR]date:thismonth\f[R],+\f[CR]date:2/1\-2/15\f[R], \f[CR]date:2021\-07\-27..nextquarter\f[R].+.PP+PERIODEXPR may include a report interval (since 1.52).+On the command line, this is equivalent to specifying a report interval+with a command line option.+In other contexts (hledger\-ui, hledger\-web), the report interval may+be ignored.+.SS date2: query+\f[B]\f[CB]date2:PERIODEXPR\f[B]\f[R]+.PD 0+.P+.PD+If you use secondary dates: this matches secondary dates within the+specified period.+It is not affected by the \f[CR]\-\-date2\f[R] flag.+A report interval in PERIODEXPR will be ignored.+.SS depth: query+\f[B]\f[CB]depth:[REGEXP=]N\f[B]\f[R]+.PD 0+.P+.PD+Match (or display, depending on command) accounts at or above this+depth, optionally only for accounts matching a provided regular+expression.+See Depth for detailed rules.+.SS find: query+\f[B]\f[CB]find:REGEX\f[B]\f[R], or \f[B]\f[CB]::REGEX\f[B]\f[R]+.PD 0+.P+.PD+Match if any text field contains this case insensitive regular+expression: the account name, the amount (as it would be displayed), the+comment, the transaction\(aqs description, code and comment, or the name+or value of any tag.+Tags include hidden tags and tags inherited from account and commodity+declarations, so a match may come from a tag not shown in+\f[CR]print\f[R] output.+Eg \f[CR]::dispose\f[R] finds lot disposals, which have a hidden+\f[CR]ptype: dispose\f[R] tag.+To see why something matched, \f[CR]print \-\-verbose\-tags\f[R] shows+the hidden tags; for inherited tags, check the account or commodity+directive.+Or, if REGEX is also a valid period expression, match if the date is+within that period.+So \f[CR]::amazon\f[R] finds \(dqamazon\(dq anywhere, and+\f[CR]::2024\f[R] finds \(dq2024\(dq in any field or a date in 2024.+Unlike \f[CR]date:\f[R], this does not set the report period.+.PP+Multiple \f[CR]find:\f[R] terms must all match, like the words of a+search.+Eg \f[CR]::amazon ::2024\f[R] shows things matching both.+(In a transaction\-oriented command like \f[CR]print\f[R], the terms may+be matched by different postings.)+To match alternatives, use a regular expression:+\f[CR]::\(aqamazon|amzn\(aq\f[R].+.SS note: query+\f[B]\f[CB]note:REGEX\f[B]\f[R]+.PD 0+.P+.PD+Match transaction notes (the part of the description right of+\f[CR]|\f[R], or the whole description if there\(aqs no \f[CR]|\f[R]).+.SS payee: query+\f[B]\f[CB]payee:REGEX\f[B]\f[R]+.PD 0+.P+.PD+Match transaction payee/payer names (the part of the description left of+\f[CR]|\f[R], or the whole description if there\(aqs no \f[CR]|\f[R]).+.SS real: query+\f[B]\f[CB]real:, real:0\f[B]\f[R]+.PD 0+.P+.PD+Match real or virtual postings respectively.+.SS status: query+\f[B]\f[CB]status:, status:!, status:*\f[B]\f[R]+.PD 0+.P+.PD+Match unmarked, pending, or cleared transactions respectively.+.SS type: query+\f[B]\f[CB]type:TYPECODES\f[B]\f[R]+.PD 0+.P+.PD+Match by account type (see Declaring accounts > Account types).+\f[CR]TYPECODES\f[R] is one or more of the single\-letter account type+codes \f[CR]ALERXCVGUM\f[R], case insensitive.+Note \f[CR]type:A\f[R], \f[CR]type:E\f[R], and \f[CR]type:R\f[R] will+also match their respective subtypes \f[CR]C\f[R] (Cash), \f[CR]V\f[R]+(Conversion), \f[CR]U\f[R] (UnrealisedGain) and \f[CR]M\f[R]+(Imbalance), and \f[CR]G\f[R] (Gain).+Certain kinds of account alias can disrupt account types, see Rewriting+accounts > Aliases and account types.+.SS tag: query+\f[B]\f[CB]tag:NAMEREGEX[=VALREGEX]\f[B]\f[R]+.PD 0+.P+.PD+Match by tag name, and optionally also by tag value.+Note:+.IP \(bu 2+Both regular expressions do infix matching.+If you need a complete match, use \f[CR]\(ha\f[R] and \f[CR]$\f[R].+.PD 0+.P+.PD+Eg: \f[CR]tag:\(aq\(hafullname$\(aq\f[R],+\f[CR]tag:\(aq\(hafullname$=\(hafullvalue$\f[R]+.IP \(bu 2+To match values, ignoring names, do \f[CR]tag:=VALREGEX\f[R]+.IP \(bu 2+With an empty NAMEREGEX, \f[CR]tag:\f[R] matches anything which has a+tag, and \f[CR]not:tag:\f[R] matches anything which has none.+.IP \(bu 2+With an empty VALREGEX, \f[CR]tag:NAMEREGEX=\f[R] matches that tag with+any value.+.IP \(bu 2+Accounts also inherit the tags of their parent accounts.+.IP \(bu 2+Postings also inherit the tags of their account and their transaction .+.IP \(bu 2+Transactions also acquire the tags of their postings.+.SS Negative queries+.SS not: query+\f[B]\f[CB]not:QUERY\f[B]\f[R]+.PD 0+.P+.PD+You can prepend \f[B]\f[CB]not:\f[B]\f[R] to a query to negate the+match.+.PD 0+.P+.PD+Eg: \f[CR]not:equity\f[R], \f[CR]not:desc:apple\f[R]+.PD 0+.P+.PD+(Also, a trick: \f[CR]not:not:...\f[R] can sometimes solve query+problems conveniently.)+.SS Space\-separated queries+When given multiple space\-separated query terms, most commands select+things which match:+.IP \(bu 2+any of the description terms AND+.IP \(bu 2+any of the account terms AND+.IP \(bu 2+any of the status terms AND+.IP \(bu 2+all the other terms.+.PP+The print command is a little different, showing transactions which:+.IP \(bu 2+match any of the description terms AND+.IP \(bu 2+have any postings matching any of the positive account terms AND+.IP \(bu 2+have no postings matching any of the negative account terms AND+.IP \(bu 2+match all the other terms.+.SS Boolean queries+For more complex needs, you can combine query terms with \f[CR]NOT\f[R],+\f[CR]AND\f[R], \f[CR]OR\f[R] operators (case insensitive) and+parentheses, writing the whole expression in quotes with one of three+prefixes: \f[CR]expr:\f[R], \f[CR]any:\f[R] or \f[CR]all:\f[R].+Eg, to show transactions involving both cash and expense accounts:+.IP+.EX+hledger print expr:\(aqcash AND expenses\(aq+.EE+.PP+The prefix and the quotes are required.+Two more things to know:+.IP \(bu 2+\f[CR]date:\f[R] queries may not be used inside an OR expression (it+could produce a report with disjoint or unclear report periods).+.IP \(bu 2+Space\-separated terms can also appear inside a boolean query, combining+as described in space\-separated queries; but it\(aqs probably clearer+to avoid mixing the two styles.+.SS expr: query+\f[B]\f[CB]expr:\(aqQUERYEXPR\(aq\f[B]\f[R]+.PD 0+.P+.PD+The general purpose boolean query.+It can match transactions, postings, accounts, etc.+depending on context.+Eg, \f[CR]expr:\(aqdate:lastmonth AND NOT (food OR rent)\(aq\f[R]+matches things dated in the last month, without food or rent in the+account name.+.PP+With transaction\-oriented commands like \f[CR]print\f[R],+posting\-oriented terms like \f[CR]acct:\f[R] and \f[CR]amt:\f[R] match+a transaction if they match any of its postings.+So, \f[CR]hledger print expr:\(aqcash AND amt:>0\(aq\f[R] shows+transactions which have at least one cash posting and at least one+positive\-amount posting (these are not necessarily the same posting).+.SS any: query+\f[B]\f[CB]any:\(aqQUERYEXPR\(aq\f[B]\f[R]+.PD 0+.P+.PD+Matches a transaction, if at least one of its postings is matched by+QUERYEXPR.+So, \f[CR]hledger print any:\(aqcash AND amt:>0\(aq\f[R] shows+transactions which have at least one posting that both involves a cash+account and has a positive amount.+.PP+Unlike \f[CR]expr:\f[R], \f[CR]any:\f[R] always considers whole+transactions.+So, \f[CR]hledger balance expenses any:cash\f[R] shows expenses from+transactions involving cash, and+\f[CR]hledger balance expenses not:any:cash\f[R] shows expenses from+transactions not involving cash.+.PP+A query containing only \f[CR]any:\f[R] (or \f[CR]all:\f[R]) terms+selects entire transactions, so its balance report will be+zero\-balanced, showing where the money in those transactions came from+and went to.+For the same reason, such a query combined with \f[CR]register\f[R]\(aqs+\f[CR]\-\-related\f[R] flag shows nothing: every posting is matched, so+there are no unmatched related postings left to show.+.SS all: query+\f[B]\f[CB]all:\(aqQUERYEXPR\(aq\f[B]\f[R]+.PD 0+.P+.PD+Matches a transaction, if it has at least one posting and all of its+postings are matched by QUERYEXPR.+So, \f[CR]hledger print all:\(aqcash OR checking\(aq\f[R] shows+transactions touching only cash and/or checking accounts.+.PP+Like \f[CR]any:\f[R], \f[CR]all:\f[R] always considers whole+transactions.+So, \f[CR]hledger register all:\(aqcash OR checking\(aq\f[R] shows the+postings of transactions touching only cash and/or checking accounts \-+eg, transfers between those two.+By contrast, \f[CR]hledger register expr:\(aqcash OR checking\(aq\f[R]+tests each posting on its own, so it could also show, say, the cash+posting of a grocery purchase.+.SS Queries and command options+Some queries can also be expressed as command\-line options:+\f[CR]depth:2\f[R] is equivalent to \f[CR]\-\-depth 2\f[R],+\f[CR]date:2023\f[R] is equivalent to \f[CR]\-p 2023\f[R], etc.+When you mix command options and query arguments, generally the+resulting query is their intersection.+.SS Queries and account aliases+When account names are rewritten by account aliases, queries see only+the new account names.+Eg with \f[CR]alias checking = assets:bank:checking\f[R],+\f[CR]acct:bank\f[R] matches the rewritten postings, but+\f[CR]acct:\(hachecking\f[R] does not.+.SS Queries and valuation+When amounts are converted to other commodities in cost or value+reports, \f[CR]cur:\f[R] and \f[CR]amt:\f[R] match the old commodity+symbol and the old amount quantity, not the new ones.+\f[CR]change:\f[R] and \f[CR]balance:\f[R] match the converted amounts,+except in \f[CR]print\f[R] (see balance: and change: queries).+(With \f[CR]\-B\f[R] and no \f[CR]\-\-lots\f[R], a sale from several+lots may be left out by \f[CR]cur:\f[R] or \f[CR]amt:\f[R], since it is+matched as converted to cost; add \f[CR]\-\-lots\f[R] to match it as+written.)+.SH Depth+With the \f[CR]\-\-depth NUM\f[R] option (short form, usually preferred:+\f[CR]\-NUM\f[R]), reports will show accounts only to the specified+depth, hiding deeper subaccounts.+Use this when you want a summary with less detail.+This flag has the same effect as a \f[CR]depth:\f[R] query argument.+So all of these are equivalent: \f[CR]depth:2\f[R],+\f[CR]\-\-depth=2\f[R], \f[CR]\-2\f[R].+.PP+You can also provide custom depths for specific accounts, by providing a+\f[CR]REGEX=NUM\f[R] argument instead of just \f[CR]NUM\f[R].+For example, \f[CR]\-\-depth assets=2\f[R] (or+\f[CR]depth:assets=2\f[R]) will collapse accounts matching the regular+expression \(dqassets\(dq to depth 2.+So \f[CR]assets:bank:savings\f[R] would be collapsed to+\f[CR]assets:bank\f[R], but \f[CR]liabilities:bank:credit card\f[R]+would not be affected.+.PP+If REGEX contains spaces or other special characters, enclose it in+quotes in the usual way.+Eg: \f[CR]\-\-depth \(aqcredit card=2\(aq\f[R]+.SS Combining depth options+If a command line contains multiple general depth options, the last one+wins.+(Useful for overriding a depth specified by scripts.)+.PP+Or a command may contain a combination of general and custom depth+options.+In this case, the most specifically (deepest) matching option wins.+Some examples:+.IP \(bu 2+\f[CR]\-\-depth assets=3 \-\-depth expenses=2 \-\-depth 1\f[R] would+collapse accounts containing \(dqassets\(dq to depth 3, accounts+containing \(dqexpenses\(dq to depth 2, and all other accounts to depth+1.+.IP \(bu 2+\f[CR]\-\-depth assets=1 \-\-depth savings=2\f[R] would collapse+\f[CR]assets:bank:savings\f[R] to depth 2 (not depth 1; because+\(dqsavings\(dq matches a deeper part of the account name than+\(dqassets\(dq).+.PP+Note currently, to override a custom depth option+\f[CR]\-\-depth REGEX=NUM\f[R] with a later option, the later option+must use the same REGEX.+.SH Pivoting+Normally, hledger groups amounts and displays their totals by account+(name).+With \f[CR]\-\-pivot PIVOTEXPR\f[R], some other field\(aqs (or multiple+fields\(aq) value is used as a synthetic account name, causing different+grouping and display.+PIVOTEXPR can be+.IP \(bu 2+any of these standard transaction or posting fields (their value is+substituted): \f[CR]status\f[R], \f[CR]code\f[R],+\f[CR]desc\f[R]/\f[CR]description\f[R], \f[CR]payee\f[R],+\f[CR]note\f[R], \f[CR]acct\f[R]/\f[CR]account\f[R],+\f[CR]comm\f[R]/\f[CR]cur\f[R], \f[CR]amt\f[R], \f[CR]cost\f[R]+.IP \(bu 2+or a tag name+.IP \(bu 2+or any combination of these, colon\-separated.+.PP+Some special cases:+.IP \(bu 2+Colons appearing in PIVOTEXPR or in a pivoted tag value will generate+account hierarchy.+.IP \(bu 2+When pivoting a posting that has multiple values for a tag, the tag\(aqs+first value will be used as the pivoted value.+.IP \(bu 2+When a posting has multiple commodities, the pivoted value of+\(dqcomm\(dq/\(dqcur\(dq will be \(dq\(dq.+Also when an unrecognised tag name or field is provided, its pivoted+value will be \(dq\(dq.+(If this causes confusing output, consider excluding those postings from+the report.)+.PP+Examples:+.IP+.EX+2016/02/16 Yearly Dues Payment+ assets:bank account 2 EUR+ income:dues \-2 EUR ; member: John Doe, kind: Lifetime+.EE+.PP+Normal balance report showing account names:+.IP+.EX+$ hledger balance+ 2 EUR assets:bank account+ \-2 EUR income:dues+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ 0+.EE+.PP+Pivoted balance report, using member: tag values instead:+.IP+.EX+$ hledger balance \-\-pivot member+ 2 EUR+ \-2 EUR John Doe+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ 0+.EE+.PP+One way to show only amounts with a member: value (using a query):+.IP+.EX+$ hledger balance \-\-pivot member tag:member=.+ \-2 EUR John Doe+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ \-2 EUR+.EE+.PP+Another way (the acct: query matches against the pivoted \(dqaccount+name\(dq):+.IP+.EX+$ hledger balance \-\-pivot member acct:.+ \-2 EUR John Doe+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ \-2 EUR+.EE+.PP+Hierarchical reports can be generated with multiple pivot values:+.IP+.EX+$ hledger balance Income:Dues \-\-pivot kind:member+ \-2 EUR Lifetime:John Doe+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ \-2 EUR+.EE+.SH Report titles+Some reports (\f[CR]aregister\f[R], \f[CR]balance\f[R] (multi\-period),+\f[CR]balancesheet\f[R], \f[CR]balancesheetequity\f[R],+\f[CR]cashflow\f[R], \f[CR]holdings\f[R], \f[CR]incomestatement\f[R])+are displayed with a title by default, and others are not.+For most reports you can set a title with+\f[CR]\-\-title=\(aqSome Text\(aq\f[R], or suppress the title with+\f[CR]\-\-title=\f[R].+Titles are shown in text and HTML output (and in some commands\(aq+CSV/TSV output).+In HTML output the title is an+\f[CR]<h3 class=\(dqreport\-title\(dq>\f[R] element, which you can style+with a \f[CR]hledger.css\f[R] file.+.PP+Compound reports, like those just mentioned, also have subreport+headings, like Assets and Liabilities in the balance sheet.+You can customise these with+\f[CR]\-\-subreport\-titles=HEADING1|HEADING2..\f[R], or suppress them+with \f[CR]\-\-subreport\-titles=\f[R].+.PP+In both \f[CR]\-\-title\f[R] and \f[CR]\-\-subreport\-titles\f[R], you+can use \f[CR]\(rsn\f[R] to generate a newline.+.PP+In multi\-period reports each period has a heading describing its date+range or end date.+When date ranges correspond to natural period boundaries, they are+described compactly by default.+Eg: \f[CR]2026\f[R], \f[CR]Q1\f[R], \f[CR]Jan\f[R], \f[CR]W02\f[R].+(Month names follow the \f[CR]\-\-lang\f[R] option.)+You can disable these compact descriptions by using+\f[CR]\-\-period\-titles=dates\f[R]; then periods will always be+described as \f[CR]STARTDATE..ENDDATE\f[R].+.SH Languages+hledger\(aqs output is in English by default.+Report titles, section headings, column headings, month names and+similar structural text can be shown in another language with the+\f[CR]\-\-lang\f[R] option (which can also be set in a config file),+when a translation catalog for that language is available.+(This is hledger\(aqs localization support; it covers the language of+hledger\(aqs own text, not number or date formats, which come from the+journal, as described below.)+.IP \(bu 2+\f[CR]\-\-lang=LANG\f[R] selects a language by its tag, like+\f[CR]de\f[R] or \f[CR]pt\-BR\f[R].+An unavailable language is an error.+.IP \(bu 2+\f[CR]\-\-lang=auto\f[R] selects the language from the environment (the+LANGUAGE, LC_ALL, LC_MESSAGES and LANG variables, see Environment),+falling back to English.+.IP \(bu 2+\f[CR]\-\-lang=en\f[R], or no \f[CR]\-\-lang\f[R] option, selects+English.+.PP+To always get German output, for example, put it in your config+file\(aqs general options:+.IP+.EX+# \(ti/.config/hledger/hledger.conf+\-\-lang de+.EE+.PP+Currently Brazilian Portuguese (\f[CR]pt\-BR\f[R]), French+(\f[CR]fr\f[R]), German (\f[CR]de\f[R]), Hawaiian (\f[CR]haw\f[R]),+Irish (\f[CR]ga\f[R]), Italian (\f[CR]it\f[R]), Japanese+(\f[CR]ja\f[R]), Russian (\f[CR]ru\f[R]), Simplified Chinese+(\f[CR]zh\f[R], also selected by \f[CR]zh_CN\f[R] or+\f[CR]zh\-Hans\f[R]), Spanish (\f[CR]es\f[R]) and Ukrainian+(\f[CR]uk\f[R]) catalogs are built in.+Catalogs are gettext PO files, which the usual translation tools can+edit.+hledger also looks for catalogs in the \f[CR]locale\f[R] subdirectory of+its config directory (\f[CR]\(ti/.config/hledger/locale/LANG.po\f[R] on+unix, \f[CR]%APPDATA%\(rshledger\(rslocale\(rsLANG.po\f[R] on windows),+and merges a catalog found there over the built\-in catalog for the same+language, if any.+So a translator can work on a new language with a released hledger, and+a user can adjust terminology to taste.+\f[CR]hledger \-\-write\-lang=LANG\f[R] puts a catalog there to start+from: a copy of the built\-in catalog for that language, or for a new+language, an untranslated one.+(It won\(aqt overwrite a catalog that is already there.)+Contributed catalogs are welcome, and no programming is needed: see+Translating hledger in the developer docs.+.PP+Only hledger\(aqs own structural text is translated.+Your data (account names, descriptions, amounts) is never changed; dates+keep their ISO format, and numbers keep the display styles declared for+each commodity.+Error messages, journal\-format output, and the column headings of CSV,+TSV and JSON output stay in English, since they are commonly read by+other programs.+Report titles, however, are translated wherever they appear, as they+would be with \f[CR]\-\-title\f[R]; and an explicit \f[CR]\-\-title\f[R]+or \f[CR]\-\-subreport\-titles\f[R] is always used as given,+untranslated.+.SH Amount arithmetic+.PP+hledger uses decimal (Decimal) numbers for accounting arithmetic:+amounts, balances, costs, prices, valuation and gains.+Floating point (Double) numbers are used for inherently approximate+statistics like \f[CR]stats\f[R] txns/s, \f[CR]prices \-\-summary\f[R]+coverage, \f[CR]roi\f[R] and \f[CR]holdings\f[R] rates of return, and+debug timings, where they are a better fit.+.PP+Unlike the usual floating point numbers, which are binary and+fixed\-size, and so frequently rounded, decimal numbers are base ten, so+amounts like 0.1 are stored exactly, and they can have up to 255 decimal+places (and any number of digits in the integer part).+Addition, subtraction and multiplication are exact (as long as the+result needs no more than 255 decimal places).+Division can produce a non\-terminating decimal (like 1/3 = 0.333...);+hledger rounds these to 255 decimal places.+The error is less than 10\(ha\-250, too small to affect transaction+balancing or reports at normal display precisions.+When hledger shows such a rounded amount in full, eg in \f[CR]print\f[R]+output, it shows 8 decimal places.+.SS Where hledger divides+Non\-terminating decimals can arise only where hledger divides.+(Journal amounts are written as finite decimals, and amount expressions+round their results, except in costs.)+Here\(aqs when that happens:+.PP+.TS+tab(@);+lw(26.2n) lw(12.2n) lw(31.5n).+T{+When+T}@T{+What is divided+T}@T{+Visible effect+T}+_+T{+Dividing in an amount expression (\f[CR]$100.00 / 3\f[R])+T}@T{+amount / number+T}@T{+None: the result is rounded to the entry\(aqs decimal places for that+commodity when the journal is read, so it is exactly what+\f[CR]print\f[R] shows.+A split that doesn\(aqt divide evenly makes the transaction unbalanced,+unless one amount is left blank.+T}+T{+Dividing in a cost expression (\f[CR]\(at 1 / 1.14 EUR\f[R])+T}@T{+amount / number, or number / amount+T}@T{+None in calculations: the cost is kept exact.+\f[CR]print\f[R] shows a repeating decimal with 8 decimal places (more+if written), so text copied from it is slightly rounded.+T}+T{+Converting a lot\(aqs total cost (\f[CR]\(at\(at\f[R]) or total cost+basis (\f[CR]{{ }}\f[R]) to a unit cost+T}@T{+total cost / quantity+T}@T{+None in calculations: gains use the unrounded unit cost.+Lot names and \f[CR]print\f[R] show it with up to 8 decimal places (more+if the cost commodity\(aqs display style has more), so text copied from+them is slightly rounded; see Cost basis precision.+T}+T{+Inferring market prices from costs, with+\f[CR]\-\-infer\-market\-prices\f[R]+T}@T{+total cost / quantity+T}@T{+None+T}+T{+Using a reverse market price+T}@T{+1 / price+T}@T{+None+T}+T{+Averaging lot costs, with the AVERAGE cost basis methods or in holdings+T}@T{+total cost / total quantity+T}@T{+None+T}+T{+Inferring costs from equity conversion postings+T}@T{+one amount / the other+T}@T{+None+T}+T{+Inferring a unit cost for several postings in one commodity, in an+implicit conversion+T}@T{+total / quantity+T}@T{+None in calculations.+\f[CR]print \-x\f[R] shows it with 8 decimal places (more if the+commodities\(aq decimal places add up to more), so text copied from it+is slightly rounded.+T}+T{+Converting amounts written with a commodity alias that has a quantity+T}@T{+amount / alias quantity+T}@T{+None in calculations: unit costs are replaced by exact total costs, and+balance assertions convert the alias amounts\(aq total (so three+\f[CR]10 min\f[R] amounts satisfy a \f[CR]= 0.5 h\f[R] assertion).+\f[CR]print \-x\f[R] shows converted amounts with all their decimal+places (8 for a repeating decimal).+T}+T{+Calculating averages (eg \f[CR]\-A\f[R]) and percentages (eg+\f[CR]\-%\f[R]) in reports+T}@T{+total / count, part / total+T}@T{+None: these are displayed rounded+T}+T{+Converting times to hours in timeclock entries, and timedot durations+written in minutes or seconds (\f[CR]10m\f[R])+T}@T{+time / hour length+T}@T{+Negligible: each is rounded at the 255th decimal place, so eg three+\f[CR]10m\f[R] timedot entries total 0.50 hours, as displayed.+But that total isn\(aqt exactly 0.5, so a balance assertion of+\f[CR]0.5\f[R] hours on it would fail.+Reports show durations with 2 decimal places; \f[CR]print\f[R] shows a+repeating decimal with 8 (\f[CR]0.16666667\f[R]).+T}+T{+Calculating rates of return: roi\(aqs IRR and TWR, and holdings\(aq XIRR+column+T}@T{+various+T}@T{+Rates are approximate (calculated with floating point numbers; IRR and+XIRR by iteration)+T}+.TE+.SH Transaction balancing+A transaction\(aqs postings must add up to zero.+When they are all in one commodity, this is simple: the sum must be+exactly zero.+But when a transaction converts between commodities using a cost, the+cost is often rounded (by you, or by your bank or broker), and requiring+an exact zero would reject many correct\-looking entries.+So, like Ledger and Beancount, hledger allows a small tolerance.+.SS How balancing is checked+For each commodity in a journal entry, hledger:+.IP "1." 3+adds up the posting amounts in that commodity, after converting any+amounts that have a cost to the cost\(aqs commodity (exactly; see Amount+arithmetic)+.IP "2." 3+finds the entry\(aqs \f[I]balancing precision\f[R] for that commodity:+the most decimal places used by that commodity\(aqs amounts in the+entry, not counting cost amounts+.IP "3." 3+considers the entry balanced if the sum rounds to zero at that+precision.+In other words, the imbalance can be at most half a unit in the last+decimal place: 0.005 for amounts with 2 decimal places, 0.5 for amounts+with no decimal places.+.PP+Eg:+.IP+.EX+2024\-01\-30 currency exchange+ assets:usd \-19110.17 USD \(at 0.869050 CHF+ assets:chf 16607.69 CHF+.EE+.PP+The first posting converts to \-16607.6932385 CHF, so the sum in CHF is+\-0.0032385 CHF.+The balancing precision for CHF is 2 (from 16607.69 CHF; the cost amount+0.869050 CHF doesn\(aqt count).+\-0.0032385 rounded to 2 decimal places is zero, so this entry is+accepted.+.PP+To make hledger check an entry more strictly, write its amounts with+more decimal places.+Eg if the second amount above is written as 16607.690 CHF, the balancing+precision becomes 3 and the entry is rejected.+.SS Where imbalances come from+.IP \(bu 2+Rounded unit costs (\f[CR]\(at\f[R]).+The exact rate may have infinitely many decimal places (above, the exact+rate is 16607.69 / 19110.17 = 0.86904983053...), or just more than your+bank or broker shows you.+This is the most common cause.+.IP \(bu 2+Total costs (\f[CR]\(at\(at\f[R]) that don\(aqt quite match the other+amounts.+Eg this entry is accepted, because the balancing precision for $ is 0+(because $100 was written with no decimals):+.RS 2+.IP+.EX+2026\-01\-01+ assets:stock \-3 AAPL \(at\(at $100.40+ assets:cash $100+.EE+.RE+.SS Accumulated imbalances+Accepted imbalances are not corrected; they stay in the data, and add+up.+So reports which convert amounts at cost, like \f[CR]balance \-B\f[R] or+\f[CR]balancesheetequity \-B\f[R], may show a small non\-zero total+where you would expect zero.+Eg after three of the currency exchange entries above,+\f[CR]hledger bal \-B\f[R] shows a total of \-0.01 CHF.+Typically this is a few cents, but each entry can contribute up to half+a unit in its last decimal place.+.PP+(Without cost conversion, these imbalances aren\(aqt directly visible.+And with \f[CR]\-\-infer\-equity\f[R], each commodity balances exactly,+and the imbalances become part of the conversion rates.)+.PP+To see an accumulated imbalance more precisely, increase the display+precision with \f[CR]\-c\f[R].+Eg:+.IP+.EX+$ hledger bal \-B \-c \(aqCHF 1.000000000\(aq+.EE+.PP+And to see which entries contribute to it, use a register report:+\f[CR]hledger reg \-B \-c \(aqCHF 1.000000000\(aq\f[R].+Or, show the imbalances explicitly, as described next.+.SS Showing imbalances+With the \f[CR]\-\-infer\-imbalance\f[R] flag, hledger shows entry+imbalances explicitly, by generating postings to an imbalance account+(\f[CR]equity:imbalance\f[R] by default) which make the entry balance+exactly (as if you had added an amountless posting to that account).+Eg:+.IP+.EX+$ hledger print \-\-infer\-imbalance+2024\-01\-30 currency exchange+ assets:usd \-19110.17 USD \(at 0.869050 CHF+ assets:chf 16607.69 CHF+ equity:imbalance 0.0032385 CHF+.EE+.PP+This doesn\(aqt change which entries are accepted.+But totals at cost are now exactly zero, and the accumulated imbalance+appears as the balance of \f[CR]equity:imbalance\f[R].+Eg after three of the currency exchange entries:+.IP+.EX+$ hledger bal \-B \-\-infer\-imbalance+ 49823.07 CHF assets:chf+ \-49823.08 CHF assets:usd+ 0.01 CHF equity:imbalance+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ 0+.EE+.PP+The imbalance postings\(aq amounts are usually smaller than the display+precision, so to see them individually, increase the display precision.+Eg:+.IP+.EX+$ hledger areg equity:imbalance \-\-infer\-imbalance \-c \(aqCHF 1.0000000\(aq+Transactions in equity:imbalance and subaccounts:+2024\-01\-30 currency exchange as:usd, as:chf CHF 0.0032385 CHF 0.0032385+2024\-01\-30 currency exchange as:usd, as:chf CHF 0.0032385 CHF 0.0064770+2024\-01\-30 currency exchange as:usd, as:chf CHF 0.0032385 CHF 0.0097155+.EE+.PP+Some notes:+.IP \(bu 2+The imbalance postings have a hidden \f[CR]_imbalance\-posting\f[R] tag+(shown by \f[CR]\-\-verbose\-tags\f[R]), so they can also be matched+with \f[CR]tag:imbalance\-posting\f[R].+.IP \(bu 2+To use a different account, declare it with the+\f[CR]M\f[R]/\f[CR]Imbalance\f[R] account type (the first one declared+is used, if there are several).+Imbalance accounts, including \f[CR]equity:imbalance\f[R], can be+matched with \f[CR]type:M\f[R].+.IP \(bu 2+With \f[CR]\-\-infer\-equity\f[R] as well, the generated equity+conversion postings use the exact cost amounts, so every commodity+balances exactly.+.IP \(bu 2+No imbalance posting is generated if its amount would display as zero+(at 8 decimal places, for a repeating decimal).+This ignores the tiny leftovers of hledger\(aqs own division (see Amount+arithmetic).+.IP \(bu 2+The imbalance account need not be declared, even in strict mode.+.IP \(bu 2+To list the entries with an imbalance, without generating postings, you+can use \f[CR]hledger print not:change:0\f[R] (see change: query).+(This also lists entries with unbalanced virtual postings;+\f[CR]not:change:0 change:\(aq<1\(aq\f[R] would list only the small+imbalances.)+.IP \(bu 2+If you use this flag with \f[CR]import\f[R], the imbalance postings will+be added to your journal too.+.SS Avoiding imbalances+You can avoid imbalances by writing exact entries.+Any of these will do:+.IP \(bu 2+Use a total cost (\f[CR]\(at\(at\f[R]) instead of a unit cost+(\f[CR]\(at\f[R]) when the unit cost would be rounded.+Total costs are converted exactly.+Eg \f[CR]\-19110.17 USD \(at\(at 16607.69 CHF\f[R].+.IP \(bu 2+Write the unit cost with enough decimal places to be exact, when+possible.+.IP \(bu 2+Add a posting to absorb the imbalance, eg to an+\f[CR]expenses:rounding\f[R] account.+If you leave its amount blank, hledger will calculate it exactly.+.SS Transaction balancing before 1.50+hledger versions before 1.50 used the commodity\(aqs display precision+as the balancing precision, instead of the precision in the entry.+This masked larger imbalances, and made balancing depend on display+settings (see issue #2402).+So some journal entries (or CSV rules) that worked with hledger <1.50+are now rejected with an \(dqunbalanced transaction\(dq error.+If you hit this, you can:+.IP \(bu 2+restore the old behaviour, by adding+\f[CR]\-\-txn\-tolerance=display\f[R] (formerly+\f[CR]\-\-txn\-balancing=old\f[R]) to the command or to your+\f[CR]\(ti/.hledger.conf\f[R] file.+This lets you keep using old journals unchanged.+.IP \(bu 2+or fix the problem entries (recommended), in one of these ways:+.RS 2+.IP "1." 3+make cost amounts more precise (add more or better decimal digits)+.IP "2." 3+or make non\-cost amounts less precise (remove unnecessary decimal+digits that are raising the precision)+.IP "3." 3+or add a posting to absorb the imbalance, as described above.+.RE+.SH Amount formatting+.SS Commodity display style+For the amounts in each commodity, hledger chooses a consistent display+style (symbol placement, decimal mark and digit group marks, number of+decimal digits) to use in most reports.+This is inferred as follows:+.PP+First, if there\(aqs a \f[CR]D\f[R] directive declaring a default+commodity, that commodity symbol and amount format is applied to all+no\-symbol amounts in the journal.+.PP+Then each commodity\(aqs display style is determined from its+\f[CR]commodity\f[R] directive.+We recommend always declaring commodities with \f[CR]commodity\f[R]+directives, since they help ensure consistent display styles and+precisions, and bring other benefits such as error checking for+commodity symbols.+Here\(aqs an example:+.IP+.EX+# Set display styles (and decimal marks, for parsing, if there is no decimal\-mark directive)+# for the $, EUR, INR and no\-symbol commodities:+commodity $1,000.00+commodity EUR 1.000,00+commodity INR 9,99,99,999.00+commodity 1 000 000.9455+.EE+.PP+But for convenience, if a \f[CR]commodity\f[R] directive is not present,+hledger infers a commodity\(aqs display styles from its amounts as they+are written in the journal (excluding cost amounts and amounts in+periodic transaction rules or auto posting rules).+It uses+.IP \(bu 2+the symbol placement and decimal mark of the first amount seen+.IP \(bu 2+the digit group marks of the first amount with digit group marks+.IP \(bu 2+and the maximum number of decimal digits seen across all amounts.+.PP+And as fallback if no applicable amounts are found, it would use a+default style, like \f[CR]$1000.00\f[R] (symbol on the left with no+space, period as decimal mark, and two decimal digits).+.PP+Finally, commodity styles can be overridden by the+\f[CR]\-c/\-\-commodity\-style\f[R] command line option, described next.+.PP+.SS Commodity style override+The \f[CR]\-c/\-\-commodity\-style\f[R] option overrides a+commodity\(aqs declared or inferred display style, for the current+command.+Its argument is a sample amount, as in the commodity directive.+Eg, to show dollar amounts with period digit group marks, comma decimal+mark, and one decimal digit:+.IP+.EX+$ hledger print \-c \(aq$1.000,0\(aq+.EE+.PP+Some things to note:+.IP \(bu 2+The option can be repeated, to set the display style of several+commodities.+.IP \(bu 2+Omitting the commodity symbol sets the style of just the no\-symbol+commodity, not of all commodities.+.IP \(bu 2+For cost amounts, and amounts displayed by the \f[CR]print\f[R] command,+it affects only the symbol placement and digit group/decimal marks;+those amounts are always displayed with all of their decimal digits.+.IP \(bu 2+In some cases hledger will adjust number formatting to improve+parseability, eg by adding trailing decimal marks when needed.+.PP+.SS Display rounding+Amounts are stored internally as decimal numbers with up to 255 decimal+places (see Amount arithmetic).+They are displayed with their original journal precisions by print and+print\-like reports, and rounded to their display precision (the number+of decimal digits specified by the commodity display style) by other+reports.+When rounding, hledger uses banker\(aqs rounding (it rounds to the+nearest even digit).+So eg 0.5 displayed with zero decimal digits appears as \(dq0\(dq.+.SS Trailing decimal marks+If you\(aqre wondering why your \f[CR]print\f[R] report sometimes shows+trailing decimal marks, with no decimal digits; it does this when+showing amounts that have digit group marks but no decimal digits, to+disambiguate them and allow them to be re\-parsed reliably (see Decimal+marks).+Eg:+.IP+.EX+commodity $1,000.00++2023\-01\-02+ (a) $1000+.EE+.IP+.EX+$ hledger print+2023\-01\-02+ (a) $1,000.+.EE+.PP+You can avoid this by disabling digit group marks, eg temporarily with+\-c/\-\-commodity:+.IP+.EX+$ hledger print \-c \(aq$1000.00\(aq+2023\-01\-02+ (a) $1000+.EE+.PP+or by forcing print to show some decimal digits, with \-\-round:+.IP+.EX+$ hledger print \-c \(aq$1,000.00\(aq \-\-round=soft+2023\-01\-02+ (a) $1,000.00+.EE+.SS Amount parseability+More generally, hledger output falls into three rough categories, which+format amounts a little bit differently to suit different consumers:+.PP+\f[B]1.+\(dqhledger\-readable output\(dq \- should be readable by hledger (and+by humans)\f[R]+.IP \(bu 2+This is produced by reports that show full journal entries:+\f[CR]print\f[R], \f[CR]import\f[R], \f[CR]close\f[R],+\f[CR]rewrite\f[R] etc.+.IP \(bu 2+It shows amounts with their original journal precisions, which may not+be consistent from one amount to the next.+.IP \(bu 2+It adds a trailing decimal mark when needed to avoid showing ambiguous+amounts.+.IP \(bu 2+It can be parsed reliably (by hledger and ledger2beancount at least, but+perhaps not by Ledger..)+.PP+\f[B]2.+\(dqhuman\-readable output\(dq \- usually for humans\f[R]+.IP \(bu 2+This is produced by all other reports.+.IP \(bu 2+It shows amounts with standard display precisions, which will be+consistent within each commodity.+.IP \(bu 2+It shows ambiguous amounts unmodified.+.IP \(bu 2+It can be parsed reliably in the context of a known report (when you+know decimals are consistently not being shown, you can assume a single+mark is a digit group mark).+.PP+\f[B]3.+\(dqmachine\-readable output\(dq \- usually for other software\f[R]+.IP \(bu 2+This is produced by all reports when an output format like+\f[CR]csv\f[R], \f[CR]tsv\f[R], \f[CR]json\f[R], or \f[CR]sql\f[R] is+selected.+.IP \(bu 2+It shows amounts as 1 or 2 do, but without digit group marks.+.IP \(bu 2+It can be parsed reliably (if needed, the decimal mark can be changed+with \-c/\-\-commodity\-style).+.SH Cost reporting+In some transactions \- for example a currency conversion, or a purchase+or sale of stock \- one commodity is exchanged for another.+In these transactions there is a conversion rate, also called the cost+(when buying) or selling price (when selling).+(In hledger docs we just say \(dqcost\(dq generically for convenience.)+With the \f[CR]\-B/\-\-cost\f[R] flag, hledger can show amounts \(dqat+cost\(dq, converted to the cost\(aqs commodity.+.SS Recording costs+We\(aqll explore several ways of recording transactions involving costs.+These are also compared at Currency conversion > Four ways to record a+conversion, compared.+.PP+Costs can be recorded explicitly in the journal, using the+\f[CR]\(at UNITCOST\f[R] or \f[CR]\(at\(at TOTALCOST\f[R] notation+described in Journal > Costs:+.PP+\f[B]Variant 1\f[R]+.IP+.EX+2022\-01\-01+ assets:dollars $\-135+ assets:euros €100 \(at $1.35 ; $1.35 per euro (unit cost)+.EE+.PP+\f[B]Variant 2\f[R]+.IP+.EX+2022\-01\-01+ assets:dollars $\-135+ assets:euros €100 \(at\(at $135 ; $135 total cost+.EE+.PP+Typically, writing the unit cost (variant 1) is preferable; it can be+more effort, requiring more attention to decimal digits; but it reveals+the per\-unit cost basis, and makes stock sales easier.+.PP+Costs can also be left implicit, and hledger will infer the cost that is+consistent with a balanced transaction:+.PP+\f[B]Variant 3\f[R]+.IP+.EX+2022\-01\-01+ assets:dollars $\-135+ assets:euros €100+.EE+.PP+Here, hledger will attach a \f[CR]\(at\(at €100\f[R] cost to the first+amount (you can see it with \f[CR]hledger print \-x\f[R]).+This form looks convenient, but there are downsides:+.IP \(bu 2+It sacrifices some error checking.+For example, if you accidentally wrote €10 instead of €100, hledger+would not be able to detect the mistake.+.IP \(bu 2+It is sensitive to the order of postings \- if they were reversed, a+different entry would be inferred and reports would be different.+.IP \(bu 2+The per\-unit cost basis is not easy to read.+.PP+So generally this kind of entry is not recommended.+You can make sure you have none of these by using \f[CR]\-s\f[R] (strict+mode), or by running \f[CR]hledger check balanced\f[R].+.SS Reporting at cost+Now when you add the \f[CR]\-B\f[R]/\f[CR]\-\-cost\f[R] flag to reports+(\(dqB\(dq is from Ledger\(aqs \-B/\-\-basis/\-\-cost flag), any amounts+which have been annotated with costs will be converted to their+cost\(aqs commodity (in the report output).+Ie they will be displayed \(dqat cost\(dq or \(dqat sale price\(dq.+.PP+For lot postings, which carry a cost basis, \f[CR]\-B\f[R] converts to+the cost basis instead: a disposal shows what the disposed units cost,+not what they sold for, consistent with how such entries balance, so eg+a lot account\(aqs cost balance is the cost of the units still held (and+zero once they are all sold), and \f[CR]bse \-B\f[R] balances.+To see transacted amounts (proceeds) instead, use+\f[CR]\-\-value=transacted\f[R].+.PP+Some things to note:+.IP \(bu 2+Costs are attached to specific posting amounts in specific transactions,+and once recorded they do not change.+This contrasts with market prices, which are ambient and fluctuating.+.IP \(bu 2+Conversion to cost is performed before conversion to market value+(described below).+.IP \(bu 2+A total at cost can be slightly off zero where you might expect zero (eg+a few cents in \f[CR]bse \-B\f[R]), because hledger accepts entries+whose costs were rounded; see Accumulated imbalances.+.SS Equity conversion postings+There is a problem with the entries above \- they are not conventional+Double Entry Bookkeeping (DEB) notation, and because of the+\(dqmagical\(dq transformation of one commodity into another, they cause+an imbalance in the Accounting Equation.+This shows up as a non\-zero grand total in balance reports like+\f[CR]hledger bse\f[R].+.PP+Most hledger users use cost notation and don\(aqt use equity postings;+for them this imbalance doesn\(aqt matter in practice and can safely be+ignored.+But if you\(aqd like to learn more, keep reading.+.PP+Conventional DEB uses an extra pair of equity postings to balance the+transaction.+Of course you can do this in hledger as well:+.PP+\f[B]Variant 4\f[R]+.IP+.EX+2022\-01\-01+ assets:dollars $\-135+ assets:euros €100+ equity:conversion $135+ equity:conversion €\-100+.EE+.PP+Now the transaction is perfectly balanced according to standard DEB, and+\f[CR]hledger bse\f[R]\(aqs total will not be disrupted.+It also translates easily to any other double entry accounting system.+.PP+And, hledger can still infer the cost for cost reporting, but it\(aqs+not done by default \- you must add the \f[CR]\-\-infer\-costs\f[R] flag+like so:+.IP+.EX+$ hledger print \-\-infer\-costs+2022\-01\-01 one hundred euros purchased at $1.35 each+ assets:dollars $\-135 \(at\(at €100+ assets:euros €100+ equity:conversion $135+ equity:conversion €\-100+.EE+.IP+.EX+$ hledger bal \-\-infer\-costs \-B+ €\-100 assets:dollars + €100 assets:euros +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- + 0 +.EE+.PP+Here are some downsides of this kind of entry:+.IP \(bu 2+The per\-unit cost basis is not easy to read.+.IP \(bu 2+Instead of \f[CR]\-B\f[R] you must remember to type+\f[CR]\-B \-\-infer\-costs\f[R].+.IP \(bu 2+\f[CR]\-\-infer\-costs\f[R] works only where hledger can identify the+two equity:conversion postings and match them up with the two+non\-equity postings.+So writing the journal entry in a particular format becomes more+important.+More on this below.+.SS Inferring equity conversion postings+Can we go in the other direction ?+Yes, if you have transactions written with the \(at/\(at\(at cost+notation, hledger can infer the missing equity postings, if you add the+\f[CR]\-\-infer\-equity\f[R] flag.+Eg:+.IP+.EX+2022\-01\-01+ assets:dollars \-$135+ assets:euros €100 \(at $1.35+.EE+.IP+.EX+$ hledger print \-\-infer\-equity+2022\-01\-01+ assets:dollars $\-135+ assets:euros €100 \(at $1.35+ equity:conversion:$\-€:€ €\-100+ equity:conversion:$\-€:$ $135.00+.EE+.PP+The equity account names will be \(dqequity:conversion:A\-B:A\(dq and+\(dqequity:conversion:A\-B:B\(dq where A is the alphabetically first+commodity symbol.+You can customise the \(dqequity:conversion\(dq part by declaring an+account with the \f[CR]V\f[R]/\f[CR]Conversion\f[R] account type (the+first\-declared one, if there are several; or if none is declared, the+alphabetically first account whose type is inferred as V, such as+\f[CR]equity:trading\f[R], is used).+.PP+For a lot disposal, the conversion postings record the units sold at+their cost basis, not at the sale price, so that the entry (and your+balance sheet) still sums to zero; the difference between the two is the+gain posting.+Eg:+.IP+.EX+commodity AAPL ; lots:++2026\-01\-02 buy+ assets:stock 10 AAPL \(at\(at $1000+ assets:cash++2026\-01\-03 sell+ assets:stock \-4 AAPL \(at\(at $600+ assets:cash $600+.EE+.IP+.EX+$ hledger print \-\-infer\-equity desc:sell+2026\-01\-03 sell+ assets:stock \-4 AAPL {2026\-01\-02, $100} \(at\(at $600+ equity:conversion:$\-AAPL:AAPL 4 AAPL+ equity:conversion:$\-AAPL:$ $\-400+ assets:cash $600+ revenues:gain $\-200+.EE+.PP+If you write such an entry yourself, write the conversion postings at+cost basis like this, and keep the transacted cost+(\f[CR]\(at\f[R]/\f[CR]\(at\(at\f[R]) on the disposal posting, since the+gain is calculated from it.+.PP+The generated equity conversion accounts need not be declared, even in+strict mode.+(And unlike normal postings, generated equity postings do not inherit+tags from account declarations.)+.SS Combining costs and equity conversion postings+Finally, you can use both the \(at/\(at\(at cost notation and equity+postings at the same time.+This in theory gives the best of all worlds \- preserving the accounting+equation, revealing the per\-unit cost basis, and providing more+flexibility in how you write the entry:+.PP+\f[B]Variant 5\f[R]+.IP+.EX+2022\-01\-01 one hundred euros purchased at $1.35 each+ assets:dollars $\-135+ equity:conversion $135+ equity:conversion €\-100+ assets:euros €100 \(at $1.35+.EE+.PP+All the other variants above can (usually) be rewritten to this final+form with:+.IP+.EX+$ hledger print \-x \-\-infer\-costs \-\-infer\-equity+.EE+.PP+Or you can enable both flags always, eg in your config file, and your+reports will have the advantages of both.+.PP+Downsides:+.IP \(bu 2+The precise format of the journal entry becomes more important.+If hledger can\(aqt detect and match up the cost and equity postings, it+will give a transaction balancing error.+.IP \(bu 2+The add command does not yet accept this kind of entry (#2056).+.IP \(bu 2+This is the most verbose form.+.SS Requirements for detecting equity conversion postings+\f[CR]\-\-infer\-costs\f[R] has certain requirements (unlike+\f[CR]\-\-infer\-equity\f[R], which always works).+It will infer costs only in transactions with:+.IP \(bu 2+Two non\-equity postings, in different commodities.+If one of them is lotful, the cost will be added to that one; otherwise+it will be added to the first (top) one.+.IP \(bu 2+Two postings to equity conversion accounts, next to one another, which+balance the two non\-equity postings.+This balancing is checked to the same precision (number of decimal+places) used in the conversion posting\(aqs amount.+Equity conversion accounts are:+.RS 2+.IP \(bu 2+any accounts declared with account type+\f[CR]V\f[R]/\f[CR]Conversion\f[R], or their subaccounts+.IP \(bu 2+otherwise, accounts named \f[CR]equity:conversion\f[R],+\f[CR]equity:trade\f[R], or \f[CR]equity:trading\f[R], or their+subaccounts.+.RE+.PP+And multiple such four\-posting groups can coexist within a single+transaction.+When \f[CR]\-\-infer\-costs\f[R] fails, it does not infer a cost in that+transaction, and does not raise an error (ie, it infers costs where it+can).+.PP+Reading variant 5 journal entries, combining cost notation and equity+postings, has all the same requirements.+When reading such an entry fails, hledger raises an \(dqunbalanced+transaction\(dq error.+For a lot disposal, the conversion postings may balance the+disposal\(aqs cost basis instead of its transacted cost, as described+above.+.PP+.SH Value reporting+hledger can also show amounts \(dqat market value\(dq, converted to some+other commodity using the market price or conversion rate on a certain+date.+.PP+This is controlled by the \f[CR]\-\-value=TYPE[,COMMODITY]\f[R] option.+We also provide simpler \f[CR]\-V\f[R] and \f[CR]\-X COMMODITY\f[R]+aliases for this, which are often sufficient.+The market prices are declared with a special \f[CR]P\f[R] directive,+and/or they can be inferred from the costs recorded in transactions, by+using the \f[CR]\-\-infer\-market\-prices\f[R] flag.+.SS \-X: Value in specified commodity+The \f[CR]\-X COMM\f[R] (or \f[CR]\-\-exchange=COMM\f[R]) option+converts amounts to their market value in the specified commodity, using+the market prices in effect on the \f[I]valuation date(s)\f[R], if any.+(More on these in a minute.)+.PP+Use this when you want to (eg) show everything in your base currency as+far as possible.+(Commodities for which no conversion rate can be found, will not be+converted.)+.PP+COMM should be the commodity symbol exactly as written in the+journal\(aqs amounts or market prices (eg \f[CR]$\f[R], not+\f[CR]USD\f[R], if the journal uses \f[CR]$\f[R]); ISO currency codes+are not matched to symbols.+If no conversion price to COMM can be found, a warning is printed,+suggesting an equivalent journal commodity if one exists.+Remember to quote special shell characters, if needed.+Some examples:+.IP \(bu 2+\f[CR]\-X€\f[R]+.IP \(bu 2+\f[CR]\-X$\f[R] (nothing after $, no quoting needed)+.IP \(bu 2+\f[CR]\-X CNY\f[R] (the space after \-X is optional)+.IP \(bu 2+\f[CR]\-X \(aqred apples\(aq\f[R]+.IP \(bu 2+\f[CR]\-X \(aqr&r\(aq\f[R]+.SS \-V: Value in default commodity(s)+The \f[CR]\-V/\-\-market\f[R] flag is a variant of \f[CR]\-X\f[R] where+you don\(aqt have to specify COMM.+Instead it tries to guess a \f[I]default valuation commodity\f[R] for+each original commodity, based on the market prices in effect on the+valuation date(s).+.PP+\f[CR]\-V\f[R] can often be a convenient shortcut for+\f[CR]\-X MYCURRENCY\f[R], but not always; depending on your data it+could guess multiple valuation commodities.+Usually you want to convert to a single commodity, so it\(aqs better to+use \f[CR]\-X\f[R], unless you\(aqre sure \f[CR]\-V\f[R] is doing what+you want.+.SS Valuation date+Market prices can change from day to day.+hledger will use the prices on a particular valuation date (or on more+than one date).+By default hledger uses \(dqend\(dq dates for valuation.+More specifically:+.IP \(bu 2+For single period reports (including normal print and register reports):+.RS 2+.IP \(bu 2+If an explicit report end date is specified, that is used.+.IP \(bu 2+Otherwise the latest transaction date or non\-future P directive date is+used.+.RE+.IP \(bu 2+For multiperiod reports, each period is valued on its last day.+.PP+This can be customised with the \-\-value option described below, which+can select either \(dqthen\(dq, \(dqend\(dq, \(dqnow\(dq, or+\(dqcustom\(dq dates.+.SS Finding market price+To convert a commodity A to its market value in another commodity B,+hledger looks for a suitable market price (exchange rate) as follows, in+this order of preference:+.IP "1." 3+A \f[I]declared market price\f[R] or \f[I]inferred market price\f[R]:+A\(aqs latest market price in B on or before the valuation date as+declared by a P directive, or (with the+\f[CR]\-\-infer\-market\-prices\f[R] flag) inferred from costs.+.IP "2." 3+A \f[I]reverse market price\f[R]: the inverse of a declared or inferred+market price from B to A.+.IP "3." 3+A \f[I]forward chain of market prices\f[R]: a synthetic price formed by+combining the shortest chain of \(dqforward\(dq (only 1 above) market+prices, leading from A to B.+.IP "4." 3+\f[I]Any chain of market prices\f[R]: a chain of any market prices,+including both forward and reverse prices (1 and 2 above), leading from+A to B.+.IP "5." 3+\f[I]Commodity alias rates\f[R]: if none of the above is found, the same+search is repeated, also using commodity aliases as fixed exchange rates+(between a commodity and its alias, when there are no market prices+between them).+This lets you value amounts in an alias declared by another file, or+show amounts in an alias with \f[CR]\-X\f[R], but aliases never change a+conversion that market prices can provide.+To see these rates and where their aliases were declared, use+\f[CR]prices \-\-show\-aliases \-\-locations\f[R];+\f[CR]\-\-debug=2\f[R] output shows when they are tried.+.PP+There is a limit to the length of these price chains; if hledger reaches+that length without finding a complete chain or exhausting all+possibilities, it will give up (with a \(dqgave up\(dq message visible+in \f[CR]\-\-debug=2\f[R] output).+That limit is currently 1000.+.PP+Amounts for which no suitable market price can be found, are not+converted.+.PP+Commodity alias rates are used only for converting, never as a default+valuation commodity for \f[CR]\-V\f[R].+.SS \-\-infer\-market\-prices: market prices from transactions+Normally, market value in hledger is fully controlled by, and requires,+P directives in your journal.+Since adding and updating those can be a chore, and since transactions+usually take place at close to market value, why not use the recorded+costs as additional market prices (as Ledger does) ?+Adding the \f[CR]\-\-infer\-market\-prices\f[R] flag to \f[CR]\-V\f[R],+\f[CR]\-X\f[R] or \f[CR]\-\-value\f[R] enables this.+.PP+So for example, \f[CR]hledger bs \-V \-\-infer\-market\-prices\f[R] will+get market prices both from P directives and from transactions.+If both occur on the same day, the P directive takes precedence.+.PP+There is a downside: value reports can sometimes be affected in+confusing/undesired ways by your journal entries.+If this happens to you, read all of this Value reporting section+carefully, and try adding \f[CR]\-\-debug\f[R] or \f[CR]\-\-debug=2\f[R]+to troubleshoot.+.PP+\f[CR]\-\-infer\-market\-prices\f[R] can infer market prices from:+.IP \(bu 2+multicommodity transactions with explicit prices+(\f[CR]\(at\f[R]/\f[CR]\(at\(at\f[R])+.IP \(bu 2+multicommodity transactions with implicit prices (no \f[CR]\(at\f[R],+two commodities, unbalanced).+(With these, the order of postings matters.+\f[CR]hledger print \-x\f[R] can be useful for troubleshooting.)+.IP \(bu 2+multicommodity transactions with equity postings, if cost is inferred+with \f[CR]\-\-infer\-costs\f[R].+.PP+There is a limitation (bug) currently: when a valuation commodity is not+specified, prices inferred with \f[CR]\-\-infer\-market\-prices\f[R] do+not help select a default valuation commodity, as \f[CR]P\f[R] prices+would.+So conversion might not happen because no valuation commodity was+detected (\f[CR]\-\-debug=2\f[R] will show this).+To be safe, specify the valuation commmodity, eg:+.IP \(bu 2+\f[CR]\-X EUR \-\-infer\-market\-prices\f[R], not+\f[CR]\-V \-\-infer\-market\-prices\f[R]+.IP \(bu 2+\f[CR]\-\-value=then,EUR \-\-infer\-market\-prices\f[R], not+\f[CR]\-\-value=then \-\-infer\-market\-prices\f[R]+.PP+Signed costs and market prices can be confusing.+For reference, here is the current behaviour.+(If you think it should work differently, see #1870.)+.IP+.EX+2022\-01\-01 Positive Unit prices+ a A 1+ b B \-1 \(at A 1++2022\-01\-01 Positive Total prices+ a A 1+ b B \-1 \(at\(at A 1+++2022\-01\-02 Negative unit prices+ a A 1+ b B 1 \(at A \-1++2022\-01\-02 Negative total prices+ a A 1+ b B 1 \(at\(at A \-1+++2022\-01\-03 Double Negative unit prices+ a A \-1+ b B \-1 \(at A \-1++2022\-01\-03 Double Negative total prices+ a A \-1+ b B \-1 \(at\(at A \-1+.EE+.PP+All of the transactions above are considered balanced (and on each day,+the two transactions are considered equivalent).+Here are the market prices inferred for B:+.IP+.EX+$ hledger \-f\- \-\-infer\-market\-prices prices+P 2022\-01\-01 B A 1+P 2022\-01\-01 B A 1.0+P 2022\-01\-02 B A \-1+P 2022\-01\-02 B A \-1.0+P 2022\-01\-03 B A \-1+P 2022\-01\-03 B A \-1.0+.EE+.SS Valuation commodity+\f[B]When you specify a valuation commodity (\f[CB]\-X COMM\f[B] or+\f[CB]\-\-value TYPE,COMM\f[B]):\f[R]+.PD 0+.P+.PD+hledger will convert all amounts to COMM, wherever it can find a+suitable market price (including by reversing or chaining prices).+.PP+\f[B]When you leave the valuation commodity unspecified (\f[CB]\-V\f[B]+or \f[CB]\-\-value TYPE\f[B]):\f[R]+.PD 0+.P+.PD+For each commodity A, hledger picks a default valuation commodity as+follows, in this order of preference:+.IP "1." 3+The price commodity from the latest P\-declared market price for A on or+before valuation date.+.IP "2." 3+The price commodity from the latest P\-declared market price for A on+any date.+(Allows conversion to proceed when there are inferred prices before the+valuation date.)+.IP "3." 3+If there are no P directives at all (any commodity or date) and the+\f[CR]\-\-infer\-market\-prices\f[R] flag is used: the price commodity+from the latest transaction\-inferred price for A on or before valuation+date.+.PP+This means:+.IP \(bu 2+If you have P directives, they determine which commodities+\f[CR]\-V\f[R] will convert, and to what.+.IP \(bu 2+If you have no P directives, and use the+\f[CR]\-\-infer\-market\-prices\f[R] flag, costs determine it.+.PP+Amounts for which no valuation commodity can be found are not converted.+.SS \-\-value: Flexible valuation+\f[CR]\-V\f[R] and \f[CR]\-X\f[R] are special cases of the more general+\f[CR]\-\-value\f[R] option:+.IP+.EX+ \-\-value=TYPE[,COMM] TYPE is then, end, now, YYYY\-MM\-DD, cost or transacted.+ COMM is an optional commodity symbol.+ Shows amounts converted to:+ \- default valuation commodity (or COMM) using market prices at posting dates+ \- default valuation commodity (or COMM) using market prices at period end(s)+ \- default valuation commodity (or COMM) using current market prices+ \- default valuation commodity (or COMM) using market prices at some date+ \- cost basis, or else transacted cost (like \-B)+ \- transacted cost only+.EE+.PP+The TYPE part selects cost or value and valuation date:+.TP+\f[CR]\-\-value=then\f[R]+Convert amounts to their value in the default valuation commodity, using+market prices on each posting\(aqs date.+.TP+\f[CR]\-\-value=end\f[R]+Convert amounts to their value in the default valuation commodity, using+market prices on the last day of the report period (or if unspecified,+the journal\(aqs end date); or in multiperiod reports, market prices on+the last day of each subperiod.+.TP+\f[CR]\-\-value=now\f[R]+Convert amounts to their value in the default valuation commodity using+current market prices (as of when report is generated).+.TP+\f[CR]\-\-value=YYYY\-MM\-DD\f[R]+Convert amounts to their value in the default valuation commodity using+market prices on this date.+.TP+\f[CR]\-\-value=cost\f[R]+Convert amounts to their cost basis where they have one (lot postings),+otherwise to their transacted cost.+Same as \f[CR]\-B\f[R]/\f[CR]\-\-cost\f[R]; see Reporting at cost.+.TP+\f[CR]\-\-value=transacted\f[R]+Convert amounts to their transacted cost or sale amount+(\f[CR]\(at\f[R]/\f[CR]\(at\(at\f[R]), ignoring any cost basis.+This is \f[CR]\-B\f[R]\(aqs behaviour for non\-lot postings, and shows+proceeds rather than cost for lot disposals.+.PP+To select a different valuation commodity, add the optional+\f[CR],COMM\f[R] part: a comma, then the target commodity\(aqs symbol.+Eg: \f[B]\f[CB]\-\-value=now,EUR\f[B]\f[R].+hledger will do its best to convert amounts to this commodity, deducing+market prices as described above.+.PP+The symbol may be written in double quotes, as in a journal.+To select the no\-symbol commodity, write it as \f[CR]\(dq\(dq\f[R], or+leave the symbol empty:+\f[B]\f[CB]\-\-value=now,\(aq\(dq\(dq\(aq\f[B]\f[R],+\f[B]\f[CB]\-\-value=now,\f[B]\f[R],+\f[B]\f[CB]\-X \(aq\(dq\(dq\(aq\f[B]\f[R] and+\f[B]\f[CB]\-X \(aq\(aq\f[B]\f[R] all work.+.SS Valuation examples+Here are some quick examples of \f[CR]\-V\f[R]:+.IP+.EX+; one euro is worth this many dollars from nov 1+P 2016/11/01 € $1.10++; purchase some euros on nov 3+2016/11/3+ assets:euros €100+ assets:checking++; the euro is worth fewer dollars by dec 21+P 2016/12/21 € $1.03+.EE+.PP+How many euros do I have ?+.IP+.EX+$ hledger \-f t.j bal \-N euros+ €100 assets:euros+.EE+.PP+What are they worth at end of nov 3 ?+.IP+.EX+$ hledger \-f t.j bal \-N euros \-V \-e 2016/11/4+ $110.00 assets:euros+.EE+.PP+What are they worth after 2016/12/21 ?+(no report end date specified, defaults to today)+.IP+.EX+$ hledger \-f t.j bal \-N euros \-V+ $103.00 assets:euros+.EE+.PP+Here are some examples showing the effect of \f[CR]\-\-value\f[R], as+seen with \f[CR]print\f[R]:+.IP+.EX+P 2000\-01\-01 A 1 B+P 2000\-02\-01 A 2 B+P 2000\-03\-01 A 3 B+P 2000\-04\-01 A 4 B++2000\-01\-01+ (a) 1 A \(at 5 B++2000\-02\-01+ (a) 1 A \(at 6 B++2000\-03\-01+ (a) 1 A \(at 7 B+.EE+.PP+Show the cost of each posting:+.IP+.EX+$ hledger \-f\- print \-\-cost+2000\-01\-01+ (a) 5 B++2000\-02\-01+ (a) 6 B++2000\-03\-01+ (a) 7 B+.EE+.PP+Show the value as of the last day of the report period (2000\-02\-29):+.IP+.EX+$ hledger \-f\- print \-\-value=end date:2000/01\-2000/03+2000\-01\-01+ (a) 2 B++2000\-02\-01+ (a) 2 B+.EE+.PP+With no report period specified, the latest transaction date or price+date is used as valuation date (2000\-04\-01):+.IP+.EX+$ hledger \-f\- print \-\-value=end+2000\-01\-01+ (a) 3 B++2000\-02\-01+ (a) 3 B++2000\-03\-01+ (a) 3 B+.EE+.PP+The value today is the same (the 2000\-04\-01 price is still in effect):+.IP+.EX+$ hledger \-f\- print \-\-value=now+2000\-01\-01+ (a) 4 B++2000\-02\-01+ (a) 4 B++2000\-03\-01+ (a) 4 B+.EE+.PP+Show the value on 2000/01/15:+.IP+.EX+$ hledger \-f\- print \-\-value=2000\-01\-15+2000\-01\-01+ (a) 1 B++2000\-02\-01+ (a) 1 B++2000\-03\-01+ (a) 1 B+.EE+.SS Interaction of valuation and queries+When matching postings based on queries in the presence of valuation,+the following happens:+.IP "1." 3+The query is separated into two parts:+.RS 4+.IP "1." 3+the currency (\f[CR]cur:\f[R]) or amount (\f[CR]amt:\f[R]).+.IP "2." 3+all other parts.+.RE+.IP "2." 3+The postings are matched to the currency and amount queries based on+pre\-valued amounts.+.IP "3." 3+Valuation is applied to the postings.+.IP "4." 3+The postings are matched to the other parts of the query based on+post\-valued amounts.+.PP+Related: #1625+.SS Effect of valuation on reports+Here is a reference for how valuation is supposed to affect each part of+hledger\(aqs reports.+It may be useful when troubleshooting.+Related: #329, #1083.+.PP+First, a quick glossary:+.TP+\f[I]cost\f[R]+calculated using price(s) recorded in the transaction(s).+.TP+\f[I]value\f[R]+market value using available market price declarations, or the unchanged+amount if no conversion rate can be found.+.TP+\f[I]report start\f[R]+the first day of the report period specified with \-b or \-p or date:,+otherwise today.+.TP+\f[I]report or journal start\f[R]+the first day of the report period specified with \-b or \-p or date:,+otherwise the earliest transaction date in the journal, otherwise today.+.TP+\f[I]report end\f[R]+the last day of the report period specified with \-e or \-p or date:,+otherwise today.+.TP+\f[I]report or journal end\f[R]+the last day of the report period specified with \-e or \-p or date:,+otherwise the latest transaction date in the journal, otherwise today.+.TP+\f[I]report interval\f[R]+a flag (\-D/\-W/\-M/\-Q/\-Y) or period expression that activates the+report\(aqs multi\-period mode (whether showing one or many subperiods).+.PP+.TS+tab(@);+lw(9.5n) lw(11.8n) lw(12.0n) lw(17.2n) lw(12.0n) lw(7.4n).+T{+Report type+T}@T{+\f[CR]\-B\f[R], \f[CR]\-\-cost\f[R]+T}@T{+\f[CR]\-V\f[R], \f[CR]\-X\f[R]+T}@T{+\f[CR]\-\-value=then\f[R]+T}@T{+\f[CR]\-\-value=end\f[R]+T}@T{+\f[CR]\-\-value=DATE\f[R], \f[CR]\-\-value=now\f[R]+T}+_+T{+\f[B]print\f[R]+T}@T{+T}@T{+T}@T{+T}@T{+T}@T{+T}+T{+posting amounts+T}@T{+cost+T}@T{+value at report end or today+T}@T{+value at posting date+T}@T{+value at report or journal end+T}@T{+value at DATE/today+T}+T{+balance assertions/assignments+T}@T{+unchanged+T}@T{+unchanged+T}@T{+unchanged+T}@T{+unchanged+T}@T{+unchanged+T}+T{+T}@T{+T}@T{+T}@T{+T}@T{+T}@T{+T}+T{+\f[B]register\f[R]+T}@T{+T}@T{+T}@T{+T}@T{+T}@T{+T}+T{+starting balance (\-H)+T}@T{+cost+T}@T{+value at report or journal end+T}@T{+valued at day each historical posting was made+T}@T{+value at report or journal end+T}@T{+value at DATE/today+T}+T{+starting balance (\-H) with report interval+T}@T{+cost+T}@T{+value at day before report or journal start+T}@T{+valued at day each historical posting was made+T}@T{+value at day before report or journal start+T}@T{+value at DATE/today+T}+T{+posting amounts+T}@T{+cost+T}@T{+value at report or journal end+T}@T{+value at posting date+T}@T{+value at report or journal end+T}@T{+value at DATE/today+T}+T{+summary posting amounts with report interval+T}@T{+summarised cost+T}@T{+value at period ends+T}@T{+sum of postings in interval, valued at interval start+T}@T{+value at period ends+T}@T{+value at DATE/today+T}+T{+running total/average+T}@T{+sum/average of displayed values+T}@T{+sum/average of displayed values+T}@T{+sum/average of displayed values+T}@T{+sum/average of displayed values+T}@T{+sum/average of displayed values+T}+T{+T}@T{+T}@T{+T}@T{+T}@T{+T}@T{+T}+T{+\f[B]balance (bs, bse, cf, is)\f[R]+T}@T{+T}@T{+T}@T{+T}@T{+T}@T{+T}+T{+balance changes+T}@T{+sums of costs+T}@T{+value at report end or today of sums of postings+T}@T{+value at posting date+T}@T{+value at report or journal end of sums of postings+T}@T{+value at DATE/today of sums of postings+T}+T{+budget amounts (\-\-budget)+T}@T{+like balance changes+T}@T{+like balance changes+T}@T{+like balance changes+T}@T{+like balances+T}@T{+like balance changes+T}+T{+grand total+T}@T{+sum of displayed values+T}@T{+sum of displayed values+T}@T{+sum of displayed valued+T}@T{+sum of displayed values+T}@T{+sum of displayed values+T}+T{+T}@T{+T}@T{+T}@T{+T}@T{+T}@T{+T}+T{+\f[B]balance (bs, bse, cf, is) with report interval\f[R]+T}@T{+T}@T{+T}@T{+T}@T{+T}@T{+T}+T{+starting balances (\-H)+T}@T{+sums of costs of postings before report start+T}@T{+value at report start of sums of all postings before report start+T}@T{+sums of values of postings before report start at respective posting+dates+T}@T{+value at report start of sums of all postings before report start+T}@T{+sums of postings before report start+T}+T{+balance changes (bal, is, bs \-\-change, cf \-\-change)+T}@T{+sums of costs of postings in period+T}@T{+same as \-\-value=end+T}@T{+sums of values of postings in period at respective posting dates+T}@T{+balance change in each period, valued at period ends+T}@T{+value at DATE/today of sums of postings+T}+T{+end balances (bal \-H, is \-\-H, bs, cf)+T}@T{+sums of costs of postings from before report start to period end+T}@T{+same as \-\-value=end+T}@T{+sums of values of postings from before period start to period end at+respective posting dates+T}@T{+period end balances, valued at period ends+T}@T{+value at DATE/today of sums of postings+T}+T{+budget amounts (\-\-budget)+T}@T{+like balance changes/end balances+T}@T{+like balance changes/end balances+T}@T{+like balance changes/end balances+T}@T{+like balances+T}@T{+like balance changes/end balances+T}+T{+row totals, row averages (\-T, \-A)+T}@T{+sums, averages of displayed values+T}@T{+sums, averages of displayed values+T}@T{+sums, averages of displayed values+T}@T{+sums, averages of displayed values+T}@T{+sums, averages of displayed values+T}+T{+column totals+T}@T{+sums of displayed values+T}@T{+sums of displayed values+T}@T{+sums of displayed values+T}@T{+sums of displayed values+T}@T{+sums of displayed values+T}+T{+grand total, grand average+T}@T{+sum, average of column totals+T}@T{+sum, average of column totals+T}@T{+sum, average of column totals+T}@T{+sum, average of column totals+T}@T{+sum, average of column totals+T}+T{+T}@T{+T}@T{+T}@T{+T}@T{+T}@T{+T}+.TE+.PP+\f[CR]\-\-cumulative\f[R] is omitted to save space, it works like+\f[CR]\-H\f[R] but with a zero starting balance.+.PP+.SH Lots and capital gains+When you buy (acquire) some amount of an investment commodity (a lot),+it can be important (depending on your local tax rules) to keep track of+its original cost and acquisition date (cost basis), so that when you+sell (dispose) it, you can calculate capital gains (or losses), and+document how you satisfied the rules about disposal order, short term vs+long term gains, and so on.+.PP+For many kinds of investment, each individual lot has its own cost+basis, which must be tracked even if the lot is reduced, split up, or+transferred.+Also lots may need to be moved and disposed of in a prescribed order.+All this can be very hard to keep track of by hand, so usually it is+done by an investment broker, cryptocurrency exchange, or specialised+tax software.+Now, you can also do it yourself with hledger.+.PP+Automated lot tracking and capital gains reporting is the biggest new+feature of hledger 2.+Lot tracking was first shipped in Ledger, then improved in Beancount;+hledger 2 evolves PTA lot tracking further, making it more powerful and+ergonomic.+You can record lot details explicitly, or let hledger infer them.+hledger checks lot entries; tracks, infers and validates lot movements;+and calculates capital gains when lots are sold.+.PP+Note hledger 2\(aqs lot processing happens only for entries that use lot+notation, or where lots are inferred.+If you have hledger 1 journal files that you want to migrate, or use+with both hledger 1 and hledger 2, see hledger 1 and hledger 2.+.PP+For practical advice on turning on lot tracking in an existing journal,+see Start tracking lots.+For a more technical version of what\(aqs in this manual, see+SPEC\-lots.+.SS First lots example+hledger\(aqs lot tracking does not require much extra work.+Here is a small example, using just the familiar \(at syntax, and new+\f[CR]lots\f[R] tag.+(Several ways to write lot entries below shows the other notations.):+.IP+.EX+commodity AAPL ; lots:++2026\-01\-15 buy+ assets:cash \-$500+ assets:stocks 10 AAPL \(at $50++2026\-02\-01 sell some+ assets:stocks \-5 AAPL \(at $70+ assets:cash $350+.EE+.PP+Lot tracking is activated for AAPL by the \f[CR]lots\f[R] tag, so+hledger will+.IP \(bu 2+keep track of each lot that\(aqs acquired (and optionally show them in+reports)+.IP \(bu 2+dispose of lots in the right order (FIFO by default)+.IP \(bu 2+calculate the resulting capital gain, and add the gain posting if+missing+.IP \(bu 2+check for many kinds of error (such as selling more than you have).+.PP+\f[CR]print\f[R] shows the inferred cost basis annotations and gain+posting (so its output can be re\-read even without the+\f[CR]commodity\f[R] directive, if the default cost basis method is+used):+.IP+.EX+$ hledger print+2026\-01\-15 buy+ assets:cash $\-500+ assets:stocks 10 AAPL {$50} \(at $50++2026\-02\-01 sell some+ assets:stocks \-5 AAPL {2026\-01\-15, $50} \(at $70+ assets:cash $350+ revenues:gain $\-100+.EE+.PP+\f[CR]print\f[R]\(aqs \f[CR]\-a\f[R] flag (short for \f[CR]\-\-all\f[R])+shows maximum detail, including the lots as subaccounts and tags showing+how the entry was analysed:+.IP+.EX+$ hledger print \-a+2026\-01\-15 buy+ assets:cash $\-500+ assets:stocks:{2026\-01\-15, $50} 10 AAPL {$50} \(at $50 ; ptype: acquire++2026\-02\-01 sell some+ assets:stocks:{2026\-01\-15, $50} \-5 AAPL {2026\-01\-15, $50} \(at $70 ; ptype: dispose+ assets:cash $350+ revenues:gain $\-100 ; ptype: gain, generated\-posting:+.EE+.PP+If anything looks wrong, see Troubleshooting lots below.+.PP+Once you have lot entries, \f[CR]holdings\f[R] will show an overview of+your investments \- units held, per\-unit and total cost and value,+realised and unrealised gain, and XIRR (extended internal rate of+return).+To see all of these, add at least one market price declaration, eg:+.IP+.EX+P 2026\-03\-31 AAPL $72+.EE+.PP+Then:+.IP+.EX+$ hledger holdings \-e 2026\-04\-01+Holdings on 2026\-03\-31++ || Date Age Units Avg cost Unit price Total cost Total value Weight UGain UGain% RGain XIRR +===============++===============================================================================================================+ assets:stocks || 2026\-01\-15 75d 5 AAPL $50 $72 $250 $360 100.0% $110 44.0% $100 1865.3% +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ || 5 AAPL $50 $250 $360 100.0% $110 44.0% $100 1865.3% +.EE+.PP+You can add \f[CR]\-\-lots\f[R] to see the individual lots (this works+with all reports):+.IP+.EX+$ hledger holdings \-e 2026\-04\-01 \-\-lots+Holdings on 2026\-03\-31++ || Date Age Units Unit cost Unit price Total cost Total value Weight UGain UGain% RGain XIRR +=================================++================================================================================================================+ assets:stocks:{2026\-01\-15, $50} || 2026\-01\-15 75d 5 AAPL $50 $72 $250 $360 100.0% $110 44.0% $100 1865.3% +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ || 5 AAPL $50 $250 $360 100.0% $110 44.0% $100 1865.3% +.EE+.SS Writing lot entries+Lot tracking can be enabled in two ways:+.IP \(bu 2+\f[I]Per posting:\f[R] write explicit cost basis annotations like in+Ledger or Beancount, or explicit lot subaccount names.+These postings will be tracked lotfully.+.IP \(bu 2+\f[I]Per commodity:\f[R] declare the commodity lotful with a+\f[CR]lots\f[R] tag.+All of its postings are tracked lotfully, and the annotations are+inferred for you.+This is convenient, and recommended.+.PP+A posting with any of these is called a lot posting.+.SS Cost basis annotations+Each acquisition of an investment creates a \f[I]lot\f[R], with a+\f[I]cost basis\f[R].+In hledger, a lot\(aqs cost basis has 2\-3 parts:+.IP "1." 3+The nominal acquisition date (required).+Usually this is the date you acquired the lot.+.IP "2." 3+A short text label (optional).+This can be used to distinguish lots acquired on the same date.+.IP "3." 3+The nominal acquisition cost (required).+Usually this is what you paid for it.+.PP+In the journal, we can write \f[I]cost basis annotations\f[R], enclosed+in {} after an amount (the syntax is described in Cost basis), above.+These often mention only part of the cost basis, typically just the cost+(\f[CR]{$50}\f[R]), or nothing at all (\f[CR]{}\f[R]); hledger infers+the rest.+.PP+On an acquisition, the annotation records the new lot\(aqs cost basis.+On a disposal or transfer, it is instead a \f[I]lot selector\f[R],+choosing which existing lot(s) to take from: a full or partial cost+basis, like \f[CR]{2026\-01\-15, $50}\f[R] or \f[CR]{2026\-01\-15}\f[R],+identifies one specific lot, while \f[CR]{}\f[R] (or no annotation) lets+hledger choose, using the cost basis method.+.SS Lotful commodities+A more convenient way to record lot transactions, is to declare+commodities as \f[I]lotful\f[R], by adding a \f[CR]lots\f[R] tag in+their declaration.+Eg:+.IP+.EX+commodity AAPL ; lots:+.EE+.PP+This tells hledger that postings involving these commodities always+involve lots, so it will infer cost basis annotations automatically, and+you won\(aqt need to write them in the journal.+.PP+The \f[CR]lots\f[R] tag can also have a value, selecting the disposal+order (see Cost basis methods); and on account declarations it disables+or customises lot tracking per account, as described in Disabling lot+tracking below.+.SS Lot subaccounts+Internally, hledger tracks each lot in a subaccount, named like the cost+basis.+You don\(aqt need to write these subaccounts in the journal; hledger+infers them automatically.+They are hidden from reports by default, since there can be many lots.+To show them, add the \f[CR]\-\-lots\f[R] flag to any report (the+holdings command is designed for viewing them).+.PP+If you do write a lot subaccount in the journal, it is equivalent to+writing a cost basis annotation on the amount:+.IP+.EX+2026\-01\-15 buy+ assets:stocks:{2026\-01\-15, $50} 10 AAPL+ assets:cash+.EE+.IP+.EX+$ hledger print +2026\-01\-15 buy+ assets:stocks 10 AAPL {2026\-01\-15, $50}+ assets:cash+.EE+.PP+A final account name part enclosed in \f[CR]{\f[R] and \f[CR]}\f[R] is+reserved for lot subaccounts, and it must be a valid lot subaccount name+(unless using \f[CR]\-I\f[R] or \f[CR]\-\-ignore\-lots\f[R]).+Lot subaccount names must be complete, including all cost basis parts \-+date, label if any, and cost.+.PP+When strictly checking account names, lot subaccounts are ignored \- you+only need to declare the base account (eg \f[CR]assets:stocks\f[R]), not+the lot subaccounts.+.SS Several ways to write lot entries+Here are two acquisitions and a disposal, written in several ways.+First, with explicit lot subaccounts:+.IP+.EX+2026\-01\-15 buy low+ assets:stocks:{2026\-01\-15, $50} 10 AAPL+ assets:cash \-$500++2026\-02\-01 buy high+ assets:stocks:{2026\-02\-01, $60} 10 AAPL+ assets:cash \-$600++2026\-03\-01 sell some+ assets:stocks:{2026\-01\-15, $50} \-5 AAPL \(at $70+ assets:cash $350+.EE+.PP+Second, with cost basis annotations (here the \f[CR]{}\f[R] selector+means: use the default method, FIFO; and the \f[CR]\(at\f[R] costs could+be omitted, since hledger can infer them from the cash postings):+.IP+.EX+2026\-01\-15 buy low+ assets:stocks 10 AAPL {$50}+ assets:cash \-$500++2026\-02\-01 buy high+ assets:stocks 10 AAPL {$60}+ assets:cash \-$600++2026\-03\-01 sell some+ assets:stocks \-5 AAPL {} \(at $70+ assets:cash $350+.EE+.PP+Third, with a \f[CR]lots\f[R] tag on the commodity, lots are inferred+from the transacted costs:+.IP+.EX+commodity AAPL ; lots:++2026\-01\-15 buy low+ assets:stocks 10 AAPL \(at $50+ assets:cash \-$500++2026\-02\-01 buy high+ assets:stocks 10 AAPL \(at $60+ assets:cash \-$600++2026\-03\-01 sell some+ assets:stocks \-5 AAPL \(at $70+ assets:cash $350+.EE+.PP+All three notations produce the same lots and the same $100 gain; Lot+reports below shows them.+.SS Disabling lot tracking+If you want a commodity tracked lotfully in only some accounts, use+annotations rather than the \f[CR]lots\f[R] tag.+Or if it should be tracked everywhere except certain accounts (eg+tax\-sheltered accounts where cost basis doesn\(aqt matter), use the+\f[CR]lots\f[R] tag, and add a \f[CR]lots: NONE\f[R] tag to those+accounts\(aq declarations to disable lot tracking there:+.IP+.EX+account assets:ira ; lots: NONE+.EE+.PP+Postings in such accounts are not lot\-tracked and get no lot+subaccounts or gain postings, unless they have explicit lot annotations,+which always enable tracking.+Moving a lotful commodity from a tracked account into such an account is+a disposal; moving it out again needs a cost basis or price on the+receiving posting.+.PP+Sometimes you may want to disable lots/gains processing entirely, to+silence lot\-related errors when you are working with incomplete+journals (eg, when piping hledger print into another hledger command, or+when fixing a complex journal\(aqs problems one at a time).+For this, use the \f[CR]\-\-ignore\-lots\f[R] flag, or just+\f[CR]\-I\f[R].+This skips lot tracking, capital gains calculation, and all lot error+checking, while still doing enough lot inference that lot entries+balance as usual.+Reports then show no lot subaccounts or gains, and \f[CR]print\f[R]+shows lot entries as you wrote them, without inferred cost basis+annotations or gain postings (explicit annotations are kept, and may not+be readable by hledger 1; if that\(aqs needed, use \f[CR]\-O ledger\f[R]+to write them in Ledger\(aqs syntax, which hledger 1 accepts and+ignores).+.SS Lot movements+hledger understands three kinds of lot movement: acquire, transfer, and+dispose.+Other real\-world lot events can usually be modelled using combinations+of these (see Other lot events below).+These are described for lots in asset accounts; in liability accounts,+which hold short positions, the signs are reversed.+.PP+Lots are calculated in date order, and entries on the same date in the+order they are read (an included file is read at the point where it is+included).+So an entry which takes lots out of an account must come after the+entries that put them there, even on the same date; hledger doesn\(aqt+reorder entries to make lots available.+When this goes wrong, the \(dqno lots available\(dq error names a later+entry on the same date which would have supplied the lots, if there is+one.+.SS Acquire+A positive lot posting in an asset account creates a new lot.+.IP+.EX+2026\-01\-01 buy shares+ assets:cash \-$500+ assets:broker 10 ETSY {$50}+.EE+.PP+The asset posting\(aqs cost is the lot\(aqs cost basis; hledger balances+the transaction and calculates gains with it.+It can be written as a cost basis annotation (\f[CR]{UNITCOST}\f[R] or+\f[CR]{{TOTALCOST}}\f[R]) or as a transacted cost+(\f[CR]\(at UNITCOST\f[R] or \f[CR]\(at\(at TOTALCOST\f[R]); in an+acquisition these mean the same thing.+(Note, \f[CR]\(at\f[R] alone makes a lot posting only if the commodity+is declared lotful or the account is named like a lot subaccount;+otherwise it is just a conversion and creates no lot.+To make it an acquisition, adding just \f[CR]{}\f[R] would be enough, eg+\f[CR]10 ETSY {} \(at $50\f[R].)+Usually you write just one and the other is inferred; if both are+written, they must agree (at the precision you wrote the basis with; the+exact transacted cost is then used as the basis; see also Basis and+transacted cost must agree).+(The total cost forms are useful when the unit cost is+non\-terminating.)+The cost can also be inferred from a lot subaccount name, or, for a+lotful commodity, from the transaction\(aqs other postings \- so even a+bare positive posting (no \f[CR]{}\f[R] or \f[CR]\(at\f[R]) can be an+acquire.+.PP+The other postings show what funded the basis, such as:+.IP \(bu 2+cash for what you paid (including fees if you want those capitalised in+the basis; see Capitalising fees)+.IP \(bu 2+an expense posting for any part of what you paid that isn\(aqt basis (a+fee you don\(aqt want to capitalise)+.IP \(bu 2+an income or equity posting for any part you didn\(aqt pay (as with a+gift\(aqs carryover basis or shares received as compensation).+.PP+Eg shares received as a gift, with the giver\(aqs basis carried over:+.IP+.EX+2026\-01\-01 gift of 10 AAPL, carryover basis $50/share+ equity:gifts received $\-500+ assets:stocks 10 AAPL \(at $50+.EE+.PP+Other cases with a basis differing from what was paid include+inheritance (stepped\-up basis), stock options and RSUs, and wash sales;+see https://en.wikipedia.org/wiki/Cost_basis.+Recording them this way keeps the accounting equation balanced and shows+where the basis came from.+.SS Basis and transacted cost must agree+In an acquisition, if both a cost basis (\f[CR]{}\f[R]) and a transacted+cost (\f[CR]\(at\f[R]) are written, they must be the same.+(Ledger and Beancount allow them to differ; hledger reports an error.)+This is because:+.IP \(bu 2+In hledger, \f[CR]\(at\f[R] has one consistent meaning: the transacted+cost, what was actually exchanged.+It\(aqs what transactions balance with (except for lot disposals, which+balance with the cost basis; see Gains).+Market prices are recorded with \f[CR]P\f[R] directives, and cost basis+with \f[CR]{}\f[R] annotations.+(hledger may infer the \f[CR]{}\f[R] from \f[CR]\(at\f[R] in a lot+acquisition, as \f[CR]print \-a\f[R] will show.)+.IP \(bu 2+If \f[CR]\(at\f[R] and \f[CR]{}\f[R] could differ, the difference would+have no proper place.+If the entry balanced with \f[CR]\(at\f[R] while gains were calculated+from \f[CR]{}\f[R], the difference would be unaccounted for: it would be+neither gain nor income, and cost reports (eg \f[CR]bse \-B\f[R]) would+be off by it.+If it balanced with \f[CR]{}\f[R] instead (as in Ledger and Beancount),+\f[CR]\(at\f[R] would need a second meaning, an informational market+price.+.IP \(bu 2+Real cases where the basis differs from what was paid (gifts,+inheritance, RSUs..)+don\(aqt need it.+They are better recorded as shown above, with the difference funded by a+separate posting, recording where it came from.+.IP \(bu 2+It catches mistakes.+Otherwise, a typo in either amount would silently miscalculate gains.+.PP+So, if you have such entries (eg from Ledger or Beancount), you can+rewrite them depending on what was intended:+.IP \(bu 2+If \f[CR]\(at\f[R] was meant as a market price (the usual Ledger and+Beancount meaning), drop it, and record the price with a \f[CR]P\f[R]+directive.+Eg, this Ledger entry, which balances with the basis, and records a+market price of 1.30 USD:+.RS 2+.IP+.EX+2026\-01\-01 buy+ assets:test 10.00 EUR {1.23 USD} \(at 1.30 USD+ assets:bank+.EE+.PP+can be written for hledger like this:+.IP+.EX+P 2026\-01\-01 EUR 1.30 USD++2026\-01\-01 buy+ assets:test 10.00 EUR {1.23 USD}+ assets:bank+.EE+.RE+.IP \(bu 2+If the basis really differs from what you paid, write the same amount in+both (or just one of them), and record the difference with a separate+posting, as in the gift example above.+.IP \(bu 2+If they differ only by rounding, write the basis with more decimal+places, or use the total cost forms.+.IP \(bu 2+To load an old journal without errors (and without lot tracking), use+\f[CR]\-I\f[R]/\f[CR]\-\-ignore\-lots\f[R].+.SS Capitalising fees+hledger does not automatically capitalise fees into cost basis (as some+tax treatments allow, for purchase or transfer fees).+To capitalise an acquisition fee, fold it into the acquisition cost:+.IP+.EX+2026\-01\-15 buy 10 AAPL at $50, plus a $10 commission, capitalised+ assets:stocks 10 AAPL \(at\(at $510+ assets:cash \-$510+.EE+.PP+This lot\(aqs cost basis is $51 per share.+(Recording the commission as a separate expense posting would instead+keep it out of the basis.)+Capitalising an in\-kind transfer fee is possible too, but fiddly; see+Other lot events.+.SS Transfer+A matching pair of negative/positive lotful postings moves one or more+existing lots between accounts, preserving their cost basis.+.IP+.EX+2026\-05\-01 transfer to another broker+ assets:broker \-10 ETSY+ assets:broker2 10 ETSY+.EE+.PP+Transfer postings should not have a transacted price, and the total+quantities sent and received must match: transferred lots keep their+identity.+Within that, source and destination postings need not pair up one to one+\- one source posting can feed several destination accounts, or several+sources one destination.+The destination amount, or the source amount, can also be elided, even+when the other posting carries a lot selector (eg+\f[CR]assets:broker \-10 ETSY {2026\-01\-01}\f[R] balanced by a bare+\f[CR]assets:broker2\f[R] posting, or vice versa).+.PP+A consequence: a disposal entry mistakenly written without a selling+price, and with the other amount left implicit, looks like a lot+transfer, and is quietly read as one, without raising an error.+If in doubt, \f[CR]print \-a\f[R] shows how an entry was read.+.SS Transfer fees+If the destination receives less than the source sends (eg because an+exchange deducted a fee), record the fee as its own posting in the same+commodity, eg \f[CR]expenses:fees 0.001 ETH \(at $3000\f[R] (or without+the price); several fee postings which together make up the difference+also work.+hledger reads the fee as a small disposal (consuming lots in the usual+cost basis method order, before the transfer) and transfers the rest.+With a price, the fee disposal gets a gain calculated; without one, it+doesn\(aqt.+Otherwise, mismatched sent/received totals are an error.+\f[CR]print \-\-lots\f[R] (or \f[CR]print \-a\f[R]) shows how the entry+was read.+.PP+Conversely, if the destination receives \f[I]more\f[R] than the source+sends (eg a reclaimed fee, or dust from a past bookkeeping error), a fee+can\(aqt explain that, and the extra should be recorded as its own+acquisition: give it a real or dummy cost basis (or price) annotation,+which keeps it out of the transfer matching.+Eg:+.IP+.EX+2026\-05\-01 transfer, plus a reclaimed fee+ assets:broker \-10 ETH+ assets:broker2 10 ETH+ expenses:fees \-0.001 ETH+ assets:broker2 0.001 ETH {$0}+.EE+.SS Transfers recorded in two entries+A transfer between your own accounts is sometimes recorded twice, once+from each account\(aqs statement, the two entries meeting in a clearing+account:+.IP+.EX+2026\-01\-03 send to wallet A ; from wallet B\(aqs statement+ assets:wallet B \-0.11 ETH+ assets:transfers 0.10 ETH+ expenses:fees 0.01 ETH++2026\-01\-03 receive from wallet B ; from wallet A\(aqs statement+ assets:transfers \-0.10 ETH+ assets:wallet A 0.10 ETH+.EE+.PP+The receiving entry takes the lots out of the clearing account, so the+sending entry must be read first (see Lot movements).+When each statement is imported into its own file, this depends on the+order the files are included in.+Some ways to make it reliable:+.IP \(bu 2+Record the transfer as one entry, from one statement, and drop it from+the other (eg with a \f[CR]skip\f[R] rule in that account\(aqs CSV+rules).+This is the most accurate model of a single event, and doesn\(aqt depend+on order.+.IP \(bu 2+Include the sending account\(aqs files before the receiving+account\(aqs.+This stops working if, on some date, transfers go both ways.+.SS Dispose+A negative lot posting sells from one or more existing lots.+.IP+.EX+2026\-08\-01 sell at a gain+ assets:broker2 \-10 ETSY {$50} \(at $90 ; selecting the lot by specific identification+ assets:cash $900+ revenues:gain $\-400 ; gain can be recorded explicitly or left implicit+.EE+.PP+The disposal posting must have a transacted price (the selling price),+either explicit or inferred: $90 here.+.PP+One exception: an \f[I]in\-kind disposal\f[R], where the entry\(aqs+non\-asset postings receive the disposed units (the same commodity, in+the same total quantity, possibly split across postings), may be+priceless.+Eg a transfer fee deducted in the commodity, or an in\-kind donation.+This is a simple way to record such outflows when you don\(aqt need a+gain calculated: the disposed units leave their lot(s) carrying their+own cost basis, so the remaining units\(aq basis is unchanged, but no+gain or loss is recognised, and the receiving posting holds unpriced+commodity units.+To have the gain calculated, give the receiving posting a transacted+price.+.PP+When the gain posting is inferred, it is calculated from the entry\(aqs+dispose postings only (the quantity times the difference between selling+price and cost basis, summed); acquire postings in the same entry+don\(aqt contribute.+.SS Short positions+A short position \- units sold before they are bought, with the broker+lending them \- is recorded as lots in a \f[I]liability\f[R] account+(type \f[CR]L\f[R], declared or inferred from the account name).+There the signs are reversed: a \f[I]negative\f[R] lot posting opens a+short lot (it is an acquire, whose cost basis is the short\-sale price),+and a \f[I]positive\f[R] lot posting closes it, by buying units back (it+is a disposal, whose transacted price is the buying price).+A short lot\(aqs gain is its basis minus the buying price, so it is+positive when the price has fallen:+.IP+.EX+commodity XYZ ; lots:++2026\-01\-02 sell short+ liabilities:broker:XYZ \-10 XYZ \(at $100+ assets:broker:cash++P 2026\-01\-31 XYZ $90++2026\-02\-02 cover+ liabilities:broker:XYZ 10 XYZ \(at $90+ assets:broker:cash+ revenues:gain+.EE+.IP+.EX+$ hledger \-f short.journal print \-x+2026\-01\-02 sell short+ liabilities:broker:XYZ \-10 XYZ {$100} \(at $100+ assets:broker:cash $1000++2026\-02\-02 cover+ liabilities:broker:XYZ 10 XYZ {2026\-01\-02, $100} \(at $90+ assets:broker:cash $\-900+ revenues:gain $\-100+.EE+.PP+Reports work as for long positions.+While the position is open, \f[CR]bs \-B\f[R] shows the liability at+cost ($1000), offsetting the cash received; \f[CR]bs \-V\f[R] shows it+at market value ($900), so the net worth includes the unrealised gain;+\f[CR]bal \-\-gain\f[R] shows that gain ($100); and \f[CR]holdings\f[R]+shows negative units and cost (but no XIRR, which is not meaningful for+a short position).+After covering, the realised gain is in \f[CR]revenues:gain\f[R], and+\f[CR]bse\f[R] balances.+.PP+Everything else is as for lots in asset accounts: cost basis annotations+and lot subaccounts, lot selectors and cost basis methods, generated or+user\-written gain postings, and \f[CR]lots: NONE\f[R] to opt out.+Note that HIFO covers the highest short\-sale price first, which+realises the largest gain first; use SPECID to choose.+Long lots and short lots of the same commodity are separate pools, so+they may use different methods.+.PP+Transferring a short position between accounts is not yet supported:+cover it in one account and open it in the other, with prices.+(\f[CR]close \-\-lots\f[R] can move short lots to and from equity,+though.)+A negative posting in an \f[I]asset\f[R] account holding no lots is+still an error, since it is usually a mistake.+.SS Other lot events+Other real\-world events \- a gift received with a carryover cost basis,+bonus shares, a stock split, capitalising an in\-kind transfer fee \-+can be recorded as combinations of acquires, transfers and disposals.+Other lot events on hledger.org has worked examples.+The right treatment varies by jurisdiction, so check your local tax+rules.+.SS Cost basis methods+If a lot transfer or a lot disposal doesn\(aqt specifically identify the+lot(s) involved, hledger selects from the available lots automatically,+using a \f[I]cost basis method\f[R] (AKA disposal method / reduction+method / booking method).+.PP+Use the method your tax jurisdiction requires or allows.+The default method is FIFO (first in, first out).+You can override this with a \f[CR]lots\f[R] tag value on the commodity+or account declaration.+(An account tag will take precedence; on an account, the tag requires a+method value.)+Eg:+.IP+.EX+commodity FUND ; lots: AVERAGE+account assets:stocks ; lots: LIFO+.EE+.PP+These methods are supported:+.PP+.TS+tab(@);+lw(8.2n) lw(14.3n) lw(11.9n) lw(35.6n).+T{+Method+T}@T{+Lots selected+T}@T{+Disposal cost basis+T}@T{+Error checking+T}+_+T{+\f[B]SPECID\f[R]+T}@T{+one specific lot+T}@T{+specified lot\(aqs cost+T}@T{+A matching lot, with sufficient balance, exists in the account.+T}+T{+\f[B]FIFO\f[R]+T}@T{+oldest first+T}@T{+each lot\(aqs cost+T}@T{+Sufficient lot(s) exist in the account.+T}+T{+\f[B]LIFO\f[R]+T}@T{+newest first+T}@T{+each lot\(aqs cost+T}@T{+\(dq+T}+T{+\f[B]HIFO\f[R]+T}@T{+highest cost first+T}@T{+each lot\(aqs cost+T}@T{+\(dq+T}+T{+\f[B]AVERAGE\f[R]+T}@T{+oldest first+T}@T{+average cost+T}@T{+\(dq+T}+T{+\f[B]FIFOALL\f[R]+T}@T{+oldest first (all accounts)+T}@T{+each lot\(aqs cost+T}@T{+Sufficient lot(s) exist in the account, and are highest priority across+all accounts.+T}+T{+\f[B]LIFOALL\f[R]+T}@T{+newest first (all accounts)+T}@T{+each lot\(aqs cost+T}@T{+\(dq+T}+T{+\f[B]HIFOALL\f[R]+T}@T{+highest cost first (all accounts)+T}@T{+each lot\(aqs cost+T}@T{+\(dq+T}+T{+\f[B]AVERAGEALL\f[R]+T}@T{+oldest first (all accounts)+T}@T{+average cost (all accounts)+T}@T{+Sufficient lot(s) exist across all accounts.+T}+.TE+.PP+\f[B]SPECID\f[R] (specific identification) is what you\(aqre using when+a disposal names its lot(s), with a lot selector like+\f[CR]{2026\-01\-15, $50}\f[R] or an explicit lot subaccount.+Select by date (and label) rather than by cost alone: costs shown in lot+names may be rounded (see Cost basis precision), so a cost\-only+selector like \f[CR]{$50}\f[R] can match more lots than intended (an+ambiguity error under SPECID; under other methods, consumed in the+method\(aqs order).+.PP+\f[B]AVERAGE\f[R] keeps one running average cost per account (pool),+recalculated at each acquisition and applied to every lot in the pool;+disposals use it, consuming lots in FIFO order so acquisition dates stay+meaningful for holding periods.+Lot names omit the cost (\f[CR]{2026\-01\-15}\f[R]), the average appears+in the holdings Avg cost column and in disposal postings shown by+\f[CR]print \-x\f[R], and transferring lots into or out of the pool+carries the average with them (a lot\(aqs original cost can\(aqt be+recovered from a pool).+close \-\-lots writes each lot with the pool\(aqs average cost as of the+closing date (\f[CR]{2026\-01\-15, $55}\f[R]), so that its output can be+read back, eg to start a new file.+(\f[CR]print \-\-lots\f[R] output for AVERAGE lots can\(aqt be read back+yet.)+.PP+The \f[B]*ALL\f[R] variants additionally check that the lots selected+are the ones that would be chosen across all accounts holding the+commodity, and raise an error naming the other account otherwise; use+them to enforce a global disposal order across brokers, exchanges and+wallets.+Since they involve every account, declare them on the commodity, not on+accounts.+\f[B]AVERAGEALL\f[R] likewise keeps a single average across all+accounts.+.SS Changing the cost basis method+hledger recalculates all lots on each run, using the currently declared+methods.+So changing a declared method also reinterprets past history under the+new method.+Sometimes that\(aqs fine; but usually you\(aqll want past disposals to+keep their original lot selections and gains (tax authorities generally+expect a method change to apply only going forward).+Things to know:+.IP \(bu 2+Disposals recorded without explicit lot selectors or gain amounts will+select different lots under the new method, changing their cost bases+and realised gains.+.IP \(bu 2+Disposals which do record the old method\(aqs selections \- as explicit+gain amounts, lot selectors, lot subaccount names, or balance assertions+\- will be checked against the new method\(aqs selections, and any+differences will be reported as errors.+.PP+hledger doesn\(aqt yet support declaring different methods for different+time periods, but you can make a method change apply only to the future,+in either of two ways:+.IP "1." 3+Make past disposals fully explicit, with lot selectors and gain amounts,+so they no longer depend on the declared method (\f[CR]print \-x\f[R]+and \f[CR]print \-\-lots\f[R] can help with this).+Then change the method.+.IP "2." 3+Or, start a new journal file at the changeover date, using+\f[CR]close \-\-clopen \-\-lots\f[R] to carry the current lots into it,+and declare the new method in the new file.+.SS Gains+Each disposal transaction has a \f[B]gain posting\f[R], usually on a+Gain\-type account, recording the capital gain (or loss) as revenue (or+negative revenue).+(Following the usual PTA style, a negative number here means profit, a+positive number means loss.)+.PP+A disposal balances at cost basis, not at transacted cost: the disposed+units count as their quantity times their cost basis (what they cost+you), the proceeds are what you received, and the gain posting accounts+for the difference.+Eg selling 5 AAPL bought at $50 for $70 each:+\f[CR]\-5 AAPL {$50} \(at $70\f[R] counts as \-$250, \f[CR]$350\f[R] is+received, and \f[CR]revenues:gain $\-100\f[R] balances the entry.+(This is the historical cost accounting convention, and is how hledger 1+users have recorded gains.+Unrealised gains are not recorded as postings, but can be reported from+market prices, eg with holdings or \f[CR]\-\-gain\f[R].+Consequently the accounting equation stays balanced through disposals.)+.PP+The gain posting can be left implicit (and hledger will infer it); or it+can be written explicitly in the journal.+Recording gains below shows examples of both.+.PP+In an inferred gain posting, the gain amount will be rounded to the+entry\(aqs local precision for the gain commodity (or if the local+precision is zero, two decimal digits will be shown \- except when both+of those digits are zero).+More decimals can be seen by increasing the display precision (eg+\f[CR]hledger print \-\-round=soft \-c \(aq$1.0000\(aq\f[R]).+.PP+An explicit gain posting can also be written without an amount, in which+case hledger fills in the calculated gain (as when the gain posting is+omitted, but with your choice of account).+At most one gain posting per entry can be left amountless.+.SS Gain accounts+The \f[B]\f[CB]Gain\f[B]\f[R] (\f[B]\f[CB]G\f[B]\f[R]) account type is a+subtype of Revenue.+Declaring an account with the G type serves three purposes:+.IP "1." 3+\f[B]Recognising gain postings\f[R] \- explicit gain postings which use+the G account will be detected reliably by account type, and error+messages may be clearer.+.IP "2." 3+\f[B]Customising account names\f[R] \- inferred gain postings will use+the first\-declared G account, rather than the default+(\f[CR]revenues:gain\f[R]).+(If no account is declared with the G type, they use the alphabetically+first account whose type is inferred as G, if any.)+.IP "3." 3+\f[B]Categorising\f[R] \- when reporting, you can match on the G account+type specifically.+.PP+G is inferred from conventional English account names (eg+\f[CR]revenues:gain\f[R], \f[CR]income:capital\-gains\f[R]; see the+regex table under Account types).+You can also declare it explicitly:+.IP+.EX+account revenues:capital gain ; type: G+.EE+.PP+(There is also an \f[B]\f[CB]UnrealisedGain\f[B]\f[R]+(\f[B]\f[CB]U\f[B]\f[R]) account type, a subtype of Equity, for accounts+like \f[CR]equity:unrealised\-gain\f[R]; hledger does not currently+generate postings to these.)+.PP+Why do we post both gains and losses to a revenue account ?+It\(aqs more convenient than using separate revenue and expense+accounts, and the sign keeps things correct.+.SS Recording gains+In a disposal entry, you can leave the gain posting out and let hledger+infer it.+This is the simplest style, and avoids most problems:+.IP+.EX+2026\-02\-01 sell+ assets:stocks \-1 AAPL {$50} \(at $60+ assets:cash $60+.EE+.PP+Or you can write it, on an account declared with the G account type.+hledger then checks your amount against the calculated gain, catching+more errors:+.IP+.EX+account revenues:gain ; type:G++2026\-02\-01 sell+ assets:stocks \-1 AAPL {$50} \(at $60+ assets:cash $60+ revenues:gain $\-10+.EE+.PP+Multiple gain postings are allowed, eg one per lot when disposing from+several lots.+.PP+Your amount needs to match the calculated gain only at the entry\(aqs+precision (the most decimal places used by the entry\(aqs amounts in+that commodity, as in transaction balancing).+hledger then uses the exact calculated gain, so that the small+difference isn\(aqt left unaccounted for (with several gain postings, it+adjusts the last one).+\f[CR]print\f[R] still shows your amount as written.+.PP+A written gain posting also protects your history, like a balance+assertion: hledger recalculates lots and gains from the whole journal+each time it runs, so if a past acquisition is edited, an inferred gain+could silently change, whereas a written one no longer matches and is+reported as an error.+\f[CR]hledger print \-x\f[R] shows the inferred gain postings, if you+want to write them into the journal.+.PP+A gain posting on an undeclared account also works: hledger detects it+heuristically (roughly: a posting to a non\-asset/liability/equity+account, not itself a lot posting, without which the rest of the entry+balances).+But the heuristic fails when the entry has another such posting, eg a+fee, and the entry is then reported as unbalanced.+So if you write gain postings, declare the account\(aqs type.+\f[CR]hledger print \-a\f[R] shows what was detected.+.PP+(Earlier hledger 2 previews also generated an+\f[CR]equity:unrealised\-gain\f[R] counter posting in each disposal, so+that disposals balanced at transacted cost.+This is no longer done, and such postings, if written explicitly, will+now leave the entry unbalanced; remove them.)+.SS Lot reports+Once lot entries are in the journal, all the usual reports work as+normal, hiding lot detail by default; \f[CR]\-\-lots\f[R] shows it.+Using the several ways journal above (any version):+.PP+\f[CR]holdings\f[R] gives an overview of your investments: units held,+cost, value, unrealised and realised gain, and XIRR (see First lots+example; add \f[CR]\-\-lots\f[R] for per\-lot detail, \f[CR]\-e\f[R] to+choose the date).+.PP+\f[CR]balance \-\-lots\f[R] (or \f[CR]bs \-\-lots\f[R]) shows the+current lots:+.IP+.EX+$ hledger bal assets:stocks \-\-lots \-N+ 5 AAPL assets:stocks:{2026\-01\-15, $50}+ 10 AAPL assets:stocks:{2026\-02\-01, $60}+.EE+.SS Realised gains+Realised gains are on the Gain\-type account (see Gain accounts), so+\f[CR]type:G\f[R] queries select them.+The total for a period:+.IP+.EX+$ hledger bal type:G \-p 2026+ $\-100 revenues:gain+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ $\-100 +.EE+.PP+Each disposal\(aqs gain, with a running total:+.IP+.EX+$ hledger reg type:G+2026\-03\-01 sell some revenues:gain $\-100 $\-100+.EE+.PP+The disposal entries, with the lots and gain amounts hledger inferred+(\f[CR]\-x\f[R] shows inferred amounts, \f[CR]\-\-lots\f[R] the lot+subaccounts, \f[CR]\-a\f[R] everything including each posting\(aqs+classification):+.IP+.EX+$ hledger print tag:ptype=dispose \-x \-\-lots+2026\-03\-01 sell some+ assets:stocks:{2026\-01\-15, $50} \-5 AAPL {2026\-01\-15, $50} \(at $70+ assets:cash $350+ revenues:gain $\-100+.EE+.PP+When using the roi command with a journal that records lots, make sure+\f[CR]\-\-pnl\f[R] matches the gain account, eg:+.IP+.EX+$ hledger roi \-\-inv assets:stocks \-\-pnl revenues:gain+.EE+.PP+so that realised gains are counted as profit rather than as cash flows+out of the investment.+.SS Unrealised gains+Unrealised gains \- on the units you still hold \- are not recorded in+the journal (see Gains); hledger calculates them from market prices when+asked.+Adding some month\-end prices to the journal above:+.IP+.EX+P 2026\-01\-31 AAPL $55+P 2026\-02\-28 AAPL $65+P 2026\-03\-31 AAPL $80+.EE+.PP+\f[CR]holdings\f[R] shows the unrealised gain (UGain) next to the+realised gain (RGain), per commodity or per lot (\f[CR]\-\-lots\f[R]),+as of today or some other date (\f[CR]\-e\f[R]).+.PP+\f[CR]balance \-\-gain\f[R] shows the unrealised gain per account: the+current value of the units held, minus what they cost.+Like \f[CR]\-V\f[R], it uses the market price at the end of the report+period (today, unless you specify \f[CR]\-e\f[R] or a period):+.IP+.EX+$ hledger bal assets:stocks \-\-gain+ $350 assets:stocks+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ $350 +.EE+.PP+That is: 15 AAPL are held, which cost $850 and are worth $1200 at $80.+\f[CR]\-\-lots\f[R] breaks it down by lot:+.IP+.EX+$ hledger bal assets:stocks \-\-gain \-\-lots \-N+ $150 assets:stocks:{2026\-01\-15, $50}+ $200 assets:stocks:{2026\-02\-01, $60}+.EE+.PP+With a report interval, \f[CR]\-H\f[R] shows the unrealised gain as of+each period end, and without \f[CR]\-H\f[R], how much it changed during+each period:+.IP+.EX+$ hledger bal assets:stocks \-\-gain \-M \-H+Historical gain in 2026Q1, valued at period ends:++ || 2026\-01\-31 2026\-02\-28 2026\-03\-31 +===============++====================================+ assets:stocks || $50 $200 $350 +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ || $50 $200 $350 +.EE+.PP+(This is not the same as \f[CR]\-\-valuechange\f[R], which shows how+much an account\(aqs value changed in each period, from price movements+and from buying and selling.)+.PP+\f[CR]\-\-gain\f[R] needs a market price for the units; where none is+found, the units are shown unconverted, alongside the negated cost.+Realised and unrealised gains don\(aqt overlap: the gain on units sold+is realised, the gain on units held is unrealised, and together they are+the total gain on the investment so far (here, $100 + $350).+.SS Lot details+Some finer points, for reference.+.SS Lot labels+Internally, each lot is identified by its cost basis date plus an+optional label.+Lots of a commodity acquired on the same date (even in different+accounts) must have unique labels to help identify them.+If you don\(aqt provide these, hledger adds sequential labels+automatically (\f[CR]\(dq0001\(dq\f[R], \f[CR]\(dq0002\(dq\f[R], ..).+Labels are used for sorting, so if you write your own, make them+sortable.+.PP+Automatic labels depend on which transactions hledger reads, so the same+lot can get a different label when files are combined (eg yearly files+with closing and opening balances).+If a lot needs a stable label, eg an acquisition dated to an earlier+purchase\(aqs date after a split or demerger, write your own.+Use a descriptive label, eg \f[CR]\(dqdemerger\(dq\f[R], not numbers+like \f[CR]\(dq0001\(dq\f[R], which can clash with automatic labels.+(More detail: SPEC\-lots.)+.SS Cost basis precision+An inferred cost basis can be a non\-terminating decimal (eg+\f[CR]3 ABC \(at\(at $10\f[R] gives a $10/3 unit cost).+hledger keeps such costs at high precision internally and calculates+gains from the unrounded value, but in lot names it displays at most 8+decimal digits, or more if the cost commodity\(aqs declared display+style has more.+Two consequences: when lots are carried into a new file as text (eg with+\f[CR]close \-\-lots\f[R]), only the displayed digits survive, so if you+track commodities needing finer cost precision, declare a wider display+style for the cost commodity up front; and changing a commodity\(aqs+display precision can change how lot names render, so lot selectors+written with the old rendering will need updating (see Troubleshooting+lots).+Selectors using just the date (and label) don\(aqt embed a cost, and are+unaffected.+(More detail: SPEC\-lots.)+.SS Lot postings and balance assertions+See also Assertions and lot subaccounts above.+.PP+On a dispose or transfer posting without an explicit lot subaccount, a+balance assertion always refers to the parent account\(aqs balance.+So if lot subaccounts are added with \f[CR]\-\-lots\f[R], the assertion+is not affected.+.PP+By contrast, in a journal entry where the lot subaccounts are recorded+explicitly, a balance assertion refers to the lot subaccount\(aqs+balance.+.PP+This means that \f[CR]hledger print \-\-lots\f[R], if it adds explicit+lot subaccounts to a journal entry, could potentially change the meaning+of balance assertions, breaking them.+To avoid this, in such cases it will move the balance assertion to a new+zero\-amount posting to the parent account (and make sure it\(aqs+subaccount\-inclusive).+(So eg+\f[CR]hledger \-f\- print \-\-lots \-x | hledger \-f\- check assertions\f[R]+will still pass.)+.SS Troubleshooting lots+hledger analyses lot entries carefully, but it won\(aqt understand every+possible shape.+When it reports a lot\-related error, or a report looks wrong:+.IP \(bu 2+\f[CR]hledger print \-a\f[R] shows how each entry was read: the inferred+cost basis, lot subaccounts and gain posting, and each posting\(aqs+classification (\f[CR]ptype: acquire\f[R], \f[CR]dispose\f[R],+\f[CR]transfer\-from\f[R], \f[CR]transfer\-to\f[R] or \f[CR]gain\f[R]).+If an entry was misread, rewrite it more explicitly, eg by adding a cost+basis annotation, or a transacted cost.+.IP \(bu 2+\(dqno lots matching ...\(dq means a lot selector matched nothing in+that account; the error lists the account\(aqs actual lots.+Common causes: the lot is in another account, or a cost\-only selector+no longer matches the displayed cost (see Cost basis precision; date+selectors avoid this).+.IP \(bu 2+A disposal written without a selling price, with the other amount left+implicit, is silently read as a transfer.+Add the price.+.IP \(bu 2+\(dqrealised gain amount is wrong\(dq means a written gain posting+doesn\(aqt match the calculated gain; the error shows both amounts.+Check which lots were selected (\f[CR]print \-a\f[R]) and the amounts.+.IP \(bu 2+\(dqcost basis ...+differs from its transacted cost\(dq means an acquisition wrote both a+\f[CR]{}\f[R] basis and an \f[CR]\(at\f[R] cost which don\(aqt agree.+Write just one of them, or see Basis and transacted cost must agree for+other fixes.+.IP \(bu 2+\(dqno ...+lots available for disposal\(dq means a sale from an account holding+none of the commodity.+If it is a short sale, record it in a liability account (see Short+positions).+If the purchases were written with just an \f[CR]\(at\f[R] cost (common+in Ledger journals), they did not create lots; declare the commodity+lotful.+.IP \(bu 2+For more detail, \f[CR]\-\-debug=5\f[R] (eg+\f[CR]hledger check \-\-debug=5\f[R]) traces lot processing step by+step.+It\(aqs verbose, and mostly useful for advanced troubleshooting or bug+reports.+.IP \(bu 2+To silence lot processing while fixing other problems, use+\f[CR]\-I\f[R] or \f[CR]\-\-ignore\-lots\f[R].+.SH Generating data+hledger can enrich the data provided to it, or generate new data, in a+number of ways.+Mostly, this is done only if you request it:+.IP \(bu 2+Missing amounts, costs, cost basis, and capital gain amounts are+inferred automatically when possible.+.IP \(bu 2+Lot subaccounts are also inferred (invisibly by default;+\f[CR]\-\-lots\f[R] makes them visible in reports).+.IP \(bu 2+The \f[CR]\-\-infer\-equity\f[R] flag infers missing conversion equity+postings from \(at/\(at\(at costs.+.IP \(bu 2+The \f[CR]\-\-infer\-costs\f[R] flag infers missing costs from+conversion equity postings.+.IP \(bu 2+The \f[CR]\-\-infer\-market\-prices\f[R] flag infers \f[CR]P\f[R] price+directives from costs.+.IP \(bu 2+The \f[CR]\-\-auto\f[R] flag adds extra postings to transactions matched+by auto posting rules.+.IP \(bu 2+The \f[CR]\-\-forecast\f[R] option generates transactions from periodic+transaction rules.+.IP \(bu 2+The \f[CR]balance \-\-budget\f[R] report infers budget goals from+periodic transaction rules.+.IP \(bu 2+Commands like \f[CR]close\f[R], \f[CR]rewrite\f[R], and+\f[CR]hledger\-interest\f[R] generate transactions or postings.+.IP \(bu 2+CSV data is converted to transactions by applying CSV conversion rules..+etc.+.PP+Such generated data is temporary, existing only at report time.+You can convert it to permanent recorded data by, eg, capturing the+output of \f[CR]hledger print\f[R] and saving it in your journal file.+This can sometimes be useful as a data entry aid.+.PP+If you are curious what data is being generated and why, run+\f[CR]hledger print \-a\f[R] (equivalent to+\f[CR]\-\-explicit \-\-lots \-\-verbose\-tags\f[R]).+\f[CR]\-x/\-\-explicit\f[R] shows inferred amounts and conversion+prices, \f[CR]\-\-lots\f[R] shows lot subaccounts and lot\-specific+postings, and \f[CR]\-\-verbose\-tags\f[R] shows the hidden tags which+hledger uses for analysing transactions .+.SH Forecasting+Forecasting, or speculative future reporting, can be useful for+estimating future balances, or for exploring different future scenarios.+.PP+The simplest and most flexible way to do it with hledger is to manually+record a bunch of future\-dated transactions.+You could keep these in a separate \f[CR]future.journal\f[R] and include+that with \f[CR]\-f\f[R] only when you want to see them.+.SS \-\-forecast+There is another way: with the \f[CR]\-\-forecast\f[R] option, hledger+can generate temporary \(dqforecast transactions\(dq for reporting+purposes, according to periodic transaction rules defined in the+journal.+Each rule can generate multiple recurring transactions, so by changing+one rule you can change many forecasted transactions.+.PP+Forecast transactions usually start after ordinary transactions end.+By default, they begin after your latest\-dated ordinary transaction, or+today, whichever is later, and they end six months from today.+(The exact rules are a little more complicated, and are given below.)+.PP+This is the \(dqforecast period\(dq, which need not be the same as the+report period.+You can override it \- eg to forecast farther into the future, or to+force forecast transactions to overlap your ordinary transactions \- by+giving the \-\-forecast option a period expression argument, like+\f[CR]\-\-forecast=..2099\f[R] or+\f[CR]\-\-forecast=2023\-02\-15..\f[R].+Note that the \f[CR]=\f[R] is required.+.SS Inspecting forecast transactions+\f[CR]print\f[R] is the best command for inspecting and troubleshooting+forecast transactions.+Eg:+.IP+.EX+\(ti monthly from 2022\-12\-20 rent+ assets:bank:checking+ expenses:rent $1000+.EE+.IP+.EX+$ hledger print \-\-forecast \-\-today=2023/4/21+2023\-05\-20 rent+ ; generated\-transaction: \(ti monthly from 2022\-12\-20+ assets:bank:checking+ expenses:rent $1000++2023\-06\-20 rent+ ; generated\-transaction: \(ti monthly from 2022\-12\-20+ assets:bank:checking+ expenses:rent $1000++2023\-07\-20 rent+ ; generated\-transaction: \(ti monthly from 2022\-12\-20+ assets:bank:checking+ expenses:rent $1000++2023\-08\-20 rent+ ; generated\-transaction: \(ti monthly from 2022\-12\-20+ assets:bank:checking+ expenses:rent $1000++2023\-09\-20 rent+ ; generated\-transaction: \(ti monthly from 2022\-12\-20+ assets:bank:checking+ expenses:rent $1000+.EE+.PP+Here there are no ordinary transactions, so the forecasted transactions+begin on the first occurrence after today\(aqs date.+(You won\(aqt normally use \f[CR]\-\-today\f[R]; it\(aqs just to make+these examples reproducible.)+.SS Forecast reports+Forecast transactions affect all reports, as you would expect.+Eg:+.IP+.EX+$ hledger areg rent \-\-forecast \-\-today=2023/4/21+Transactions in expenses:rent and subaccounts:+2023\-05\-20 rent as:ba:checking $1000 $1000+2023\-06\-20 rent as:ba:checking $1000 $2000+2023\-07\-20 rent as:ba:checking $1000 $3000+2023\-08\-20 rent as:ba:checking $1000 $4000+2023\-09\-20 rent as:ba:checking $1000 $5000+.EE+.IP+.EX+$ hledger bal \-M expenses \-\-forecast \-\-today=2023/4/21+Balance changes in 2023\-05\-01..2023\-09\-30:++ || May Jun Jul Aug Sep +===============++===================================+ expenses:rent || $1000 $1000 $1000 $1000 $1000 +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-++\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ || $1000 $1000 $1000 $1000 $1000 +.EE+.SS Forecast tags+Forecast transactions generated by \-\-forecast have a hidden tag,+\f[CR]_generated\-transaction\f[R].+So if you ever need to match forecast transactions, you could use+\f[CR]tag:_generated\-transaction\f[R] (or just+\f[CR]tag:generated\f[R]) in a query.+.PP+For troubleshooting, you can add the \f[CR]\-\-verbose\-tags\f[R] flag.+Then, visible \f[CR]generated\-transaction\f[R] tags will be added also,+so you can view them with the \f[CR]print\f[R] command.+Their value indicates which periodic rule was responsible.+.SS Forecast period, in detail+Forecast start/end dates are chosen so as to do something useful by+default in almost all situations, while also being flexible.+Here are (with luck) the exact rules, to help with troubleshooting:+.PP+The forecast period starts on:+.IP \(bu 2+the later of+.RS 2+.IP \(bu 2+the start date in the periodic transaction rule+.IP \(bu 2+the start date in \f[CR]\-\-forecast\f[R]\(aqs argument+.RE+.IP \(bu 2+otherwise (if those are not available): the later of+.RS 2+.IP \(bu 2+the report start date specified with+\f[CR]\-b\f[R]/\f[CR]\-p\f[R]/\f[CR]date:\f[R]+.IP \(bu 2+the day after the latest ordinary transaction in the journal+.RE+.IP \(bu 2+otherwise (if none of these are available): today.+.PP+The forecast period ends on:+.IP \(bu 2+the earlier of+.RS 2+.IP \(bu 2+the end date in the periodic transaction rule+.IP \(bu 2+the end date in \f[CR]\-\-forecast\f[R]\(aqs argument+.RE+.IP \(bu 2+otherwise: the report end date specified with+\f[CR]\-e\f[R]/\f[CR]\-p\f[R]/\f[CR]date:\f[R]+.IP \(bu 2+otherwise: 180 days (\(ti6 months) from today.+.SS Forecast troubleshooting+When \-\-forecast is not doing what you expect, one of these tips should+help:+.IP \(bu 2+Remember to use the \f[CR]\-\-forecast\f[R] option.+.IP \(bu 2+Remember to have at least one periodic transaction rule in your journal.+.IP \(bu 2+Test with \f[CR]print \-\-forecast\f[R].+.IP \(bu 2+Check for typos or too\-restrictive start/end dates in your periodic+transaction rule.+.IP \(bu 2+Leave at least 2 spaces between the rule\(aqs period expression and+description fields.+.IP \(bu 2+Check for future\-dated ordinary transactions suppressing forecasted+transactions.+.IP \(bu 2+Try setting explicit report start and/or end dates with \f[CR]\-b\f[R],+\f[CR]\-e\f[R], \f[CR]\-p\f[R] or \f[CR]date:\f[R]+.IP \(bu 2+Try adding the \f[CR]\-E\f[R] flag to encourage display of empty+periods/zero transactions.+.IP \(bu 2+Try setting explicit forecast start and/or end dates with+\f[CR]\-\-forecast=START..END\f[R]+.IP \(bu 2+Consult Forecast period, in detail, above.+.IP \(bu 2+Check inside the engine: add \f[CR]\-\-debug=2\f[R] (eg).+.SH Budgeting+With the balance command\(aqs \f[CR]\-\-budget\f[R] report, each+periodic transaction rule generates recurring budget goals in specified+accounts, and goals and actual performance can be compared.+See the balance command\(aqs doc below.+.PP+You can generate budget goals and forecast transactions at the same+time, from the same or different periodic transaction rules:+\f[CR]hledger bal \-M \-\-budget \-\-forecast ...\f[R]+.PP+See also: Budgeting on hledger.org.+.SH Posting types+hledger detects and tags certain kinds of postings, to help it+understand complex transactions.+Here is quick overview of the posting detection rules.+.PP+By default, these tags are hidden (with a \f[CR]_\f[R] prefix), so they+can be queried but they won\(aqt appear in \f[CR]print\f[R] output.+To also add visible tags, for troubleshooting, use \f[CR]print\f[R]\(aqs+\f[CR]\-\-verbose\-tags\f[R] or \f[CR]\-a/\-\-all\f[R] flags.+.PP+.TS+tab(@);+lw(5.4n) lw(40.2n) lw(24.4n).+T{+Tag+T}@T{+Detected pattern+T}@T{+Effect+T}+_+T{+\f[CR]conversion\-posting\f[R]+T}@T{+A pair of adjacent, single\-commodity, costless postings to+\f[CR]Conversion\f[R]\-type accounts, with a nearby corresponding+costful or potentially corresponding costless posting+T}@T{+Helps transaction balancer infer costs or avoid redundancy in commodity+conversions+T}+T{+\f[CR]cost\-posting\f[R]+T}@T{+A costful posting whose amount and transacted cost correspond to a+conversion postings pair; or a costless posting matching one of the pair+T}@T{+Helps transaction balancer infer costs or avoid redundancy in commodity+conversions+T}+T{+\f[CR]generated\-posting\f[R]+T}@T{+Postings generated at runtime+T}@T{+Helps users understand or find postings added at runtime by hledger+T}+T{+\f[CR]ptype:acquire\f[R]+T}@T{+Positive postings with lot annotations, or in a lotful commodity, with+no matching counterposting (negative, in a liability account: a short+position)+T}@T{+Creates a new lot+T}+T{+\f[CR]ptype:dispose\f[R]+T}@T{+Negative postings with lot annotations, or in a lotful commodity, with+no matching counterposting (positive, in a liability account: covering a+short position)+T}@T{+Selects and reduces existing lots+T}+T{+\f[CR]ptype:transfer\-from\f[R]+T}@T{+The negative posting of a pair of counterpostings, at least one with lot+annotation or a lotful commodity; or a negative lot posting with an+equity counterpart (equity transfer)+T}@T{+Moves lots between accounts, preserving cost basis+T}+T{+\f[CR]ptype:transfer\-to\f[R]+T}@T{+The positive posting of a transfer pair; or a positive lot posting with+an equity counterpart (equity transfer, e.g.+opening balances)+T}@T{+As above+T}+T{+\f[CR]ptype:gain\f[R]+T}@T{+In a disposal: a user\-written posting to a \f[CR]Gain\f[R]\-type+account (or, failing that, a non\-asset/liability/equity posting without+which the entry balances); or the realised\-gain posting hledger+generates+T}@T{+Records the realised capital gain/loss; set aside by the transaction+balancer, so the disposal balances at cost basis+T}+.TE+.SH PART 5: MORE ABOUT THE COMMAND LINE+.SH Output+.SS Output destination+hledger commands send their output to the terminal by default.+You can of course redirect this, eg into a file, using standard shell+syntax:+.IP+.EX+$ hledger print > foo.txt+.EE+.PP+Some commands (print, register, stats, the balance commands) also+provide the \f[CR]\-o\f[R]/\f[CR]\-\-output\-file\f[R] option, which+does the same thing without needing the shell.+Eg:+.IP+.EX+$ hledger print \-o foo.txt+$ hledger print \-o \- # write to stdout (the default)+.EE+.PP+These commands (except stats) also provide \f[CR]\-\-view\f[R], which+writes the output to a file and opens it in your system\(aqs default+viewer for that kind of file, eg a web browser for HTML.+The file is the one given by \f[CR]\-o\f[R], or else \f[CR]view.FMT\f[R]+in hledger\(aqs cache directory (\f[CR]$XDG_CACHE_HOME/hledger/\f[R] or+\f[CR]\(ti/.cache/hledger/\f[R], or+\f[CR]%LOCALAPPDATA%\(rshledger\(rs\f[R] on Windows), replaced each+time, and readable only by you (on unix systems).+hledger shows the file\(aqs path; if the report is sensitive, you can+delete the file when you\(aqre done with it, or use \f[CR]\-o\f[R] to+save it somewhere else.+The output format is HTML unless you choose another, with \f[CR]\-O\f[R]+or the \f[CR]\-o\f[R] file\(aqs extension.+Eg:+.IP+.EX+$ hledger is \-M \-\-chart \-\-view # see an income statement chart and table in a web browser+$ hledger reg \-O csv \-\-view # or a register in a spreadsheet+.EE+.PP+To view several reports at once, on one page, use \f[CR]run\f[R] with+\f[CR]\-\-view\f[R]:+.IP+.EX+$ hledger run \-\-view \-\- is \-M \-\-chart \-\- bs \-Q \-\-chart \-\- reg expenses \-p thismonth+.EE+.SS Output format+Some commands offer other kinds of output, not just text on the+terminal.+Here are those commands and the formats currently supported:+.PP+.TS+tab(@);+lw(15.6n) lw(3.9n) lw(7.0n) lw(4.7n) lw(7.0n) lw(4.7n) lw(6.2n) lw(8.6n) lw(3.9n) lw(4.7n) lw(3.9n).+T{+command+T}@T{+txt+T}@T{+journal+T}@T{+html+T}@T{+csv/tsv+T}@T{+fods+T}@T{+ledger+T}@T{+beancount+T}@T{+sql+T}@T{+json+T}@T{+svg+T}+_+T{+aregister+T}@T{+Y+T}@T{+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+T}@T{+T}@T{+T}@T{+Y+T}@T{+Y+T}+T{+balance+T}@T{+Y+T}@T{+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+T}@T{+T}@T{+T}@T{+Y+T}@T{+Y+T}+T{+balancesheet+T}@T{+Y+T}@T{+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+T}@T{+T}@T{+T}@T{+Y+T}@T{+Y+T}+T{+balancesheetequity+T}@T{+Y+T}@T{+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+T}@T{+T}@T{+T}@T{+Y+T}@T{+Y+T}+T{+cashflow+T}@T{+Y+T}@T{+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+T}@T{+T}@T{+T}@T{+Y+T}@T{+Y+T}+T{+holdings+T}@T{+Y+T}@T{+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+T}@T{+T}@T{+T}@T{+Y+T}@T{+T}+T{+incomestatement+T}@T{+Y+T}@T{+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+T}@T{+T}@T{+T}@T{+Y+T}@T{+Y+T}+T{+print+T}@T{+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+T}+T{+register+T}@T{+Y+T}@T{+T}@T{+Y+T}@T{+Y+T}@T{+Y+T}@T{+T}@T{+T}@T{+T}@T{+Y+T}@T{+Y+T}+.TE+.PP+You can also see which output formats a command supports by running+\f[CR]hledger CMD \-h\f[R] and looking for the+\f[CR]\-O\f[R]/\f[CR]\-\-output\-format=FMT\f[R] option,+.PP+You can select the output format by using that option:+.IP+.EX+$ hledger print \-O csv # print CSV to standard output+.EE+.PP+or by choosing a suitable filename extension with the+\f[CR]\-o\f[R]/\f[CR]\-\-output\-file=FILE.FMT\f[R] option:+.IP+.EX+$ hledger balancesheet \-o foo.csv # write CSV to foo.csv+.EE+.PP+The \f[CR]\-O\f[R] option can be combined with \f[CR]\-o\f[R] to+override the file extension if needed:+.IP+.EX+$ hledger balancesheet \-o foo.txt \-O csv # write CSV to foo.txt+.EE+.PP+Here are some notes about the various output formats.+.SS Text output+This is the default: human readable, plain text report output, suitable+for viewing with a monospace font in a terminal.+If your data contains unicode or wide characters, you\(aqll need a+terminal and font that render those correctly.+(This can be challenging on MS Windows.)+.PP+Some reports (\f[CR]register\f[R], \f[CR]aregister\f[R]) will normally+use the full window width.+If this isn\(aqt working or you want to override it, you can use the+\f[CR]\-w\f[R]/\f[CR]\-\-width\f[R] option.+.PP+Balance reports (\f[CR]balance\f[R], \f[CR]balancesheet\f[R],+\f[CR]incomestatement\f[R]...)+use whatever width they need.+Multi\-period multi\-currency reports can often be wider than the+window.+Besides using a pager, helpful techniques for this situation include+\f[CR]\-\-layout=bare\f[R], \f[CR]\-X COMM\f[R], \f[CR]cur:\f[R],+\f[CR]\-\-transpose\f[R], \f[CR]\-\-tree\f[R], \f[CR]\-\-depth\f[R],+\f[CR]\-\-drop\f[R], switching to html output, etc.+.PP+The display style of amounts (symbol placement, decimal and digit group+marks, number of decimal digits) is inferred per commodity, and can be+overridden with \f[CR]\-c/\-\-commodity\-style\f[R]; see Amount+formatting.+.SS Box\-drawing characters+hledger draws simple table borders by default, to minimise the risk of+display problems caused by a terminal/font not supporting box\-drawing+characters.+.PP+But your terminal and font probably do support them, so we recommend+using the \f[CR]\-\-pretty\f[R] flag to show prettier tables in the+terminal.+This is a good flag to add to your hledger config file.+.SS Colour+hledger tries to automatically detect ANSI colour and text styling+support and use it when appropriate.+(Currently, it is used rather minimally: some reports show negative+numbers in red, and help output uses bold text for emphasis.)+Colour is not used when the \f[CR]TERM\f[R] environment variable is+\f[CR]dumb\f[R], or \f[CR]NO_COLOR\f[R] is set, or output is not going+to a colour\-capable terminal.+.PP+You can override this by setting the \f[CR]NO_COLOR\f[R] environment+variable to disable it, or by using the \f[CR]\-\-color/\-\-colour\f[R]+option, perhaps in your config file, with a \f[CR]y\f[R]/\f[CR]yes\f[R]+or \f[CR]n\f[R]/\f[CR]no\f[R] value to force it on or off.+.SS Paging+In unix\-like environments, when displaying large output (in any output+format) in the terminal, hledger tries to use a pager when appropriate.+(You can disable this with the \f[CR]\-\-pager=no\f[R] option, perhaps+in your config file.)+.PP+The pager shows one page of text at a time, and lets you scroll around+to see more.+While it is active, usually \f[CR]SPACE\f[R] shows the next page,+\f[CR]h\f[R] shows help, and \f[CR]q\f[R] quits.+The home/end/page up/page down/cursor keys, and mouse scrolling, may+also work.+.PP+hledger will use the pager specified by the \f[CR]PAGER\f[R] environment+variable, otherwise \f[CR]less\f[R] if available, otherwise+\f[CR]more\f[R] if available.+(With one exception: \f[CR]hledger help \-p TOPIC\f[R] will always use+\f[CR]less\f[R], so that it can scroll to the topic.)+.PP+The pager is expected to display hledger\(aqs ANSI colour and text+styling.+If you see junk characters, you might need to configure your pager to+handle ANSI codes.+Or you could disable colour as described above.+.PP+If you are using the \f[CR]less\f[R] pager, hledger tries to provide a+consistently pleasant experience by running it with some extra options+added to your \f[CR]LESS\f[R] environment variable:+.PP+\-\-chop\-long\-lines \-\-hilite\-unread \-\-ignore\-case \-\-no\-init+\-\-quit\-if\-one\-screen \-\-shift=8 \-\-squeeze\-blank\-lines+\-\-use\-backslash+.PP+and when colour output is enabled:+.PP+\-\-RAW\-CONTROL\-CHARS+.PP+You can prevent this by setting your preferred options in the+\f[CR]HLEDGER_LESS\f[R] variable, which will be used instead of+\f[CR]LESS\f[R].+.SS HTML output+HTML output has some default styling built in; eg, it prevents wrapping+within dates and individual commodity amounts.+It can be customised (or overridden) by an optional+\f[CR]hledger.css\f[R] file in the same directory (there is a sample in+the hledger repo).+.PP+With \f[CR]\-\-chart\f[R], commands that can show charts show one (as+inline SVG), with the text report collapsed below it (see Balance+charts).+.PP+HTML output will be a HTML fragment, not a complete HTML document.+It has a newline after each table row, for readability.+Like other hledger output, for non\-ascii characters it will use the+system locale\(aqs text encoding (see Text encoding).+.SS CSV / TSV output+In CSV or TSV output, digit group marks (such as thousands separators)+are disabled automatically.+.SS FODS output+FODS is the OpenDocument Spreadsheet format as plain XML, as read by+LibreOffice and OpenOffice.+For those spreadsheet applications it is better than CSV.+It works across locales: decimal point or comma, and the character+encoding is stored in the XML header, so non\-ascii text is safe.+It supports fixed header rows and columns, cell types (string, number,+date), styles (bold) and borders.+And it keeps number and currency separate, so amounts show their+currency but remain numbers usable in formulas.+You can still extract CSV from FODS/ODS if needed, with utilities like+\f[CR]libreoffice \-\-headless\f[R] or ods2csv.+.PP+ODS supports only the locale\(aqs thousands separator as a digit group+mark, so FODS output enables thousands separators if your commodity+style has any digit groups.+.SS Ledger output+This is a Ledger\-specific journal format supported by the+\f[CR]print\f[R] command.+It is currently identical to hledger\(aqs default \f[CR]print\f[R]+output except that cost basis annotations will use Ledger\(aqs syntax,+(\f[CR]{COST} [DATE] (NOTE)\f[R]), not hledger\(aqs+(\f[CR]{DATE, \(dqLABEL\(dq, COST}\f[R]).+With \f[CR]print \-\-export\f[R], directives and comments are also+reproduced, and directives which Ledger does not support are commented+out.+.SS Beancount output+This is Beancount\(aqs journal format, supported by the \f[CR]print\f[R]+command.+You can use this to export your hledger data to Beancount, eg to use the+Fava web app.+.PP+hledger will try to adjust your data to suit Beancount, automatically.+By default only transactions are converted; with+\f[CR]print \-\-export\f[R], the options and \f[CR]commodity\f[R],+\f[CR]open\f[R] and \f[CR]price\f[R] directives Beancount needs are+generated too, and top\-level comments are converted, so the output can+be read by Beancount directly.+Be cautious and check the conversion until you are confident it is good.+If you plan to export to Beancount often, you may want to follow its+conventions, for a cleaner conversion:+.IP \(bu 2+use Beancount\-friendly account names+.IP \(bu 2+use currency codes instead of currency symbols+.IP \(bu 2+use cost notation instead of equity conversion postings+.IP \(bu 2+avoid virtual postings, balance assignments, and secondary dates.+.PP+There is one big adjustment: for Beancount, the top level account names+must be \f[CR]Assets\f[R], \f[CR]Liabilities\f[R], \f[CR]Equity\f[R],+\f[CR]Income\f[R], and/or \f[CR]Expenses\f[R].+A top level hledger account named \f[CR]revenue\f[R] or+\f[CR]revenues\f[R] (case insensitive) will be converted to+\f[CR]Income\f[R].+Any other top level account whose account type is known (declared or+inferred) will have the corresponding Beancount top level account+prepended; eg with \f[CR]account bonds ; type:A\f[R],+\f[CR]bonds:treasury\f[R] becomes \f[CR]Assets:Bonds:Treasury\f[R].+Otherwise, you should use \f[CR]\-\-alias\f[R] (see \f[CR]\-\-alias\f[R]+option, or this hledger2beancount.conf file).+.PP+Other adjustments hledger makes:+.IP \(bu 2+\f[B]Account names:\f[R] aside from the top\-level names, hledger makes+valid Beancount account names by capitalising each part, replacing+spaces and underscores with \f[CR]\-\f[R], replacing other unsupported+characters with \f[CR]C<HEXBYTES>\f[R], prepending \f[CR]A\f[R] to parts+which don\(aqt begin with a letter or digit, and appending \f[CR]:A\f[R]+to account names which have only one part.+.IP \(bu 2+\f[B]Commodity names:\f[R] hledger makes valid Beancount+commodity/currency names, which must be 2\-24 uppercase letters, digits,+or \f[CR]\(aq\f[R], \f[CR].\f[R], \f[CR]_\f[R], \f[CR]\-\f[R], beginning+with a letter and ending with a letter or digit.+Known currency symbols become ISO 4217 currency codes; otherwise letters+are capitalised, spaces become \f[CR]\-\f[R], other unsupported+characters become \f[CR]C<HEXBYTES>\f[R], and \f[CR]C\f[R] is prepended+or appended if needed.+One\-letter symbols are doubled, and the no\-symbol commodity becomes+\f[CR]CC\f[R].+(hledger tries to keep your commodities distinct, but collisions are+possible with short symbols like \f[CR]CC\f[R], \f[CR]C\f[R] and+no\-symbol, which are distinct in hledger but all become \f[CR]CC\f[R]+in Beancount.)+.IP \(bu 2+\f[B]Balance assignments\f[R] are not supported by Beancount, so they+are converted to explicit amounts.+.IP \(bu 2+\f[B]Virtual postings\f[R] are not allowed by Beancount, so any virtual+postings are omitted.+.IP \(bu 2+\f[B]Tags\f[R] become Beancount metadata (except tags whose name begins+with \f[CR]_\f[R]).+Metadata names are adjusted to be Beancount\-compatible: beginning with+a lowercase letter, at least two characters long, with unsupported+characters encoded; values use Beancount\(aqs string type.+A tag repeated with multiple values (eg an account with both+\f[CR]type:Asset\f[R] and \f[CR]type:Cash\f[R]) becomes one metadata+entry with the values comma separated:+\f[CR]type: \(dqAsset, Cash\(dq\f[R].+.IP \(bu 2+\f[B]Costs:\f[R] Beancount doesn\(aqt allow redundant costs and+conversion postings as hledger does; if you have any, the conversion+postings are omitted.+Currently at most one cost + conversion postings group per transaction+is supported.+.IP \(bu 2+\f[B]Directives:\f[R] with \f[CR]print \-\-export\f[R], hledger+generates a \f[CR]commodity\f[R] directive for each declared commodity,+and an \f[CR]open\f[R] directive for each declared or used account,+dated on the account\(aqs earliest posting (or the earliest transaction+date).+Account and commodity tags become metadata on these directives, and an+account\(aqs \f[CR]lots:\f[R] tag becomes its Beancount booking method.+Other hledger directives have no Beancount equivalent and are dropped.+.IP \(bu 2+\f[B]Tolerance:\f[R] with \f[CR]print \-\-export\f[R], a sample+\f[CR]inferred_tolerance_default\f[R] option is provided, commented out.+If Beancount complains that transactions aren\(aqt balanced, this is an+easy workaround.+.IP \(bu 2+\f[B]Operating currency:\f[R] declaring one or more improves Beancount+and Fava reports.+With \f[CR]print \-\-export\f[R], hledger declares each currency used in+cost amounts as an operating currency.+If needed, replace these with your own declaration, like+\f[CR]option \(dqoperating_currency\(dq \(dqUSD\(dq\f[R].+.SS SQL output+SQL output is expected to work at least with SQLite, MySQL and Postgres.+.PP+The SQL statements are expected to be executed in the empty database.+If you already have tables created via SQL output of hledger, you would+probably want to either clear data from these (via \f[CR]delete\f[R] or+\f[CR]truncate\f[R] SQL statements) or \f[CR]drop\f[R] the tables+completely before import; otherwise your postings would be duplicated.+.PP+For SQLite, it is more useful if you modify the generated \f[CR]id\f[R]+field to be a PRIMARY KEY.+Eg:+.IP+.EX+$ hledger print \-O sql | sed \(aqs/id serial/id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL/g\(aq | ...+.EE+.SS JSON output+Our JSON is rather large and verbose, since it is a faithful+representation of hledger\(aqs internal data types.+To understand its structure, read the Haskell type definitions, which+are mostly in+https://github.com/hledgerorg/hledger/blob/main/hledger\-lib/Hledger/Data/Types.hs.+hledger\-web\(aqs OpenAPI specification may also be relevant.+.PP+hledger stores numbers with sometimes up to 255 significant digits.+This is too many digits for most JSON consumers, so in JSON output we+round numbers to at most 10 decimal places.+(We don\(aqt limit the number of integer digits.)+Related: #1195+.SS SVG output+SVG output shows a chart of the report, rather than the report\(aqs+table (as the \f[CR]\-\-chart\f[R] flag does with text output; see+Balance charts).+It is a self\-contained image file, viewable in web browsers and many+image viewers.+It has a light and a dark colour scheme, chosen by the viewer\(aqs+preference, and tooltips showing each bar\(aqs or point\(aqs values.+Currently the \f[CR]aregister\f[R], \f[CR]balance\f[R],+\f[CR]balancesheet\f[R], \f[CR]balancesheetequity\f[R],+\f[CR]cashflow\f[R], \f[CR]incomestatement\f[R] and \f[CR]register\f[R]+commands can produce it.+Eg:+.IP+.EX+$ hledger bal \-M expenses \-o expenses.svg+.EE+.SS Debug output+We intend hledger to be relatively easy to troubleshoot, introspect and+develop.+You can add \f[CR]\-\-debug[=N]\f[R] to any hledger command line to see+additional debug output.+N ranges from 1 (least output, the default) to 9 (maximum output).+Typically you would start with 1 and increase until you are seeing+enough.+At level 1 or higher, the output includes timing lines, showing the run+time and memory allocation of each phase of hledger\(aqs work: reading+and parsing data, each stage of journal finalising, and running the+command.+These can show where the time goes when processing a large journal.+Debug output goes to stderr, and is not affected by+\f[CR]\-o/\-\-output\-file\f[R] (unless you redirect stderr to stdout,+eg: \f[CR]2>&1\f[R]).+It will be interleaved with normal output, which can help reveal when+parts of the code are evaluated.+To capture debug output in a log file instead, you can usually redirect+stderr, eg:+.IP+.EX+hledger bal \-\-debug=3 2>hledger.log+.EE+.PP+(This option doesn\(aqt work in a config file yet.)+.SS Built\-in tests+hledger\(aqs unit tests are built in to the executable, and+\f[CR]\-\-test\f[R] runs them, printing the results and exiting with a+non\-zero code if any fail.+\f[CR]\-\-test=PATTERN\f[R] runs just the tests whose names contain+PATTERN (it can also be a tasty pattern).+Eg:+.IP+.EX+$ hledger \-\-test # run all unit tests+$ hledger \-\-test=balance # run tests with \(dqbalance\(dq in their name+.EE+.PP+This can be a sanity check of an unusual hledger build; failures are+unlikely, but if you see one, please report it as a bug.+(hledger\-web also has a \f[CR]\-\-test\f[R] flag, which runs its own+tests.)+.SH Charts+hledger can show many reports as a chart: add \f[CR]\-\-chart\f[R] to a+\f[CR]balance\f[R], \f[CR]balancesheet\f[R],+\f[CR]balancesheetequity\f[R], \f[CR]cashflow\f[R],+\f[CR]incomestatement\f[R], \f[CR]aregister\f[R], \f[CR]register\f[R] or+\f[CR]holdings\f[R] report.+(The \f[CR]activity\f[R] command always shows one.)+A suitable kind of chart is chosen for the report: eg stacked bars per+period for balance changes, lines for balances over time, or a bar per+account for a single period.+In the terminal the chart is drawn with text characters, filling the+terminal\(aqs width (or the width set by \f[CR]\-w\f[R]):+.IP+.EX+$ hledger bal \-Q expenses income \-\-chart \-w 50+Balance changes in 2008:++░ expenses:food ▒ expenses:supplies+█ income:gifts ▓ income:salary++2008Q1 $\-1 ▓▓▓▓▓▓▓▓▓▓▓▓│+2008Q2 $1 ████████████│░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒+2008Q3 0 │+2008Q4 0 │+.EE+.PP+With SVG output (eg \f[CR]\-o chart.svg\f[R]) it is a graphical chart;+with HTML output it is shown with the report\(aqs table collapsed below+it; and with CSV, TSV or JSON output you get the chart\(aqs data.+To see a graphical chart quickly, add \f[CR]\-\-view\f[R], eg+\f[CR]hledger is \-M \-\-chart \-\-view\f[R].+\f[CR]\-\-chart\f[R] also accepts a chart kind, \f[CR]net\f[R] (to draw+the net total, which charts leave out by default), and a fixed scale, eg+to compare charts.+For the details, see Balance charts, aregister, Register charts and+Holdings charts.+.SH Command line tips+Here are some tips for using hledger at the command line; feel free to+skip these until you need them.+.SS Special characters+In commands you type at the command line, certain characters have+special meaning and sometimes need to be \(dqescaped\(dq or+\(dqquoted\(dq, by prefixing backslashes or enclosing in quotes.+.PP+If you are able to minimise the use of special characters in your data,+you won\(aqt have to deal with this as much.+For example, you could use hyphen \f[CR]\-\f[R] or underscore+\f[CR]_\f[R] instead of spaces in account names, and you could use the+\f[CR]USD\f[R] currency code instead of the \f[CR]$\f[R] currency symbol+in amounts.+.PP+But if you prefer to use spaced account names and \f[CR]$\f[R], it\(aqs+fine.+Just be aware of this topic so you can check this doc when needed.+(These examples are mostly tested on unix; some details might need to be+adapted if you\(aqre on Windows.)+.SS Escaping shell special characters+These are some characters which may have special meaning to your shell+(the program which interprets command lines):+.IP \(bu 2+SPACE, \f[CR]<\f[R], \f[CR]>\f[R], \f[CR](\f[R], \f[CR])\f[R],+\f[CR]|\f[R], \f[CR]\(rs\f[R], \f[CR]%\f[R]+.IP \(bu 2+\f[CR]$\f[R] if followed by a word character+.PP+So for example, to match an account name containing spaces, like+\(dqcredit card\(dq, don\(aqt write:+.IP+.EX+$ hledger register credit card+.EE+.PP+Instead, enclose the name in single quotes:+.IP+.EX+$ hledger register \(aqcredit card\(aq+.EE+.PP+On unix or in Windows powershell, if you use double quotes your shell+will silently treat \f[CR]$\f[R] as variable interpolation.+So you should probably avoid double quotes, unless you want that+behaviour, eg in a script:+.IP+.EX+$ hledger register \(dqassets:$SOMEACCT\(dq+.EE+.PP+But in an older Windows CMD.EXE window, you must use double quotes:+.IP+.EX+C:\(rsUsers\(rsMe> hledger register \(dqcredit card\(dq+.EE+.PP+On unix or in Windows powershell, as an alternative to quotes you can+write a backslash before each special character:+.IP+.EX+$ hledger register credit\(rs card+.EE+.PP+Finally, since hledger\(aqs query arguments are regular expressions+(described below), you could also fill that gap with \f[CR].\f[R] which+matches any character:+.IP+.EX+$ hledger register credit.card+.EE+.SS Escaping regular expression special characters+Some characters also have special meaning in regular expressions, which+hledger\(aqs arguments often are.+Those include:+.IP \(bu 2+\f[CR].\f[R], \f[CR]\(ha\f[R], \f[CR]$\f[R], \f[CR][\f[R], \f[CR]]\f[R],+\f[CR](\f[R], \f[CR])\f[R], \f[CR]|\f[R], \f[CR]\(rs\f[R]+.PP+To escape one of these, write \f[CR]\(rs\f[R] before it.+But note this is in addition to the shell escaping above.+So for characters which are special to both shell and regular+expressions, like \f[CR]\(rs\f[R] and \f[CR]$\f[R], you will sometimes+need two levels of escaping.+.PP+For example, a balance report that uses a \f[CR]cur:\f[R] query+restricting it to just the $ currency, should be written like this:+.IP+.EX+$ hledger balance cur:\(rs\(rs$+.EE+.PP+Explanation:+.IP "1." 3+Add a backslash \f[CR]\(rs\f[R] before the dollar sign \f[CR]$\f[R] to+protect it from regular expressions (so it will be matched literally+with no special meaning).+.IP "2." 3+Add another backslash before that backslash, to protect it from the+shell (so the shell won\(aqt consume it).+.IP "3." 3+\f[CR]$\f[R] doesn\(aqt need to be protected from the shell in this+case, because it\(aqs not followed by a word character; but it would be+harmless to do so.+.PP+But here\(aqs another way to write that, which tends to be easier: add+backslashes to escape from regular expressions, then enclose with quotes+to escape from the shell:+.IP+.EX+$ hledger balance cur:\(aq\(rs$\(aq+.EE+.SS Escaping in other situations+hledger options and arguments are sometimes used in places other than+the command line, where the escaping/quoting rules are different.+For example, backslash\-quoting may not be available.+Here\(aqs a quick reference:+.PP+.TS+tab(@);+lw(17.5n) lw(52.5n).+T{+In unix shell+T}@T{+Use single quotes and/or backslash (or double quotes for variable+interpolation)+T}+T{+In Windows \f[CR]powershell\f[R]+T}@T{+Use single quotes (or double quotes for variable interpolation)+T}+T{+In Windows \f[CR]cmd\f[R]+T}@T{+Use double quotes+T}+T{+In hledger\-ui\(aqs filter prompt+T}@T{+Use single or double quotes+T}+T{+In hledger\-web\(aqs search form+T}@T{+Use single or double quotes+T}+T{+In an argument file+T}@T{+Don\(aqt use spaces, don\(aqt shell\-escape, do regex\-escape, write one+argument/option per line+T}+T{+In a config file+T}@T{+Use single or double quotes, enclosing all or part of an argument+(\f[CR]\(aqdesc:a b\(aq\f[R] or \f[CR]desc:\(aqa b\(aq\f[R], as in the+unix shell)+T}+T{+In \f[CR]repl\f[R] or a \f[CR]run\f[R] script+T}@T{+Use single or double quotes, enclosing all or part of an argument+T}+T{+In \f[CR]ghci\f[R] (the Haskell REPL)+T}@T{+Use double quotes, and enclose the whole argument+T}+.TE+.SS Unicode characters+hledger is expected to handle non\-ascii characters correctly:+.IP \(bu 2+they should be parsed correctly in input files and on the command line,+by all hledger tools (add, iadd, hledger\-web\(aqs search/add/edit+forms, etc.)+.IP \(bu 2+they should be displayed correctly by all hledger tools, and on\-screen+alignment should be preserved.+.PP+This requires a well\-configured environment.+Here are some tips:+.IP \(bu 2+A system locale must be configured, which can decode the characters+being used.+This is essential \- see Text encoding and Install: Text encoding.+.IP \(bu 2+Your terminal software (eg Terminal.app, iTerm, CMD.exe, xterm..)+must support unicode.+On Windows, you may need to use Windows Terminal.+.IP \(bu 2+The terminal must be using a font which includes the required unicode+glyphs.+.IP \(bu 2+The terminal should be configured to display wide characters as double+width (for report alignment).+.IP \(bu 2+On Windows, for best results you should run hledger in the same kind of+environment in which it was built.+Eg hledger built in the standard CMD.EXE environment (like the binaries+on our download page) might show display problems when run in a cygwin+or msys terminal, and vice versa.+(See eg #961).+.SS Regular expressions+A regular expression (regexp) is a small piece of text where certain+characters (like \f[CR].\f[R], \f[CR]\(ha\f[R], \f[CR]$\f[R],+\f[CR]+\f[R], \f[CR]*\f[R], \f[CR]()\f[R], \f[CR]|\f[R], \f[CR][]\f[R],+\f[CR]\(rs\f[R]) have special meanings, forming a tiny language for+matching text precisely \- very useful in hledger and elsewhere.+To learn all about them, visit regular\-expressions.info.+.PP+hledger supports regexps whenever you are entering a pattern to match+something, eg in query arguments, account aliases, CSV if rules,+hledger\-web\(aqs search form, hledger\-ui\(aqs \f[CR]/\f[R] search,+etc.+You may need to wrap them in quotes, especially at the command line (see+Special characters above).+Here are some examples:+.PP+Account name queries (quoted for command line use):+.IP+.EX+Regular expression: Matches:+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+bank assets:bank, assets:bank:savings, expenses:art:banksy, ...+:bank assets:bank:savings, expenses:art:banksy+:bank: assets:bank:savings+\(aq\(habank\(aq none of those ( \(ha matches beginning of text )+\(aqbank$\(aq assets:bank ( $ matches end of text )+\(aqbig \(rs$ bank\(aq big $ bank ( \(rs disables following character\(aqs special meaning )+\(aq\(rsbbank\(rsb\(aq assets:bank, assets:bank:savings ( \(rsb matches word boundaries )+\(aq(sav|check)ing\(aq saving or checking ( (|) matches either alternative )+\(aqsaving|checking\(aq saving or checking ( outer parentheses are not needed )+\(aqsavings?\(aq saving or savings ( ? matches 0 or 1 of the preceding thing )+\(aqmy +bank\(aq my bank, my bank, ... ( + matches 1 or more of the preceding thing )+\(aqmy *bank\(aq mybank, my bank, my bank, ... ( * matches 0 or more of the preceding thing )+\(aqb.nk\(aq bank, bonk, b nk, ... ( . matches any character )+.EE+.PP+Some other queries:+.IP+.EX+desc:\(aqamazon|amzn|audible\(aq Amazon transactions+cur:EUR amounts with commodity symbol EUR+cur:\(rs\(rs$ amounts with commodity symbol $+cur:....? amounts with 3\- or 4\-character symbols+tag:.=202[1\-3] things with any tag whose value contains 2021, 2022 or 2023+.EE+.PP+Account name aliases: accept \f[CR].\f[R] instead of \f[CR]:\f[R] as+account separator:+.IP+.EX+alias /\(rs./=: replaces all periods in account names with colons+.EE+.PP+Show multiple top\-level accounts combined as one:+.IP+.EX+\-\-alias=\(aq/\(ha[\(ha:]+/=combined\(aq ( [\(ha:] matches any character other than : )+.EE+.PP+Show accounts with the second\-level part removed:+.IP+.EX+\-\-alias \(aq/\(ha([\(ha:]+):[\(ha:]+/ = \(rs1\(aq+ match a top\-level account and a second\-level account+ and replace those with just the top\-level account+ ( \(rs1 in the replacement text means \(dqwhatever was matched+ by the first parenthesised part of the regexp\(dq+.EE+.PP+CSV rules: match CSV records containing dining\-related MCC codes:+.IP+.EX+if \(rs?MCC581[124]+.EE+.PP+Match CSV records with a specific amount around the end/start of month:+.IP+.EX+if %amount \(rsb3\(rs.99+& %date (29|30|31|01|02|03)$+.EE+.SS hledger\(aqs regular expressions+hledger\(aqs regular expressions come from the regex\-tdfa library.+If they\(aqre not doing what you expect, it\(aqs important to know+exactly what they support:+.IP "1." 3+they are case insensitive+.IP "2." 3+they are infix matching (they do not need to match the entire thing+being matched)+.IP "3." 3+they are POSIX ERE (extended regular expressions)+.IP "4." 3+they also support GNU word boundaries (\f[CR]\(rsb\f[R],+\f[CR]\(rsB\f[R], \f[CR]\(rs<\f[R], \f[CR]\(rs>\f[R])+.IP "5." 3+backreferences are supported when doing text replacement in account+aliases or CSV rules, where backreferences can be used in the+replacement string to reference capturing groups in the search regexp.+Otherwise, if you write \f[CR]\(rs1\f[R], it will match the digit+\f[CR]1\f[R].+.IP "6." 3+they do not support lazy quantifiers (\f[CR]*?\f[R]), mode modifiers+(\f[CR](?s)\f[R]), character classes (\f[CR]\(rsw\f[R],+\f[CR]\(rsd\f[R]), or anything else not mentioned above.+.IP "7." 3+they may not (I\(aqm guessing not) properly support right\-to\-left or+bidirectional text.+.PP+Some things to note:+.IP \(bu 2+In the \f[CR]alias\f[R] directive and \f[CR]\-\-alias\f[R] option,+regular expressions must be enclosed in forward slashes+(\f[CR]/REGEX/\f[R]).+Elsewhere in hledger, these are not required.+.IP \(bu 2+In queries, to match a regular expression metacharacter like+\f[CR]$\f[R] as a literal character, prepend a backslash.+Eg to search for amounts with the dollar sign in hledger\-web, write+\f[CR]cur:\(rs$\f[R].+.IP \(bu 2+On the command line, some metacharacters like \f[CR]$\f[R] have a+special meaning to the shell and so must be escaped at least once more.+See Special characters.+.SS Argument files+You can save a set of command line options and arguments in a file, and+then use them by writing \f[CR]\(atFILE.args\f[R] as a hledger command+argument.+The \f[CR].args\f[R] file extension is conventional, but not required.+In an argument file,+.IP \(bu 2+Each line can contain one argument, flag, or option.+.IP \(bu 2+Blank lines or lines beginning with \f[CR]#\f[R] are ignored.+.IP \(bu 2+An option\(aqs flag and value should be joined by \f[CR]=\f[R].+.IP \(bu 2+An option value or an argument may contain spaces.+Don\(aqt use single or double quotes.+.IP \(bu 2+And generally, use one less level of quoting/escaping than at the+command line.+Eg \f[CR]cur:\(rs$\f[R], not \f[CR]cur:\(rs\(rs$\f[R] as on the command+line.+.PP+For example:+.IP+.EX+# cash.args++assets:cash+assets:charles schwab:sweep+cur:\(rs$+\-c=$1.+.EE+.IP+.EX+$ hledger bal \(atcash.args+.EE+.SS Shell completions+If you use the bash, zsh or fish shells, you can optionally set up+context\-sensitive autocompletion for hledger command lines.+Try pressing \f[CR]hledger<SPACE><TAB><TAB>\f[R] (should list all+hledger commands) or \f[CR]hledger reg acct:<TAB><TAB>\f[R] (should list+your top\-level account names).+If completions aren\(aqt working, or for more details, see Install >+Shell completions.+.SH PART 6: COMMON TASKS+For a gentle, step by step introduction to hledger \- installing,+starting a journal, recording transactions, and running the main reports+\- see hledger by example on the website.+For a faster tour, see the 5 minute quick start.+Here are a few more tasks which aren\(aqt covered there.+.SH Setting LEDGER_FILE+hledger looks for your accounting data in a journal file,+\f[CR]$HOME/.hledger.journal\f[R] by default.+You can override this by setting the \f[CR]LEDGER_FILE\f[R] environment+variable (see Environment), eg to \f[CR]\(ti/finance/main.journal\f[R].+Here\(aqs how to do that on different systems:+.SS Set LEDGER_FILE on unix+It depends on your shell, but running these commands in the terminal+will work for many people; adapt if needed:+.IP+.EX+$ echo \(aqexport LEDGER_FILE=\(ti/finance/main.journal\(aq >> \(ti/.profile+$ source \(ti/.profile+.EE+.PP+When correctly configured:+.IP \(bu 2+\f[CR]env | grep LEDGER_FILE\f[R] will show your new setting+.IP \(bu 2+and so should \f[CR]hledger setup\f[R] and \f[CR]hledger files\f[R].+.SS Set LEDGER_FILE on mac+In a terminal window, follow the unix procedure above.+.PP+Note GUI applications started from the Dock or Spotlight, such as a GUI+Emacs, don\(aqt see variables set in your shell profile.+If needed, you can set the variable for them too, until the next reboot,+with \f[CR]launchctl setenv LEDGER_FILE \(ti/finance/main.journal\f[R]+(then restart the application).+.SS Set LEDGER_FILE on Windows+It can be easier to create a default file at+\f[CR]C:\(rsUsers\(rsUSER\(rs.hledger.journal\f[R], and have it include+your other files.+See I\(aqm on Windows, how do I keep my files in+\f[CR]AppData\(rsRoaming\f[R] ?+.PP+Otherwise: using the gui is easiest:+.IP "1." 3+In task bar, search for \f[CR]environment variables\f[R], and choose+\(dqEdit environment variables for your account\(dq.+.IP "2." 3+Create or change a \f[CR]LEDGER_FILE\f[R] setting in the User variables+pane.+A typical value would be+\f[CR]C:\(rsUsers\(rsUSER\(rsfinance\(rsmain.journal\f[R].+.IP "3." 3+Click OK to complete the change.+.IP "4." 3+And open a new powershell window.+(Existing windows won\(aqt see the change.)+.PP+Or at the command line, you can do it this way:+.IP "1." 3+In a powershell window, run+\f[CR][Environment]::SetEnvironmentVariable(\(dqLEDGER_FILE\(dq, \(dqC:\(rsUser\(rsUSER\(rsfinance\(rsmain.journal\(dq, [System.EnvironmentVariableTarget]::User)\f[R]+.IP "2." 3+And open a new powershell window.+(Existing windows won\(aqt see the change.)+.PP+Other methods you may find online are often unreliable: they may not+persist, may not affect the current window, or may need administrator+rights or a newer powershell.+If you still have trouble, see eg Setting Windows PowerShell environment+variables or Adding path permanently to windows using powershell+doesn\(aqt appear to work.+.PP+When correctly configured:+.IP \(bu 2+in a new powershell window, \f[CR]$env:LEDGER_FILE\f[R] will show your+new setting+.IP \(bu 2+and so should \f[CR]hledger setup\f[R] and (once the file exists)+\f[CR]hledger files\f[R].+.SH Reconciling+Periodically you should reconcile \- compare your hledger\-reported+balances against external sources of truth, like bank statements or your+bank\(aqs website \- to be sure that your ledger accurately represents+the real\-world balances (and, that the real\-world institutions have+not made a mistake!).+This gets easy and fast with (1) practice and (2) frequency.+If you do it daily, it can take 2\-10 minutes.+If you let it pile up, expect it to take longer as you hunt down errors+and discrepancies.+.PP+A typical workflow:+.IP "1." 3+Reconcile cash.+Count what\(aqs in your wallet.+Compare with what hledger reports (\f[CR]hledger bal cash\f[R]).+If they are different, try to remember the missing transaction, or look+for the error in the already\-recorded transactions.+A register report can be helpful (\f[CR]hledger reg cash\f[R]).+If you can\(aqt find the error, add an adjustment transaction.+Eg if you have $105 in your wallet but hledger says $107, and can\(aqt+explain the missing $2, it could be:+.RS 4+.IP+.EX+2023\-01\-16 * adjust cash+ assets:cash $\-2 = $105+ expenses:misc+.EE+.RE+.IP "2." 3+Reconcile checking.+Log in to your bank\(aqs website.+Compare today\(aqs (cleared) balance with hledger\(aqs cleared balance+(\f[CR]hledger bal checking \-C\f[R]).+If they are different, track down the error or record the missing+transaction(s) or add an adjustment transaction, similar to the above.+Unlike the cash case, you can usually compare the transaction history+and running balance from your bank with the one reported by+\f[CR]hledger reg checking \-C\f[R].+This will be easier if you generally record transaction dates quite+similar to your bank\(aqs clearing dates.+.IP "3." 3+Repeat for other asset/liability accounts.+.PP+Tip: an institution\(aqs numbers can be rounded differently in different+places \- its website, its CSV or other exports, its emailed and paper+statements.+Choose one as your reference (usually the official statement), and aim+to reproduce its numbers: adjust hledger\(aqs display precision with+\f[CR]\-c\f[R] or \f[CR]\-\-round\f[R] (see Display rounding), and+record any small remaining differences with an adjustment transaction,+eg to an \f[CR]expenses:rounding\f[R] account.+.PP+Tip: instead of the register command, use hledger\-ui to see a+live\-updating register while you edit the journal:+\f[CR]hledger\-ui \-\-register checking \-C\f[R]+.PP+After reconciling, it could be a good time to mark the reconciled+transactions\(aq status as \(dqcleared and confirmed\(dq, if you want to+track that, by adding the \f[CR]*\f[R] marker after the date.+.PP+If you\(aqre using version control, this can be a good time to commit:+.IP+.EX+$ git commit \-m \(aqtxns\(aq 2023.journal+.EE+.SH Closing a journal file+At the end of the year, you may want to continue your journal in a new+file, so that old transactions don\(aqt slow down or clutter your+reports, and to help ensure the integrity of your accounting history.+See the close command.+.PP+If using version control, don\(aqt forget to \f[CR]git add\f[R] the new+file.+.SH hledger 1 and hledger 2+hledger 2 (the 1.99.x previews, and 2.0 when released) reads hledger 1+data, and most hledger 1 journals work unchanged.+hledger 1 (1.52.x) continues to receive essential fixes, and both can be+installed side by side (eg by renaming the hledger 1 executable to+\f[CR]hledger1\f[R]).+.PP+To upgrade from hledger 1:+.IP "1." 3+Back up your data files, or commit them to version control.+.IP "2." 3+Run \f[CR]hledger check\f[R] with hledger 2.+If you import CSV, also run your usual import command with+\f[CR]\-\-dry\-run\f[R].+.IP "3." 3+Compare your usual reports with hledger 1\(aqs (eg+\f[CR]hledger1 bs\f[R] and \f[CR]hledger bs\f[R]), and investigate any+differences.+.PP+Things that can need attention include cost basis annotations like+\f[CR]{$50}\f[R], which hledger 1 ignored but hledger 2 uses to track+lots, and a few checks that are now stricter.+Upgrading to hledger 2 describes them all, with fixes, and how to switch+back, or keep data usable with both versions.+.SH BUGS+We welcome bug reports in the hledger issue tracker+(https://bugs.hledger.org), or on the hledger chat or mail list+(https://hledger.org/support).+.PP+Some known issues and limitations:+.PP+hledger uses the system\(aqs text encoding when reading non\-ascii text.+If no system encoding is configured, or if the data\(aqs encoding is+different, hledger will give an error.+(See Text encoding and Troubleshooting.)+.PP+On Microsoft Windows, depending what kind of terminal window you use,+non\-ascii characters, ANSI text formatting, and/or the add command\(aqs+TAB key, may not be fully supported.+(For best results, try a powershell window.)+.PP+When showing colour, hledger sometimes asks the terminal for its+background colour, to choose colours that suit it (for headings, and for+charts in terminals advertising 24\-bit colour).+Occasionally this can misbehave: a terminal that doesn\(aqt answer (eg+some tmux setups) can delay the output by up to half a second; over a+slow connection, a late answer may appear as stray characters at your+shell prompt; on macOS, hledger can hang if its input is explicitly+redirected from \f[CR]/dev/tty\f[R]; and hledger may be stopped if it is+run in the background.+\f[CR]\-\-color=no\f[R] avoids these.+.PP+When processing large data files, hledger uses more memory than Ledger.+You can cap its memory use with GHC runtime system options, eg+\f[CR]hledger +RTS \-M2G \-RTS ...\f[R] (if it needs more, it will stop+with an error), and see memory and garbage collection statistics with+\f[CR]+RTS \-s \-RTS\f[R].+To use less memory at some cost in speed, add \f[CR]+RTS \-c \-RTS\f[R]+to use the compacting garbage collector; on large journals this can+reduce memory use by 20\-40%, while running 40\-60% slower.+(A RTS \f[CR]\-M\f[R] limit also enables this automatically, as memory+use approaches the limit.)+A multi\-period report with more than 10,000 periods, or a+\f[CR]\-\-forecast\f[R] that would generate more than 100,000+transactions (which in practice means a mistyped date somewhere, making+the report or the forecast span thousands of years), prints a warning+before starting, since it may need a lot of memory, so that you can+cancel it.+.SS Troubleshooting+Here are some common issues you might encounter when you run hledger,+and how to resolve them (and remember also you can usually get quick+Support):+.PP+\f[B]PATH issues: I get an error like \(dqNo command \(aqhledger\(aq+found\(dq\f[R]+.PD 0+.P+.PD+Depending how you installed hledger, the executables may not be in your+shell\(aqs PATH.+Eg on unix systems, stack installs hledger in \f[CR]\(ti/.local/bin\f[R]+and cabal installs it in \f[CR]\(ti/.cabal/bin\f[R].+You may need to add one of these directories to your shell\(aqs PATH,+and/or open a new terminal window.+.PP+\f[B]LEDGER_FILE issues: I configured LEDGER_FILE but hledger is not+using it\f[R]+.PD 0+.P+.PD+.IP \(bu 2+\f[CR]LEDGER_FILE\f[R] should be a real environment variable, not just a+shell variable.+Eg on unix, the command \f[CR]env | grep LEDGER_FILE\f[R] should show+it.+You may need to use \f[CR]export\f[R] (see+https://stackoverflow.com/a/7411509).+On Windows, \f[CR]$env:LEDGER_FILE\f[R] should show it.+.IP \(bu 2+You may need to force your shell to see the new configuration.+A simple way is to close your terminal window and open a new one.+.PP+\f[B]Text decoding issues: I get errors like \(dqIllegal byte+sequence\(dq or \(dqInvalid or incomplete multibyte or wide+character\(dq or \(dqcommitAndReleaseBuffer: invalid argument (invalid+character)\(dq\f[R]+.PD 0+.P+.PD+hledger usually needs its input to be decodable with the system+locale\(aqs text encoding.+See Text encoding and Install: Text encoding.+.PP+\f[B]COMPATIBILITY ISSUES: hledger gives an error with my Ledger+file\f[R]+.PD 0+.P+.PD+Not all of Ledger\(aqs journal file syntax or feature set is supported.+See hledger and Ledger for full details.+++.SH AUTHORS+Simon Michael <simon@joyful.com> and contributors.+.br+See http://hledger.org/CREDITS.html++.SH COPYRIGHT+Copyright 2007-2023 Simon Michael and contributors.++.SH LICENSE+Released under GNU GPL v3 or later.++.SH SEE ALSO+hledger(1), hledger\-ui(1), hledger\-web(1), ledger(1)
+ embeddedfiles/hledger.info view
@@ -0,0 +1,18208 @@+This is hledger.info, produced by makeinfo version 7.3 from stdin.++INFO-DIR-SECTION User Applications+START-INFO-DIR-ENTRY+* hledger: (hledger). Command-line plain text accounting tool.+END-INFO-DIR-ENTRY+++File: hledger.info, Node: Top, Next: PART 1 USER INTERFACE, Up: (dir)++hledger(1)+**********++hledger - a robust, friendly plain text accounting app (command line+version).++ 'hledger'+or+'hledger COMMAND [OPTS] [ARGS]'++ hledger is a robust, user-friendly, cross-platform set of programs+for tracking money, time, or any other commodity, using double-entry+accounting and a simple, editable file format. hledger is inspired by+and largely compatible with ledger(1), and largely interconvertible with+beancount(1).++ This manual is for hledger's command line interface, version 2.0. It+also describes the common options, file formats and concepts used by all+hledger programs. It might accidentally teach you some+bookkeeping/accounting as well! You don't need to know everything in+here to use hledger productively, but when you have a question about+functionality, this doc should answer it. It is detailed, so do skip+ahead or skim when needed. You can read it on hledger.org, or as an+info manual or man page on your system. You can also open a built-in+copy, at a point of interest, by running+'hledger help [TOPIC]'.++ The main function of the hledger CLI is to read plain text files+describing financial transactions, crunch the numbers, and print a+useful report or chart on the terminal (or save it as HTML, CSV, JSON,+SQL or SVG). Many reports are available, as subcommands. hledger will+also detect other 'hledger-*' executables as extra subcommands.++ hledger usually reads from (and appends to) a journal file specified+by the 'LEDGER_FILE' environment variable (defaulting to+'$HOME/.hledger.journal'); or you can specify files with '-f' options.+It can also read timeclock files, timedot files, or any CSV/SSV/TSV file+with a date field.++ Here is a small journal file, describing some starting balances and+two transactions:++2025-01-01 * opening balances+ assets:bank:checking $1000 = $1000+ assets:cash $100 = $100+ liabilities:creditcard $-50 = $-50+ equity:opening/closing balances++2025-01-10 * gift received+ income:gifts $-20+ assets:cash $20++2025-01-12 farmers market+ assets:cash $-13+ expenses:food $13++ Transactions are dated movements of money (etc.) between two or more+_accounts_: bank accounts, your wallet, revenue/expense categories,+people, etc. You can choose any account names you wish, using ':' to+indicate subaccounts. There must be at least two spaces between account+name and amount. Positive amounts are inflow to that account (_debit_),+negatives are outflow from it (_credit_). (Some reports show revenue,+liability and equity account balances as negative numbers as a result;+this is normal.)++ Some details from this example: the first entry records your+real-world balances on a starting date, with the equity account+absorbing the difference (its amount is inferred); the '= AMOUNT' parts+are optional balance assertions, for extra error checking; the '*' after+a date is an optional status mark, meaning "cleared"; and the currency+symbols are optional, but a good habit.++ hledger's add command can help you add transactions, or you can+install other data entry UIs like hledger-web or hledger-iadd. For more+extensive/efficient changes, use a text editor: Emacs + ledger-mode, VIM++ vim-ledger, or VS Code + hledger-vscode are some good choices (see+https://hledger.org/editors.html).++ To get started, run 'hledger add' and follow the prompts, or save+some entries like the above in '$HOME/.hledger.journal', then try+commands like:++$ hledger print -x+$ hledger aregister assets+$ hledger balance+$ hledger balancesheet+$ hledger incomestatement+$ hledger incomestatement -M --chart++ Run 'hledger' to list the commands.++ In this manual, we'll cover all of hledger's functionality in detail.+For a more gentle step by step introduction, see hledger by example, or+for a faster intro, the 5 minute quick start.++ For tips on configuring a default journal file, reconciling with your+bank, closing a file at end of year, or migrating between hledger 1 and+2, see PART 6: COMMON TASKS.++* Menu:++* PART 1 USER INTERFACE::+* Input::+* Commands::+* Options::+* Environment::+* PART 2 COMMANDS::+* User interface commands::+* Data entry commands::+* Report commands::+* Maintenance commands::+* Data generation commands::+* PART 3 DATA FORMATS::+* Journal::+* CSV::+* Timeclock::+* Timedot::+* PART 4 CONCEPTS::+* Time periods::+* Queries::+* Depth::+* Pivoting::+* Report titles::+* Languages::+* Amount arithmetic::+* Transaction balancing::+* Amount formatting::+* Cost reporting::+* Value reporting::+* Lots and capital gains::+* Generating data::+* Forecasting::+* Budgeting::+* Posting types::+* PART 5 MORE ABOUT THE COMMAND LINE::+* Output::+* Charts::+* Command line tips::+* PART 6 COMMON TASKS::+* Setting LEDGER_FILE::+* Reconciling::+* Closing a journal file::+* hledger 1 and hledger 2::+* BUGS::+++File: hledger.info, Node: PART 1 USER INTERFACE, Next: Input, Prev: Top, Up: Top++1 PART 1: USER INTERFACE+************************+++File: hledger.info, Node: Input, Next: Commands, Prev: PART 1 USER INTERFACE, Up: Top++2 Input+*******++hledger reads one or more data files, each time you run it. You can+specify a file with '-f', like so++$ hledger -f FILE [-f FILE2 ...] print++ Files are most often in hledger's journal format, with the '.journal'+file extension ('.hledger' or '.j' also work); these files describe+transactions, like an accounting general journal.++ When no file is specified, hledger looks for '.hledger.journal' in+your home directory.++ But most people prefer to keep financial files in a dedicated folder,+perhaps with version control. Also, starting a new journal file each+year is common (it's not required, but helps keep things fast and+organised). So we usually configure a different journal file, by+setting the 'LEDGER_FILE' environment variable, to something like+'~/finance/2023.journal'. For more about how to do that on your system,+see Common tasks > Setting LEDGER_FILE.++* Menu:++* Text encoding::+* Data formats::+* Standard input::+* Multiple files::+* Strict mode::+++File: hledger.info, Node: Text encoding, Next: Data formats, Up: Input++2.1 Text encoding+=================++hledger expects non-ascii input to be decodable with the system locale's+text encoding. (For CSV/SSV/TSV files, this can be overridden by the+'encoding' CSV rule.)++ So, trying to read non-ascii files which have the wrong text+encoding, or when no system locale is configured, will fail. To fix+this, configure your system locale appropriately, and/or convert the+files to your system's text encoding (using 'iconv' on unix, or+powershell or notepad on Windows). See Install: Text encoding for more+tips.++ hledger's output will use the system locale's encoding.++ hledger's docs and example files mostly use UTF-8 encoding.+++File: hledger.info, Node: Data formats, Next: Standard input, Prev: Text encoding, Up: Input++2.2 Data formats+================++Usually the data file is in hledger's journal format, but it can be in+any of the supported file formats, which currently are:++Reader: Reads: Automatically used for+ files with extensions:+---------------------------------------------------------------------------+'journal' hledger journal files and some '.journal' '.j'+ Ledger journals, for '.hledger' '.ledger'+ transactions+'timeclock' timeclock files, for precise '.timeclock'+ time logging+'timedot' timedot files, for approximate '.timedot'+ time logging+'csv' Comma- or other '.csv'+ delimiter-separated values, for+ data import+'ssv' Semicolon separated values '.ssv'+'tsv' Tab separated values '.tsv'+'rules' CSV/SSV/TSV/other separated '.rules'+ values, alternate way++ These formats are described in more detail below.++ hledger detects the format automatically based on the file extensions+shown above. If it can't recognise the file extension, it assumes+'journal' format. So for non-journal files, it's important to use a+recognised file extension, so as to either read successfully or to show+relevant error messages.++ You can also force a specific reader/format by prefixing the file+path with the format and a colon. Eg, to read a .dat file containing+tab separated values:++$ hledger -f tsv:/some/file.dat stats+++File: hledger.info, Node: Standard input, Next: Multiple files, Prev: Data formats, Up: Input++2.3 Standard input+==================++The file name '-' means standard input:++$ cat FILE | hledger -f- print++ If reading non-journal data in this way, you'll need to write the+format as a prefix, like 'timeclock:' here:++$ echo 'i 2009/13/1 08:00:00' | hledger print -f timeclock:-+++File: hledger.info, Node: Multiple files, Next: Strict mode, Prev: Standard input, Up: Input++2.4 Multiple files+==================++You can specify multiple '-f' options, to read multiple files as one big+journal. When doing this, note that certain features (described below)+will be affected:++ * Balance assertions will not see the effect of transactions in+ previous files. (Usually this doesn't matter as each file will set+ the corresponding opening balances.)+ * Some directives will not affect previous or subsequent files.++ If needed, you can work around these by using a single parent file+which includes the others (this works with CSV files too), or+concatenating the files into one, eg: 'cat a.journal b.journal | hledger+-f- CMD'.+++File: hledger.info, Node: Strict mode, Prev: Multiple files, Up: Input++2.5 Strict mode+===============++hledger checks input files for valid data. By default, the most+important errors are detected, while still accepting easy journal files+without a lot of declarations:++ * Are the input files parseable, with valid syntax ?+ * Are all transactions balanced ?+ * Do all balance assertions pass ?++ With the '-s'/'--strict' flag, additional checks are performed:++ * Are all accounts posted to, declared with an 'account' directive ?+ (Account error checking)+ * Are all commodities declared with a 'commodity' directive ?+ (Commodity error checking)+ * Are all commodity conversions declared explicitly ?++ You can use the check command to run individual checks - the ones+listed above and some more.+++File: hledger.info, Node: Commands, Next: Options, Prev: Input, Up: Top++3 Commands+**********++hledger provides various subcommands for getting things done. Most of+these commands do not change the journal file; they just read it and+output a report. A few commands assist with adding data and file+management. Some commands to start with:++ * 'hledger add' - add transactions, with interactive prompts+ * 'hledger print' - show journal entries+ * 'hledger aregister assets:checking' ('areg') - show one account's+ transactions and running balance+ * 'hledger balancesheet' ('bs') - show assets, liabilities and net+ worth+ * 'hledger incomestatement' ('is') - show revenues and expenses++ To show a summary of commands, run 'hledger' with no arguments. See+also PART 2: COMMANDS below.++ To use a particular command, run 'hledger CMD [CMDOPTS] [CMDARGS]',++ * CMD is the full command name, or its standard abbreviation shown in+ the commands list, or any unambiguous prefix of the name.++ * CMDOPTS are command-specific options, if any. Command-specific+ options must be written after the command name. Eg: 'hledger print+ -x'.++ * CMDARGS are additional arguments to the command, if any. Most+ hledger commands accept arguments representing a query, to limit+ the data in some way. Eg: 'hledger reg assets:checking'.++ To list a command's options, arguments, and documentation in the+terminal, run 'hledger CMD -h'. Eg: 'hledger bal -h'.++* Menu:++* Add-on commands::+++File: hledger.info, Node: Add-on commands, Up: Commands++3.1 Add-on commands+===================++In addition to the built-in commands, you can install _add-on commands_,+which will also appear in hledger's commands list. Some of these can be+installed as separate packages; others can be found in hledger's bin/+directory, documented at https://hledger.org/scripts.html.++ Add-on commands are programs or scripts in your shell's PATH, whose+name starts with "hledger-" and ends with no extension or a recognised+extension (".bat", ".com", ".exe", ".hs", ".js", ".lhs", ".lua", ".php",+".pl", ".py", ".rb", ".rkt", or ".sh"), and (on unix and mac) which has+executable permission for the current user.++ You can run add-on commands directly: 'hledger-ui --watch'.++ Or you can run them with hledger, like built-in commands: 'hledger ui+--watch'. In this case hledger's config file will be used, so you can+set custom options for the addon there. (Before hledger 1.50, an '--'+argument was needed before addon options, but not any more.)++ Arguments written after the command name are passed on to the add-on+unchanged, except for the options specific to the 'hledger' CLI+('--conf', '--no-conf', '-n'), which hledger consumes. To send one of+those to the add-on instead, write it after a '--' argument: 'hledger ui+-- -n'. hledger consumes only that first '--'; later ones are passed on+like any other argument.+++File: hledger.info, Node: Options, Next: Environment, Prev: Commands, Up: Top++4 Options+*********++Run 'hledger -h' to see general command line help. Options can be+written either before or after the command name. These options are+specific to the 'hledger' CLI:++Flags:+ --conf=CONFFILE Use extra options defined in this config file. If+ not specified, searches upward and in XDG config+ dir for hledger.conf (or .hledger.conf in $HOME).+ -n --no-conf ignore any config file++ And the following general options are common to most hledger+commands:++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.+ --alias=A=B|/RGX/=RPL transform account names from A to B, or by+ replacing regular expression matches+ --auto generate extra postings by applying auto posting+ rules ("=") to all transactions+ --forecast[=PERIOD] Generate extra transactions from periodic rules+ ("~"), from after the latest ordinary transaction+ until 6 months from now. Or, during the specified+ PERIOD (the equals is required). Auto posting rules+ will also be applied to these transactions. In+ hledger-ui, also make future-dated transactions+ visible at startup.+ --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)++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 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)+ --date2 match/use secondary dates instead (deprecated)+ -U --unmarked include only unmarked postings/transactions+ -P --pending include only pending postings/transactions+ -C --cleared include only cleared postings/transactions+ (-U/-P/-C can be combined)+ -R --real include only non-virtual postings+ -E --empty Show zero items, which are normally hidden.+ In hledger-ui & hledger-web, do the opposite.+ --depth=DEPTHEXP if a number (or -NUM): show only top NUM levels+ of accounts. If REGEXP=NUM, only apply limiting to+ accounts matching the regular expression.+ -B --cost 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? 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:+ -? 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+ --test[=PATTERN] run built-in tests (those matching PATTERN) and+ exit+ --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++ Usually hledger accepts any unambiguous flag prefix, eg you can write+'--dry' instead of '--dry-run'.++ You can combine short flags which don't take arguments, eg you can+write '-MAST' instead of '-M -A -S -T'. Flags requiring an argument+can't be combined in this way ('-If FILE' won't work).++ If the same option appears more than once in a command line, usually+the last (right-most) wins. Similarly, if mutually exclusive flags are+used together, the right-most wins. (When flags are mutually exclusive,+they'll usually have a group prefix in -help.)++ With most commands, arguments are interpreted as a hledger query+which filters the data. Some queries can be expressed either with+options or with arguments.++* Menu:++* Config files::+* Command aliases::+* Config file troubleshooting::+++File: hledger.info, Node: Config files, Next: Command aliases, Up: Options++4.1 Config files+================++You can configure default command line options and arguments+conveniently in a hledger config file. Config file options will be+inserted near the start of your command line, so you can override them+with command line options.++ You can specify a config file with the '--conf' option. Otherwise,+hledger will search for a default config file, in this order:++ * 'hledger.conf' in the current directory or above+ * '.hledger.conf' in your home directory+ * 'hledger.conf' in your XDG config+ ('~/.config/hledger/hledger.conf').++ Only one config file is used. Here's a small example:++# General options, used with all hledger commands that support them.+--pretty++# Command-specific options.+[print]+--explicit --infer-costs++ And here is a commented starter config file:+https://github.com/hledgerorg/hledger/blob/main/hledger.conf.sample++ You can put not only options, but also arguments in a config file.++ You can ignore all config files by adding the '-n'/'--no-conf' flag+to the command line. This is recommended when using hledger in scripts.+When both '--conf' and '--no-conf' options are used, the right-most+wins.++ Note, hledger 1 also reads config files, but some things written for+hledger 2 make it stop with an error: indented lines (including the+continuation lines of a multi-line command alias), a '#' inside quotes,+quotes around only part of an argument, and options in a '[COMMAND]'+section which that command doesn't have in hledger 1. (hledger 1+ignores single-line command aliases, and unknown options in the general+section.) In this situation, you can run hledger 1 with '-n', or give+it a separate config file with '--conf'.+++File: hledger.info, Node: Command aliases, Next: Config file troubleshooting, Prev: Config files, Up: Options++4.2 Command aliases+===================++In a config file you can also define command aliases: your own custom+commands, which expand to a longer command line (similar to git's+aliases). (Since 1.99.4.) Eg:++[alias]+p = print+p1 = transactions+rev10 = balance type:R -2 -X$ -p 'every 10 years from 2000'++ With this in your config file, you'll see a 'rev10' command in the+'hledger help commands' list, and 'hledger rev10' will run the balance+command above. Options or arguments written at the command line will be+added at the end, usually overriding those in the alias; eg 'hledger+rev10 -X €' will convert to '€' instead of '$'. Command aliases can+also be used in 'run' command scripts and at the 'repl' prompt.++ Each line in an '[alias]' section should look like 'NAME = COMMAND+[ARGS..]'. A command line can be continued on following lines by+indenting them more than the 'NAME'; the indented lines are joined to+the command line. Blank lines and comment lines within it are ignored,+so you can space it out or comment out individual lines. Eg:++[alias]+rev10 = balance+ type:R+ -2+ -X$+ -p 'every 10 years from 2000'+ # --drop 1++ (hledger 1 can't read these continuation lines; see Config files.)++ Command aliases override addon commands with the same name, but they+can't override builtin command names or abbreviations like 'balance' or+'bal'. If the same alias name is defined more than once, the last+definition wins.++ An alias's command can be a hledger builtin command, addon command,+or another alias. If there's a '[COMMAND]' options section for an+alias's resolved builtin command, that will also be applied.++ Or if an alias's command line begins with '!', the rest is run as a+shell command (with any extra command line arguments appended). Eg:++[alias]+git-commit = ! git commit -p+jj-commit = ! jj commit -i++ For safety, shell command aliases run only if defined in a trusted+config file: one you gave explicitly with '--conf', or your user config+file ('~/.hledger.conf' or the XDG 'hledger.conf'). Shell commands in a+nearby automatically-found 'hledger.conf', in the current directory or a+parent directory, will not run - this prevents a config file from an+untrusted downloaded or shared directory from running arbitrary shell+commands.+++File: hledger.info, Node: Config file troubleshooting, Prev: Command aliases, Up: Options++4.3 Config file troubleshooting+===============================++A default config file (one which hledger finds and uses automatically,+without a '--conf' option) is convenient, but it can surprise you, eg by+quietly changing report output, or breaking scripts which use hledger.+Some tips:++ 1. Be mindful about what you put in your config file; consider the+ effect on all your reports.+ 2. If a hledger command isn't doing what you expect, try it again with+ '-n', to see if a config file is to blame.+ 3. Run 'hledger setup' to list the currently active config file.+ ('setup' is not affected by config files.)+ 4. Add '--debug' or '--debug=8' to any command to see config/command+ line debug output.+ 5. In scripts, and in examples you share with others, add '-n' so that+ a config file can't change the result.+ 6. When you download hledger data from elsewhere, watch out for+ directories containing a 'hledger.conf' file.+ 7. If hledger reports an error in a config file which should be fine,+ you might be running an older hledger version. (Since 1.99.6,+ config file errors show the hledger version; with older versions,+ check which hledger executables are in your PATH.)+ 8. A config file with errors doesn't stop help flags like '--help' or+ '--version' from working, unless they're used with a command alias+ defined in that file, in which case the error is reported.+++File: hledger.info, Node: Environment, Next: PART 2 COMMANDS, Prev: Options, Up: Top++5 Environment+*************++These environment variables affect hledger:++ *HLEDGER_FASTPATH* hledger parses simple journal entries with a+special fast-path parser, when possible. Setting this to 'off' disables+the fast path, so that all entries are parsed by the general parser,+which could be useful to rule out a parser bug. Setting it to 'check'+parses each entry with both parsers, and reports an error if they+disagree. ('--debug=1' shows how much of a journal was parsed by the+fast path.)++ *HLEDGER_LESS* If 'less' is your pager, this variable specifies the+'less' options hledger should use. (Otherwise, 'LESS' + custom options+are used.)++ *LEDGER_FILE* The default journal file, to be used when no+'-f/--file' option is provided. For example, it could be+'~/finance/main.journal'. This can also be a glob pattern, eg+'./2???.journal'. (If the glob matches multiple files, only the+alphanumerically first one is used.) If LEDGER_FILE points to a+non-existent file, an error will be raised. If the value is the empty+string, it is ignored.++ If LEDGER_FILE is not set and '-f' is not provided, the default+journal file is '$HOME/.hledger.journal' (or if a home directory can't+be detected, './.hledger.journal').++ See also Common tasks > Setting LEDGER_FILE.++ *NO_COLOR* If this environment variable exists (with any value,+including empty), hledger will not use ANSI color codes in terminal+output, unless overridden by an explicit '--color=y' or '--colour=y'+option.++ *LANGUAGE*, *LC_ALL*, *LC_MESSAGES*, *LANG* When the '--lang=auto'+option is used, these select the language of report titles and headings,+following the usual gettext rules: the effective locale is 'LC_ALL',+else 'LC_MESSAGES', else 'LANG'; if that is 'C', 'POSIX' or unset,+English is used; otherwise the languages listed in 'LANGUAGE'+(colon-separated) are tried first, then the effective locale. See+Languages.+++File: hledger.info, Node: PART 2 COMMANDS, Next: User interface commands, Prev: Environment, Up: Top++6 PART 2: COMMANDS+******************++Here are hledger's standard commands. You can list these by running+'hledger help commands', or as a more compact list by running 'hledger'.+If you have installed more add-on commands, they also will be listed.++ In the following command docs, each command's specific options are+shown. Most commands also support the general options described above,+though some of them might have no effect. (Usually if there's a+sensible way for a general option to affect a command, it will.) You+can list all of a command's options by running 'hledger CMD -h'.++ *User interface commands*++ * help (h) - show documentation and examples+ * repl - run multiple commands from an interactive prompt+ * run - run multiple commands from a file or command line+ * ui - (if installed) run a terminal UI+ * web - (if installed) run a web UI++ *Data entry commands*++ * add - add transactions using terminal prompts+ * get - fetch transaction and price data for import+ * import - add new transactions from other files, eg CSV files++ *Report commands*++ * accounts (acc) - account names+ * activity - transaction or posting counts, as a bar chart+ * aregister (areg) - an account's transactions & running balance+ * balance (bal) - balance changes, end balances, gains, budgets &+ more+ * balancesheet (bs) - assets, liabilities and net worth+ * balancesheetequity (bse) - assets, liabilities and equity+ * cashflow (cf) - changes in liquid assets+ * codes - transaction codes+ * commodities (comm) - commodity/currency symbols+ * descriptions (desc) - transaction descriptions+ * files - input files used+ * holdings - investment holdings and performance+ * incomestatement (is) - revenues and expenses+ * notes - the note part of transaction descriptions+ * payees - the payee part of transaction descriptions+ * prices - market prices+ * print - transaction entries, or a whole exported journal+ * register (reg) - matched postings & running total, across accounts+ * roi - return on investments+ * stats - journal statistics+ * tags - tag names+ * transactions (tx) - transactions, in compact one-line format++ *Maintenance commands*++ * setup - check your hledger installation+ * init - create starter journal files+ * check - check that your journal is valid+ * diff - compare an account's transactions in two journals++ *Data generation commands*++ * close - generate transactions to zero/restore/assert balances+ * rewrite - generate postings by rule, like print -auto++ Next, these commands are described in detail.+++File: hledger.info, Node: User interface commands, Next: Data entry commands, Prev: PART 2 COMMANDS, Up: Top++7 User interface commands+*************************++* Menu:++* help::+* repl::+* run::+* ui::+* web::+++File: hledger.info, Node: help, Next: repl, Up: User interface commands++7.1 help+========++ h. + Show some part of hledger's documentation.++Flags:+ -i use info when showing the manual+ -m use man when showing the manual+ -p use less (or $PAGER) when showing the manual+ -w use a web browser when showing the manual+ -l just list the manual topics matching TOPIC+ --builtins with commands: show only builtin commands+ --addons with commands: show only addon commands+ --aliases with commands: show only command aliases++ The part shown is selected by arguments:++ * 'quickref' (or no args): a quick reference / overview+ * 'commands': all commands, including addons and aliases (or just one+ category, with -builtins/-addons/-aliases)+ * 'usage [CMD]': command line options help (like -h/-help)+ * 'examples [CMD]': command line examples+ * 'manual [TOPIC]': view a topic in the manual, or list them all+ * 'TOPIC': (like 'manual TOPIC')+ * 'home|install|relnotes|docs|support|sponsor': browse hledger.org+ pages++ TOPIC is a section heading in the hledger, hledger-ui or hledger-web+manual, or part of one, matched case insensitively. Enclose it in+quotes if it contains spaces. With no TOPIC ('hledger help manual'),+all manual topics are listed, indented to show (most of) their+hierarchy.++ The manual will be shown in a default viewer (info, man, pager, web+browser), or you can choose with -i/-m/-p/-w.++ The manual is built in to your hledger executable, so it can be+useful when offline, or when you prefer the terminal to a web browser,+or when the appropriate hledger manual or viewers are not installed+properly on your system.++ By default it chooses the best viewer found in $PATH, trying in this+order: 'info', 'man', '$PAGER', 'less', 'more', stdout. (If a TOPIC is+specified, '$PAGER' and 'more' are not tried.) You can force the use of+info, man, or a pager with the '-i', '-m', or '-p' flags. If no viewer+can be found, or if running non-interactively, it just prints the manual+to stdout.++ Examples:++$ hledger help # show the quick reference+$ hledger help -h # show the help command's options+$ hledger help commands # list all commands+$ hledger help commands --aliases # list just the command aliases+$ hledger help 'time periods' # show the "Time periods" section in the manual+$ hledger help keys # show the "KEYS" section in the hledger-ui manual+$ hledger help -l # list the manual's topics+$ hledger help -l journal # list the manual topics matching "journal"+$ hledger help examples add # show examples for the add command+++File: hledger.info, Node: repl, Next: run, Prev: help, Up: User interface commands++7.2 repl+========++Start an interactive prompt for running hledger commands. Input files+are reloaded only when they change, so commands run faster.++Flags:+ --no-watch disable automatic reloading of changed input+ files, config aliases and addon commands++ 'hledger repl' starts a read-eval-print loop (REPL) where you can+enter commands interactively. As with the 'run' command, each input+file (or each input file/input options combination) is parsed just once,+so commands will run more quickly than if you ran them individually at+the command line.++ The input file(s) specified for the 'repl' command will be used+throughout the session; but you can override this temporarily by+specifying new '-f' options for a command.++ Before running a command, any input files which have changed on disk+are automatically reloaded (including CSV rules files). Also command+aliases are reloaded if the config file has changed, and addon commands+are re-detected if PATH's contents have changed. The '--no-watch' flag+disables all of this reloading, so as to work with a stable snapshot of+the data, or to avoid file/directory polling on a slow network drive.++ Any other general flags given to 'repl' - input, reporting, or+display flags such as '-I', '--strict', '--alias', '-b'/'-e', '--depth',+'--cost', '--value', '--color' - are also applied to every command you+run. A command can still override them by specifying its own flags.++ The command syntax is the same as with 'run':++ * enter one hledger command at a time, without the usual 'hledger'+ first word+ * empty lines and comment text from '#' to end of line are ignored+ * enclose arguments in quotes if they contain spaces.++ Use 'help' (or 'h') to show the quick reference, or 'help commands'+to list commands. Addons in PATH and command aliases defined in a+config file can also be used. Generally 'repl' should feel much like+using hledger at the command line. But 'repl' requires full command+names or official abbreviations (it does not recognise ad hoc+abbreviations).++ To run a single shell command, type '! SHELLCMD' (eg '! ls' or '! git+status').++ While it is running, the REPL remembers your command history, and you+can navigate in the usual ways:++ * Keypad or Emacs navigation keys to edit the current command line+ * UP/DOWN or control-P/control-N to step back/forward through history+ * control-R to search for a past command+ * TAB to complete file paths.++ You can type control-C to cancel a long-running command (but only+once; typing it a second time will exit the REPL).++ In most shells you can type control-Z to temporarily exit to the+shell (and then 'fg' to return to the REPL).++ To exit the REPL, use control-D or 'q' or 'quit' or 'exit'.++* Menu:++* Examples::+++File: hledger.info, Node: Examples, Up: repl++7.2.1 Examples+--------------++Start the REPL and enter some commands:++$ hledger repl +hledger 1.52+Enter hledger commands. To exit, enter 'quit' or 'exit', or send EOF / control-d.+2025> stats+Main file : .../2025.journal+...+2025> stats -f 2024/2024.journal +Main file : .../2024.journal+...+2025> stats+Main file : .../2025.journal+...++ or:++$ hledger repl -f some.journal+hledger 1.52+Enter hledger commands. To exit, enter 'quit' or 'exit', or send EOF / control-d.+some> bs+...+some> print -b 'last week'+...+some> bs -f other.journal+...+++File: hledger.info, Node: run, Next: ui, Prev: repl, Up: User interface commands++7.3 run+=======++Run a sequence of hledger commands, provided as files or command line+arguments. Input files are parsed just once, so the commands run+faster.++Flags:+ -O --output-format=FMT select the output format. Supported formats:+ html.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ --view write output to FILE, or to view.FMT in hledger's+ cache directory, and open it in the system's+ default viewer for its format (eg a web browser for+ html). The default format is html.++ You can use 'run' in three ways:++ * 'hledger run -- CMD1 -- CMD2 -- CMD3' - read commands from the+ command line, separated by '--'+ * 'hledger run SCRIPTFILE1 SCRIPTFILE2' - read commands from one or+ more files+ * 'cat SCRIPTFILE1 | hledger run' - read commands from standard+ input.++ 'run' first loads the input file(s) specified by 'LEDGER_FILE' or by+'-f' options, in the usual way. Then it runs each command in turn, each+using the same input data. But if you want a particular command to use+different input, you can specify an '-f' option within that command.+This will override (not add to) the default input, just for that+command.++ Any other general flags given to 'run' - input, reporting, or display+flags such as '-I', '--strict', '--alias', '-b'/'-e', '--depth',+'--cost', '--value', '--color' - are also applied to every command it+runs. A command can still override them by specifying its own flags.++ Each input file (more precisely, each combination of input file and+input options) is parsed only once. This means that commands will not+see any changes made to these files, until the next run. But the+commands will run more quickly than if run individually (typically about+twice as fast).++ Command scripts, whether in a file or written on the command line,+have a simple syntax:++ * each line may contain a single hledger command and its arguments,+ without the usual 'hledger' first word+ * empty lines are ignored+ * text from '#' to end of line is a comment, and ignored+ * you can use single or double quotes to quote arguments when needed,+ as on the command line+ * these extra commands are available: 'echo TEXT' prints some text+ (interpreting the backslash escapes '\n', '\t', '\r', '\\'), and+ 'exit' or 'quit' ends the run.++ On unix systems you can use '#!/usr/bin/env hledger run' in the first+line of a command file to make it a runnable script. If that gives an+error, use '#!/usr/bin/env -S hledger run'.++ It's ok to use the 'run' command recursively within a command script.++ With '-O html', '-o FILE.html' or '--view', 'run' collects the+commands' outputs into one HTML page instead of printing them: a section+for each command, headed by its command line, which can be folded; and a+heading for each 'echo'. Commands which can produce HTML (the balance+commands, 'register', 'aregister', 'print', 'holdings', 'activity') do+so, charts included; others' text output is shown as is. '--view' then+opens the page in your web browser (see Output destination), which is a+convenient way to see several reports, or charts, at once:++$ hledger run --view -- echo Overview -- is -M --chart -- bs -Q --chart -- reg expenses -p thismonth++ Command aliases defined in a config file can also be used in command+scripts.++ You may find some differences in behaviour between 'run' command+lines and normal hledger command lines. 'run' is a little stricter; eg+it requires full command names or official abbreviations (as seen in the+commands list), and command options must be written after the command+name.++* Menu:++* Examples: Examples 2.+++File: hledger.info, Node: Examples 2, Up: run++7.3.1 Examples+--------------++Run commands from the command line:++hledger -f some.journal run -- balance assets --depth 2 -- balance liabilities -f /some/other.journal --depth 3 --transpose -- stats++ This would load 'some.journal', run 'balance assets --depth 2' on it,+then run 'balance liabilities --depth 3 --transpose' on+'/some/other.journal', and finally run 'stats' on 'some.journal'++ Run commands from standard input:++(echo "files"; echo "stats") | hledger -f some.journal run++ Run commands as a script:++$ cat report+#!/usr/bin/env -S hledger run -f some.journal++echo "List of accounts in some.journal"+accounts++echo "Assets of some.journal"+balance assets --depth 2++echo "Liabilities from /some/other.journal"+balance liabilities -f /some/other.journal --depth 3 --transpose++echo "Commands from another.script, applied to another.journal"+run -f another.journal another.script++$ chmod +x report+$ ./report+List of accounts in some.journal+...+++File: hledger.info, Node: ui, Next: web, Prev: run, Up: User interface commands++7.4 ui+======++Runs hledger-ui, a terminal UI (if installed).+++File: hledger.info, Node: web, Prev: ui, Up: User interface commands++7.5 web+=======++Runs hledger-web, a web UI (if installed).+++File: hledger.info, Node: Data entry commands, Next: Report commands, Prev: User interface commands, Up: Top++8 Data entry commands+*********************++* Menu:++* add::+* get::+* import::+++File: hledger.info, Node: add, Next: get, Up: Data entry commands++8.1 add+=======++Add new transactions to a journal file, with interactive prompting.++Flags:+ --no-new-accounts don't allow creating new accounts+ --layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 - right-align amounts, as in hledger 1+ COL - align decimal marks at column COL+ (default: 53)++ Many hledger users edit their journals directly with a text editor,+or generate them from CSV. For more interactive data entry, there is the+'add' command, which prompts interactively on the console for new+transactions, and appends them to the main journal file (which should be+in journal format). Existing transactions are not changed. This is one+of the few hledger commands that writes to the journal file (see also+'import').++ To use it, just run 'hledger add' and follow the prompts. You can+add as many transactions as you like; when you are finished, enter '.'+or press control-d or control-c to exit.++ Features:++ * add tries to provide useful defaults, using the most similar (by+ description) and nearest-dated transaction (filtered by the query,+ if any) as a template.+ * You can also set the initial defaults with command line arguments.+ * Readline-style edit keys can be used during data entry.+ * The tab key will auto-complete whenever possible - accounts,+ payees/descriptions, dates ('yesterday', 'today', 'tomorrow'). If+ the input area is empty, it will insert the default value.+ * A parenthesised transaction code may be entered following a date.+ * Comments and tags may be entered following a description or amount.+ * If you make a mistake, enter '<' at any prompt to go one step+ backward.+ * Before saving a transaction, add checks that the journal will still+ be readable with it added, as the next read with the same options+ will check it (eg balance assertions must pass, lots must be valid,+ and with '--strict', the strict checks must pass). If not, it+ shows the error and goes one step backward, so you can correct the+ entry. (With a large journal this check may take a moment; it runs+ while you are deciding whether to save.)+ * Input prompts are displayed in a different colour when the terminal+ supports it.++ Notes:++ * If you enter a number with no commodity symbol, and you have+ declared a default commodity with a 'D' directive, you might expect+ 'add' to add this symbol for you. It does not do this; we assume+ that if you are using a 'D' directive you prefer not to see the+ commodity symbol repeated on amounts in the journal.+ * 'add' creates entries in journal format; it won't work with+ timeclock or timedot files.+ * There is a known issue on Windows if this hledger version is built+ from stackage: the prompts will show ANSI junk instead of colours+ (#2410). You can avoid this by using official hledger release+ binaries or by building it with haskeline >=0.8.4; or by running+ 'add' with '--color=no', perhaps configured in your config file.++ Examples:++ * Record new transactions, saving to the default journal file:++ hledger add++ * Add transactions to 2024.journal, but also load 2023.journal for+ completions:++ hledger add --file 2024.journal --file 2023.journal++ * Provide answers for the first four prompts:++ hledger add today 'best buy' expenses:supplies '$20'++ There is a detailed tutorial at https://hledger.org/add.html.++* Menu:++* add and balance assertions::+* add and balance assignments::+++File: hledger.info, Node: add and balance assertions, Next: add and balance assignments, Up: add++8.1.1 add and balance assertions+--------------------------------++You can add a balance assertion by writing 'AMOUNT = BALANCE' when asked+for an amount. Eg '100 = 500'.++ Also, each time you enter a new amount, hledger re-checks all balance+assertions in the journal and rejects the new amount if it would make+any of them fail. You can run 'add' with '-I' or '--ignore-assertions'+to disable balance assertion checking.+++File: hledger.info, Node: add and balance assignments, Prev: add and balance assertions, Up: add++8.1.2 add and balance assignments+---------------------------------++*Adding a new balance assignment*+When entering a posting amount, you can write a '= BALANCEAMOUNT'+balance assignment (or '==', '=*', '==*') instead. The posting amount+required to produce this balance will be calculated automatically.+_(Since 1.51)_++ *Adding a posting dated before an existing balance assignment*+'add' won't let you add a posting dated earlier than an existing balance+assignment in that account. (Because it calculates balance assignments+only once at startup, converting them to assertions, so adding the new+amount causes an assertion failure.) To work around this, run 'add'+with balance assertions ignored: 'hledger add -I'.+++File: hledger.info, Node: get, Next: import, Prev: add, Up: Data entry commands++8.2 get+=======++Fetch new transactions and market prices for the journal, by running+'getdata' and 'getprices' helper scripts. New prices are merged into+prices files automatically; new transaction data is just saved, for+later conversion & import by 'import'.++Flags:+ --transactions fetch transactions only+ --prices fetch prices only+ --dry-run just print the commands that would be run++ By default, this command fetches both transactions and prices.++* Menu:++* Phase 1 transactions data::+* Phase 2 prices::+* Merging new prices::+* get's helper scripts::+++File: hledger.info, Node: Phase 1 transactions data, Next: Phase 2 prices, Up: get++8.2.1 Phase 1: transactions data+--------------------------------++ 1. Creates a 'data/' directory next to the main journal file, if it+ does not exist.+ 2. If the 'data/getdata' helper script exists, runs it in the data+ directory, so it can save downloaded files (CSV/TSV/JSON/OFX/etc.)+ there.+++File: hledger.info, Node: Phase 2 prices, Next: Merging new prices, Prev: Phase 1 transactions data, Up: get++8.2.2 Phase 2: prices+---------------------++ 1. Creates a 'prices/' directory next to the main journal file, if it+ does not exist.+ 2. If the 'prices/getprices' helper script exists, hledger first+ guesses the journal's base currency (the commodity most used as the+ target in P price directives; or if there are no P directives, the+ commodity most used in postings; or if there are no postings,+ "USD"). Then for each other commodity in the journal, it fetches+ daily market prices in the base currency, from that commodity's+ earliest transaction until today, by running 'getprices BASECUR+ COMM START END'. Each commodity's prices are merged into+ 'prices/<COMM>.prices', preserving existing prices.++ Commands being run, and files being updated, are logged to stderr.+With '--dry-run', you can preview the commands without running them.+++File: hledger.info, Node: Merging new prices, Next: get's helper scripts, Prev: Phase 2 prices, Up: get++8.2.3 Merging new prices+------------------------++Complete historical price data can be hard to get, so the prices phase+is careful to preserve older prices. If prices files already exist, the+newly fetched prices will be merged as follows:++ * Prices files will be updated only if they contain nothing but P+ directives (or blank lines).+ * New prices for dates already seen are discarded. (So if you want+ to replace old prices, you must delete them before running 'get'.)+ * If no new prices remain to be added, the prices file is left as-is.+ * Otherwise, the old prices plus the new prices are saved to the+ file, ordered by: date, from commodity, to commodity. Each price+ keeps the number format it was written with.+++File: hledger.info, Node: get's helper scripts, Prev: Merging new prices, Up: get++8.2.4 get's helper scripts+--------------------------++Data downloading varies for everyone, and needs to be easily+customisable, so it is done via helper scripts:++* Menu:++* getdata::+* getprices::+++File: hledger.info, Node: getdata, Next: getprices, Up: get's helper scripts++8.2.4.1 getdata+...............++If you want 'get' to download transaction data for you, make your own+'getdata' shell script (or executable program), and install it in the+'data' directory next to your main journal file.++ It should download zero or more transaction data files into its+current directory. Anything it prints (on stdout or stderr) is shown on+stderr, as progress output. These are typically bank/brokerage+CSV/TSV/SSV files, but could be anything that your hledger rules files+can read. The hledger repo's getdata is a stub you can start from, with+commented examples.+++File: hledger.info, Node: getprices, Prev: getdata, Up: get's helper scripts++8.2.4.2 getprices+.................++If you want 'get' to download historical market prices (useful for+currency conversions, and value or gains reports), install a 'getprices'+script in the 'prices' directory next to your main journal file.++ You can start with the hledger repo's getprices, customising it if+needed. This script uses pricehist, so you will need to install that+python tool also (eg with 'uv tool install pricehist'). Some price+providers limit the commodity pairs, history, or number of requests+available for free; you can get better data by paying them and setting+up their API keys as environment variables.++ Or, you can make your own 'getprices' script. It should accept 3-4+arguments:++ * ISO code for the base currency+ * ISO code for the commodity to be priced+ * ISO start date+ * optional ISO end date (default: today)+++File: hledger.info, Node: import, Prev: get, Up: Data entry commands++8.3 import+==========++Import new transactions from one or more data files to the main journal.+Or with no arguments, import from the rules files in 'rules/'.++Flags:+ -g --get fetch new data first by running the get command+ --catchup just mark all transactions as already imported+ --dry-run just show the transactions to be imported+ --layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 - right-align amounts, as in hledger 1+ COL - align decimal marks at column COL+ (default: 53)++ This command detects new transactions in one or more data files+specified as arguments, and appends them to the main journal.++ You can import from any input file format hledger supports, but+CSV/SSV/TSV files, downloaded from financial institutions, are the most+common import source.++ The import destination is the default journal file, or another+specified in the usual way with '$LEDGER_FILE' or '-f/--file'. It+should be in journal format.++ Before writing anything, 'import' checks that the journal will still+be readable with the new transactions added, as the next read with the+same options will check it (eg balance assertions must pass, lots must+be valid, and with '--strict', the strict checks must pass). If not, it+shows the error and imports nothing (and updates no '.latest' files). A+dry run does this check too.++ Examples:++$ hledger import bank1-checking.csv bank1-savings.csv++$ hledger import *.csv++* Menu:++* Default import sources::+* Fetching new data first::+* Import dry run::+* Overlap detection::+* First import::+* Importing balance assignments::+* Import and commodity styles::+* Import archiving::+* Import special cases::+++File: hledger.info, Node: Default import sources, Next: Fetching new data first, Up: import++8.3.1 Default import sources+----------------------------++If 'import' is run with no file arguments, it looks in the journal's+'rules/' directory (next to the main journal file) and imports from+every '.rules' file found there, in alphabetical order. Files whose+name begins with '.' or '_' are skipped: the '_' prefix is for rules+files that are either disabled, or shared/common rules 'include'd by+other rules files and not meant to be read directly.++ So a typical setup might be:++~/finance/2026.journal+~/finance/rules/bank1-checking.rules+~/finance/rules/bank1-savings.rules+~/finance/rules/_common.rules # included by others, not read directly+~/finance/rules/_brokerage.rules # disabled++ and 'hledger import' reads 'bank1-checking.rules' then+'bank1-savings.rules'.++ If the 'rules/' directory does not exist or contains no usable+'.rules' files, import reports an error.+++File: hledger.info, Node: Fetching new data first, Next: Import dry run, Prev: Default import sources, Up: import++8.3.2 Fetching new data first+-----------------------------++With '-g/--get', 'import' runs the 'get' command first, which runs your+'data/getdata' and 'prices/getprices' scripts (if any) to download new+transaction and price data. The import then proceeds normally, with the+new transaction data (if any) readable by your rules files' 'source'+rules.+++File: hledger.info, Node: Import dry run, Next: Overlap detection, Prev: Fetching new data first, Up: import++8.3.3 Import dry run+--------------------++It's useful to preview the import by running first with '--dry-run', to+sanity check the range of dates being imported, and to check the effect+of your conversion rules if converting from CSV. Eg:++$ hledger import bank.csv --dry-run++ A dry run archives no data files and updates no '.latest' files.+With '-g', the 'get' command does a dry run too. But 'source' rules'+data cleaning and data generating commands do run, since their output is+needed for the preview; so these should be safe to repeat.++ The dry run output is valid journal format, so hledger can re-parse+it. If the output is large, you could show just the uncategorised+transactions like so:++$ hledger import --dry-run bank.csv | hledger -f- -I print unknown++ You could also run this repeatedly to see the effect of edits to your+conversion rules:++$ watchexec -- "hledger import --dry-run bank.csv | hledger -f- -I print unknown"++ Once the conversion and dates look good enough to import to your+journal, perhaps with some manual fixups to follow, you would do the+actual import:++$ hledger import bank.csv+++File: hledger.info, Node: Overlap detection, Next: First import, Prev: Import dry run, Up: import++8.3.4 Overlap detection+-----------------------++Reading CSV files is built in to hledger, and not specific to 'import';+so you could also import by doing 'hledger -f bank.csv print+>>$LEDGER_FILE'.++ But 'import' is easier and provides some advantages. The main one is+that it avoids re-importing transactions it has seen on previous runs.+This means you don't have to worry about overlapping data in successive+downloads of your bank CSV; just download and 'import' as often as you+like, and only the new transactions will be imported each time.++ We don't call this "deduplication", as it's generally not possible to+reliably detect duplicates in bank CSV. Instead, 'import' remembers the+latest date processed previously in each CSV file (saving it in a hidden+file), and skips any records prior to that date. This works well for+most real-world CSV, where:++ 1. the data file name is stable (does not change) across imports+ 2. the item dates are stable across imports+ 3. the order of same-date items is stable across imports+ 4. the newest items have the newest dates++ (Occasional violations of 2-4 are often harmless; you can reduce the+chance of disruption by downloading and importing more often.)++ Overlap detection is automatic, and shouldn't require much attention+from you, except perhaps at first import (see below). But here's how it+works:++ * For each 'FILE' being imported from:++ 1. hledger reads a file named '.latest.FILE' file in the same+ directory, if any. This file contains the latest record date+ previously imported from FILE, in YYYY-MM-DD format. If+ multiple records with that date were imported, the date is+ repeated on N lines.++ 2. hledger reads records from FILE. If a latest date was found in+ step 1, any records before that date, and the first N records+ on that date, are skipped.++ * After a successful import from all FILEs, without error and without+ '--dry-run', hledger updates each FILE's '.latest.FILE' for next+ time.++ If this goes wrong, it's relatively easy to repair:++ * You'll notice it before import when you preview with 'import+ --dry-run'.+ * Or after import when you try to reconcile your hledger account+ balances with your bank.+ * 'hledger print -f FILE.csv' will show all recently downloaded+ transactions. Compare these with your journal. Copy/paste if+ needed.+ * Update your conversion rules and print again, if needed.+ * You can manually update or remove the .latest file, or use 'import+ --catchup FILE'.+ * Download and import more often, eg twice a week, at least while you+ are learning. It's easier to review and troubleshoot when there+ are fewer transactions.+++File: hledger.info, Node: First import, Next: Importing balance assignments, Prev: Overlap detection, Up: import++8.3.5 First import+------------------++The first time you import from a file, when no corresponding .latest+file has been created yet, all of the records will be imported.++ But perhaps you have been entering the data manually, so you know+that all of these transactions are already recorded in the journal. In+this case you can run 'hledger import --catchup' once. This will create+a .latest file containing the latest CSV record date, so that none of+those records will be re-imported.++ Or, if you know that some but not all of the transactions are in the+journal, you can create the .latest file yourself. Eg, let's say you+previously recorded foobank transactions up to 2024-10-31 in the+journal. Then in the directory where you'll be saving 'foobank.csv',+you would create a '.latest.foobank.csv' file containing++2024-10-31++ Or if you had three foobank transactions recorded with that date, you+would repeat the date that many times:++2024-10-31+2024-10-31+2024-10-31++ Then 'hledger import foobank.csv [--dry-run]' will import only the+newer records.+++File: hledger.info, Node: Importing balance assignments, Next: Import and commodity styles, Prev: First import, Up: import++8.3.6 Importing balance assignments+-----------------------------------++Journal entries added by import will have all posting amounts made+explicit (like 'print -x').++ This means that any balance assignments in the imported entries would+need to be evaluated. But this generally isn't possible, as the main+file's account balances are not visible during import. So try to avoid+generating balance assignments with your CSV rules, or importing from a+journal that contains balance assignments. (Balance assignments are+best avoided anyway.)++ But if you must use them, eg because your CSV includes only balances:+you can import with 'print', which leaves implicit amounts implicit.+('print' can also do overlap detection like import, with the '--new'+flag):++$ hledger print --new -f bank.csv >> $LEDGER_FILE++ (If you think 'import' should preserve implicit balances, please test+that and send a pull request.)+++File: hledger.info, Node: Import and commodity styles, Next: Import archiving, Prev: Importing balance assignments, Up: import++8.3.7 Import and commodity styles+---------------------------------++Amounts in entries added by import will be formatted according to the+journal's canonical commodity styles, as declared by 'commodity'+directives or inferred from the journal's amounts.++ Related: CSV > Amount decimal places.+++File: hledger.info, Node: Import archiving, Next: Import special cases, Prev: Import and commodity styles, Up: import++8.3.8 Import archiving+----------------------++When importing from a CSV rules file ('hledger import bank.rules'), you+can use the archive rule to enable automatic archiving of the data file.++ After a successful import, the data file specified by 'source' will+be moved (or data generated by a command will be saved) to an archive+directory. This can be useful for troubleshooting, detecting variations+in your banks' CSV data, regenerating entries with improved rules, etc.++ The archive directory is 'data/archive/', next to the main journal+file, auto-created. The archive file name will be similar to the rules+file, with a date added: the original data file's modification date, or+today's date if the data was command-generated.++ The 'archive' rule also causes 'import' to handle 'source' glob+patterns differently: when there are multiple matched files, it will+pick the oldest, not the newest.+++File: hledger.info, Node: Import special cases, Prev: Import archiving, Up: import++8.3.9 Import special cases+--------------------------++* Menu:++* Multiple journals in the same directory::+* Import configurations to avoid::+* Deduplication::+* Varying file name::+* Multiple versions::+++File: hledger.info, Node: Multiple journals in the same directory, Next: Import configurations to avoid, Up: Import special cases++8.3.9.1 Multiple journals in the same directory+...............................................++You might want to keep each journal you are importing to in its own+directory. That way, each will have its own 'rules/', 'data/', and+'data/archive/' directories (if those are used).++ Otherwise, imports to the same-directory journals will potentially+use the same 'rules/', 'data/' and 'data/archive/' directories+(depending on commands and rules configuration). This is not+necessarily a problem; it might even be desirable in some cases. But+see below:+++File: hledger.info, Node: Import configurations to avoid, Next: Deduplication, Prev: Multiple journals in the same directory, Up: Import special cases++8.3.9.2 Import configurations to avoid+......................................++A few unusual workflows which you should generally avoid:++ * Don't import from one input file to different journals. The+ imports' overlap detection would overwrite the same '.latest.FILE'+ state file. (In effect, the journals would compete for the new+ records.)++ * Don't import from multiple data files on the same day, reusing the+ same rules file for all, with 'archive' enabled. The archived file+ names in 'data/archive/' would clash, causing some archives to be+ overwritten.++ * Don't do argument-less 'hledger import' to more than one journal in+ the same directory. That would read from the same files in+ 'rules/', potentially disrupting both overlap detection and+ archiving.+++File: hledger.info, Node: Deduplication, Next: Varying file name, Prev: Import configurations to avoid, Up: Import special cases++8.3.9.3 Deduplication+.....................++Here are two kinds of "deduplication" which 'import' does not handle+(and should not, because these can happen legitimately in financial+data):++ * Two or more of the new CSV records are identical, and generate+ identical new journal entries.+ * A new CSV record generates a journal entry identical to one(s)+ already in the journal.+++File: hledger.info, Node: Varying file name, Next: Multiple versions, Prev: Deduplication, Up: Import special cases++8.3.9.4 Varying file name+.........................++If you have a download whose file name varies, you could rename it to a+fixed name after each download. Or you could use a CSV 'source' rule+with a suitable glob pattern, and import from the .rules file.+++File: hledger.info, Node: Multiple versions, Prev: Varying file name, Up: Import special cases++8.3.9.5 Multiple versions+.........................++Say you download 'bank.csv', import it, but forget to delete it from+your downloads folder. The next time you download it, your web browser+will save it as (eg) 'bank (2).csv'. The source rule's glob patterns+are for just this situation: instead of specifying 'source bank.csv',+specify 'source bank*.csv'. Then 'hledger -f bank.rules CMD' or+'hledger import bank.rules' will automatically pick the newest matched+file ('bank (2).csv').++ Alternately, what if you download, but forget to import or delete,+then download again ? Now each of 'bank.csv' and 'bank (2).csv' might+contain data that's not in the other, and not in your journal. In this+case, it's best to import each of them in turn, oldest first (otherwise,+overlap detection could cause new records to be skipped). Enabling+import archiving ensures this. Then 'hledger import bank.rules; hledger+import bank.rules' will import and archive first 'bank.csv', then 'bank+(2).csv'.+++File: hledger.info, Node: Report commands, Next: Maintenance commands, Prev: Data entry commands, Up: Top++9 Report commands+*****************++* Menu:++* accounts::+* activity::+* aregister::+* balance::+* balancesheet::+* balancesheetequity::+* cashflow::+* codes::+* commodities::+* descriptions::+* files::+* holdings::+* incomestatement::+* notes::+* payees::+* prices::+* print::+* register::+* roi::+* stats::+* tags::+* transactions::+++File: hledger.info, Node: accounts, Next: activity, Up: Report commands++9.1 accounts+============++(acc)++ List the account names used or declared in the journal.++Flags:+ -u --used list accounts used+ -d --declared list accounts declared+ --undeclared list accounts used but not declared+ --unused list accounts declared but not used+ --find list the first account matched by the first+ argument (a case-insensitive infix regexp)+ --directives show as account directives, for use in journals+ --locations also show where accounts were declared, or first+ used+ --types also show account types when known+ --show-aliases also show account aliases declared with alias:+ tags+ -l --flat list/tree mode: show accounts as a flat list+ (default)+ -t --tree list/tree mode: show accounts as a tree+ --drop=N flat mode: omit N leading account name parts++ This command lists account names - all of them by default, or just+the ones which have been used in transactions ('-u/--used'), or declared+with 'account' directives ('-d/--declared'), or used but not declared+('--undeclared'), or declared but not used ('--unused'), or just the+first one matched by a pattern ('--find', returning a non-zero exit code+if it fails).++ You can add query arguments to select a subset of transactions or+accounts. Note that transaction-specific query terms like 'date:' will+exclude declared-but-unused accounts, which don't have that field.++ With '--directives', it shows valid account directives which could be+pasted into a journal file, including any account aliases as 'alias:'+tags. This is useful together with '--undeclared' when updating your+account declarations to satisfy 'hledger check accounts'.++ With '--locations', it also shows the file and line number of each+account's declaration, if any, and the account's overall declaration+order; these may be useful when troubleshooting account display order.+For an undeclared account, it shows where the account was first used+(posted to), if anywhere.++ With '--types', it also shows each account's type, if it's known.+(See Declaring accounts > Account types.)++ With '--show-aliases', it also shows each account's aliases, declared+with 'alias:' tags. (Aliases from 'alias' directives or '--alias'+options are not shown.) Also, account names in the query will match+aliases too, so eg 'hledger accounts --show-aliases chk' shows the+account(s) with an alias containing 'chk'.++ It shows a flat list by default. With '--tree', it uses indentation+to show the account hierarchy. In flat mode you can add '--drop N' to+omit the first few account name components. Account names can be+depth-clipped with 'depth:N' or '--depth N' or '-N'.++ Examples:++$ hledger accounts+assets:bank:checking+assets:bank:saving+assets:cash+expenses:food+expenses:supplies+income:gifts+income:salary+liabilities:debts++$ hledger accounts --undeclared --directives >> $LEDGER_FILE+$ hledger check accounts+++File: hledger.info, Node: activity, Next: aregister, Prev: accounts, Up: Report commands++9.2 activity+============++Show a bar chart of transaction counts per week, or other report+interval.++Flags:+ -O --output-format=FMT select the output format. Supported formats:+ txt, svg, html, csv, tsv, json.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ --view write output to FILE, or to view.FMT in hledger's+ cache directory, and open it in the system's+ default viewer for its format (eg a web browser for+ html). The default format is html.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)+ --txns count transactions, showing just the total+ (default)+ --postings count postings, showing each account's count+ -S --sort-amount with --postings, sort accounts by posting count,+ largest first+ -T --total show the total count, below the chart+ -A --average show the average count per period, below the+ chart (and as a line in SVG charts)++ The activity command shows how many transactions there are in each+week (or with a report interval, each day, month, quarter etc.), as a+bar chart. Each transaction is one character, unless there are too many+to fit, when the bars are scaled down. With query arguments, it counts+only the transactions which have at least one matched posting.++ Or with '--postings', it shows how many postings there are in each+period, with each account's postings stacked in its own colour. With+query arguments, it counts only the matched postings. This is a+shortcut for 'balance --count --chart', with a weekly interval by+default, so it can show charts in all the same ways: eg with '-1' or+other depth limit to show less detail, '-0' to show just the total+count, without the accounts' detail, '-S'/'--sort-amount' to show the+accounts with most postings first. (Transaction counts show just the+total, since a transaction's postings can be in several accounts.)++ '--txns' selects transaction counts explicitly; if both '--txns' and+'--postings' are given, the last one wins.++ Both kinds of chart can be shown in the usual ways, eg with+'-w'/'--width' to set the width, '-T'/'--total' and '-A'/'--average' to+show the total count and the average count per period below the chart+(in graphical charts, the average is also drawn as a dashed line), or+'-o FILE.svg' (or '-O svg') for a graphical chart.++ Examples:++$ hledger activity -M -T -A -w 40+Transaction counts in 2008:++Jan 1 █+Feb 0+Mar 0+Apr 0+May 0+Jun 3 ███+Jul 0+Aug 0+Sep 0+Oct 0+Nov 0+Dec 1 █++Total 5, Average 0.4++$ hledger activity -M --postings -1 -w 40+Posting counts in 2008:++▓ assets █ expenses ░ income+▒ liabilities++Jan 2 ▓░+Feb 0+Mar 0+Apr 0+May 0+Jun 7 ▓▓▓▓██░+Jul 0+Aug 0+Sep 0+Oct 0+Nov 0+Dec 2 ▓▒+++File: hledger.info, Node: aregister, Next: balance, Prev: activity, Up: Report commands++9.3 aregister+=============++(areg)++ Show the transactions and running balances in one account, with one+entry per transaction.++Flags:+ --txn-dates filter strictly by transaction date, not posting+ date. Warning: this can show a wrong running+ balance.+ --no-elide don't show only 2 commodities per amount+ --cumulative accumulation mode: show running total from report+ start date+ -H --historical accumulation mode: show historical running+ total/balance (includes postings before report+ start date) (default)+ -A --average show running average of transaction amounts+ instead of balance (implies --empty and, unless -H+ is used, --cumulative)+ -r --related show the other accounts in each transaction+ (default)+ --matched show the matched accounts (this account or its+ subaccounts) instead+ --invert display all amounts with reversed sign+ --drop=N omit N leading account name parts+ --heading=YN show heading row above table: yes (default) or no+ -w --width=N set output width (default: terminal width). -wN,M+ sets description width as well.+ --align-all guarantee alignment across all lines (slower)+ -O --output-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ --view write output to FILE, or to view.FMT in hledger's+ cache directory, and open it in the system's+ default viewer for its format (eg a web browser for+ html). The default format is html.+ --chart[=net,SCALE] show a chart: instead of the table (txt), above+ it (html), or as data (csv, tsv, json). net: also+ draw the net total (a line, or marks in text+ charts). SCALE: the amount that fills the chart (eg+ 1000 or 1000 USD; one per commodity), for+ comparable charts.++ 'aregister' shows the overall transactions affecting a particular+account (and any subaccounts). Each report line represents one+transaction in this account. Transactions before the report start date+are included in the running balance ('--historical' mode is the+default). You can suppress this behaviour using the '--cumulative'+option.++ This is a more "real world", bank-like view than the 'register'+command (which shows individual postings, possibly from multiple+accounts, not necessarily in historical mode). As a quick rule of+thumb:++ * 'aregister' is best when reconciling real-world asset/liability+ accounts+ * 'register' is best when reviewing individual revenues/expenses.++ Note this command's non-standard, and required, first argument; it+specifies the account whose register will be shown. You can write the+account's name, or (to save typing) a case-insensitive infix regular+expression matching the name, which selects the alphabetically first+matched account. (For example, if you have 'assets:personal checking'+and 'assets:business checking', 'hledger areg checking' would select+'assets:business checking'.)++ Transactions involving subaccounts of this account will also be+shown. 'aregister' ignores depth limits, so its final total will always+match a historical balance report with similar arguments.++ Any additional arguments are standard query arguments, which will+limit the transactions shown. Note some queries will disturb the+running balance, causing it to be different from the account's+real-world running balance.++ An example: this shows the transactions and historical running+balance during july, in the first account whose name contains+"checking":++$ hledger areg checking date:jul++ Each 'aregister' line item shows:++ * the transaction's date (or the relevant posting's date if+ different, see below)+ * the names of all the other account(s) involved in this transaction+ (probably abbreviated)+ * the total change to this account's balance from this transaction+ * the account's historical running balance after this transaction.++ The account column normally shows the other accounts in each+transaction (this is also selectable with '-r/--related'). With+'--matched', it shows the matched accounts instead: this account, or the+subaccounts of it that were posted to. This is useful when the account+has subaccounts, eg:++$ hledger areg expenses --matched++ shows which expense categories each transaction touched. Any+additional query arguments also narrow the matched accounts shown. The+amounts and running balance are the same in both modes.++ Transactions making a net change of zero are not shown by default;+add the '-E/--empty' flag to show them.++ The '-A/--average' flag shows the running average change per+transaction, instead of the running balance, so the last number shown is+the average for the whole report period. It implies '--empty', since+zero-change transactions also affect the average. Unlike aregister's+other reports, it is not historical by default; add '-H' to include the+transactions before the report start date in the average. Like+'register -A', it works best with a single commodity.++ For performance reasons, column widths are chosen based on the first+1000 lines; this means unusually wide values in later lines can cause+visual discontinuities as column widths are adjusted. If you want to+ensure perfect alignment, at the cost of more time and memory, use the+'--align-all' flag.++ By default, 'aregister' shows a heading above the data. However,+when reporting in a language different from English, it is easier to+omit this heading and prepend your own one. For this purpose, use the+'--heading=no' option.++ This command also supports the output destination and output format+options. The output formats supported are 'txt', 'csv', 'tsv', 'html',+'fods' and 'json'.++ With '--chart', or with 'svg' output ('-o FILE.svg'), it shows a+chart of the account's balance (or running total or average) over time+instead. A text chart has a row per transaction (for a row per period+instead, use a balance report with a report interval and '-H'). An SVG+chart draws the balance as a line on a time scale. With '--chart -O+csv' (or tsv or json) it shows the chart's data. See also Balance+charts.++* Menu:++* aregister and posting dates::+++File: hledger.info, Node: aregister and posting dates, Up: aregister++9.3.1 aregister and posting dates+---------------------------------++aregister always shows one entry (and one date and amount) per+transaction. (With a single commodity, this means line = one+transaction. But multi-commodity amounts will be shown with one line+per commodity.) But sometimes transactions have postings with different+dates. Also, not all of a transaction's postings may be within the+report period. To resolve this, aregister shows the earliest of the+transaction's date and posting dates that is in-period, and the sum of+the in-period postings. In other words it will show a combined line+item with just the earliest date, and the running balance will+(temporarily, until the transaction's last posting) be inaccurate. Use+'register -H' if you need to see the individual postings.++ There is also a '--txn-dates' flag, which filters strictly by+transaction date, ignoring posting dates. This too can cause an+inaccurate running balance.+++File: hledger.info, Node: balance, Next: balancesheet, Prev: aregister, Up: Report commands++9.4 balance+===========++(bal)++ Show accounts with some kind of summed numeric data: balance changes+per period, end balances on period end dates, simple capital gains,+budget goal performance, etc.++Flags:+ --sum calculation mode: show sum of posting amounts+ (default)+ --valuechange calculation mode: show total change of value+ of period-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ --gain calculation mode: show capital gain/loss+ (historical balance value minus cost basis, or+ transacted cost where there is none)+ --budget[=DESCPAT] calculation mode: show sum of posting amounts+ together with budget goals defined by periodic+ transactions. With a DESCPAT argument (must be+ separated by = not space),+ use only periodic transactions with matching+ description+ (case insensitive substring match).+ --count calculation mode: show the count of postings+ --change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports, default)+ --cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. -b/--begin) to+ column end+ -H --historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date)+ -l --flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth-clipped.+ -t --tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ --drop=N in list mode, omit N leading account name+ parts+ --declared include non-parent declared accounts (best+ used with -E)+ -A --average show a row average column (in multicolumn+ reports)+ -T --row-total show a row total column (in multicolumn+ reports)+ --summary-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ -N --no-total omit the final total row+ --no-elide in tree mode, don't squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without -E)+ --full-names in tree mode, show full account names instead+ of indented leaf names+ --format=FORMATSTR use this custom line format (in simple+ reports)+ -S --sort-amount sort by amount instead of account code/name+ (in flat mode). With multiple columns, sorts by+ the row total, or by row average if that is+ displayed.+ -% --percent express values in percentage of each column's+ total+ -r --related show the other accounts transacted with,+ instead+ --invert display all amounts with reversed sign+ --transpose switch rows and columns (use vertical time+ axis); repeat to cancel+ --layout=ARG how to lay out multi-commodity amounts and the+ overall table:+ 'wide[,W]': commodities on same line, up to W+ wide+ 'tall' : commodities on separate lines+ 'bare' : commodity symbols in a separate+ column+ 'tidy' : each data field in its own column+ --base-url=URLPREFIX in html output, generate links to hledger-web,+ with this prefix. (Usually the base url shown by+ hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, fods, svg.+ -o --output-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ --view write output to FILE, or to view.FMT in+ hledger's cache directory, and open it in the+ system's default viewer for its format (eg a web+ browser for html). The default format is html.+ --chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: grouped (a bar per account type, side by+ side). net: also draw the net total (a line, or+ marks in text charts). SCALE: the amount that+ fills the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)++ 'balance' is one of hledger's oldest and most versatile commands, for+listing account balances, balance changes, values, value changes and+more, during one time period or many. Generally it shows a table, with+rows representing accounts, and columns representing periods.++ Note there are some variants of the 'balance' command with convenient+defaults, which are simpler to use: 'balancesheet',+'balancesheetequity', 'cashflow' and 'incomestatement'. When you need+more control, then use 'balance'.++* Menu:++* balance features::+* Simple balance report::+* Balance report line format::+* Filtered balance report::+* List or tree mode::+* Depth limiting::+* Dropping top-level accounts::+* Showing declared accounts::+* Sorting by amount::+* Percentages::+* Multi-period balance report::+* Balance change end balance::+* Balance report modes::+* Budget report::+* Balance report layout::+* Balance report output::+* Balance charts::+* Some useful balance reports::+++File: hledger.info, Node: balance features, Next: Simple balance report, Up: balance++9.4.1 balance features+----------------------++Here's a quick overview of the 'balance' command's features, followed by+more detailed descriptions and examples. Many of these work with the+other balance-like commands as well ('bs', 'cf', 'is'..).++ 'balance' can show..++ * accounts as a list ('-l') or a tree ('-t')+ * optionally depth-limited ('-[1-9]')+ * sorted by declaration order and name, or by amount++ ..and their..++ * balance changes (the default)+ * or actual and planned balance changes ('--budget')+ * or value of balance changes ('-V')+ * or change of balance values ('--valuechange')+ * or capital gain/loss ('--gain')+ * or balance changes from sibling postings ('--related'/'-r')+ * or postings count ('--count')++ ..in..++ * one time period (the whole journal period by default)+ * or multiple periods ('-D', '-W', '-M', '-Q', '-Y', '-p INTERVAL')++ ..either..++ * per period (the default)+ * or accumulated since report start date ('--cumulative')+ * or accumulated since account creation ('--historical/-H')++ ..possibly converted to..++ * cost ('--value=cost[,COMM]'/'--cost'/'-B')+ * or market value, as of transaction dates ('--value=then[,COMM]')+ * or at period ends ('--value=end[,COMM]')+ * or now ('--value=now')+ * or at some other date ('--value=YYYY-MM-DD')++ ..with..++ * totals ('-T'), averages ('-A'), percentages ('-%'), inverted sign+ ('--invert')+ * rows and columns swapped ('--transpose')+ * another field used as account name ('--pivot')+ * custom-formatted line items (single-period reports only)+ ('--format')+ * commodities displayed on the same line or multiple lines+ ('--layout')+ * a chart instead of a table ('--chart')++ This command supports the output destination and output format+options, with output formats 'txt', 'csv', 'tsv', 'json', 'html',+'fods', and 'svg'. In 'txt' output in a colour-supporting terminal,+negative amounts are shown in red.+++File: hledger.info, Node: Simple balance report, Next: Balance report line format, Prev: balance features, Up: balance++9.4.2 Simple balance report+---------------------------++With no arguments, 'balance' shows a list of all accounts and their+change of balance - ie, the sum of posting amounts, both inflows and+outflows - during the entire period of the journal. ("Simple" here+means just one column of numbers, covering a single period. You can+also have multi-period reports, described later.)++ For real-world accounts, these numbers will normally be their end+balance at the end of the journal period; more on this below.++ Accounts are sorted by declaration order if any, and then+alphabetically by account name. For instance (using+examples/sample.journal):++$ hledger -f examples/sample.journal bal+ $1 assets:bank:saving+ $-2 assets:cash+ $1 expenses:food+ $1 expenses:supplies+ $-1 income:gifts+ $-1 income:salary+ $1 liabilities:debts+--------------------+ 0 ++ Accounts with a zero balance (and no non-zero subaccounts, in tree+mode - see below) are hidden by default. Use '-E/--empty' to show them+(revealing 'assets:bank:checking' here):++$ hledger -f examples/sample.journal bal -E+ 0 assets:bank:checking+ $1 assets:bank:saving+ $-2 assets:cash+ $1 expenses:food+ $1 expenses:supplies+ $-1 income:gifts+ $-1 income:salary+ $1 liabilities:debts+--------------------+ 0 ++ The total of the amounts displayed is shown as the last line, unless+'-N'/'--no-total' is used.+++File: hledger.info, Node: Balance report line format, Next: Filtered balance report, Prev: Simple balance report, Up: balance++9.4.3 Balance report line format+--------------------------------++For single-period balance reports displayed in the terminal (only), you+can use '--format FMT' to customise the format and content of each line.+Eg:++$ hledger -f examples/sample.journal balance --format "%20(account) %12(total)"+ assets $-1+ bank:saving $1+ cash $-2+ expenses $2+ food $1+ supplies $1+ income $-2+ gifts $-1+ salary $-1+ liabilities:debts $1+---------------------------------+ 0++ The FMT format string specifies the formatting applied to each+account/balance pair. It may contain any suitable text, with data+fields interpolated like so:++ %[MIN][.MAX](FIELDNAME)++ * MIN pads with spaces to at least this width (optional)++ * MAX truncates at this width (optional)++ * FIELDNAME must be enclosed in parentheses, and can be one of:++ * 'depth_spacer' - a number of spaces equal to the account's+ depth, or if MIN is specified, MIN * depth spaces.+ * 'account' - the account's name+ * 'total' - the account's balance/posted total, right justified++ Also, FMT can begin with an optional prefix to control how+multi-commodity amounts are rendered:++ * '%_' - render on multiple lines, bottom-aligned (the default)+ * '%^' - render on multiple lines, top-aligned+ * '%,' - render on one line, comma-separated++ There are some quirks. Eg in one-line mode, '%(depth_spacer)' has no+effect, instead '%(account)' has indentation built in. Experimentation+may be needed to get pleasing results.++ Some example formats:++ * '%(total)' - the account's total+ * '%-20.20(account)' - the account's name, left justified, padded to+ 20 characters and clipped at 20 characters+ * '%,%-50(account) %25(total)' - account name padded to 50+ characters, total padded to 20 characters, with multiple+ commodities rendered on one line+ * '%20(total) %2(depth_spacer)%-(account)' - the default format for+ the single-column balance report. The total field keeps this+ 20-character width as a minimum, but widens automatically when+ displayed amounts need more room.+++File: hledger.info, Node: Filtered balance report, Next: List or tree mode, Prev: Balance report line format, Up: balance++9.4.4 Filtered balance report+-----------------------------++You can show fewer accounts, a different time period, totals from+cleared transactions only, etc. by using query arguments or options to+limit the postings being matched. Eg:++$ hledger -f examples/sample.journal bal --cleared assets date:200806+ $-2 assets:cash+--------------------+ $-2 +++File: hledger.info, Node: List or tree mode, Next: Depth limiting, Prev: Filtered balance report, Up: balance++9.4.5 List or tree mode+-----------------------++By default, or with '-l/--flat', accounts are shown as a flat list with+their full names visible, as in the examples above.++ With '-t/--tree', the account hierarchy is shown, with subaccounts'+"leaf" names indented below their parent:++$ hledger -f examples/sample.journal balance+ $-1 assets+ $1 bank:saving+ $-2 cash+ $2 expenses+ $1 food+ $1 supplies+ $-2 income+ $-1 gifts+ $-1 salary+ $1 liabilities:debts+--------------------+ 0++ Notes:++ * "Boring" accounts are combined with their subaccount for more+ compact output, unless '--no-elide' is used. Boring accounts have+ no balance of their own and just one subaccount (eg 'assets:bank'+ and 'liabilities' above).++ * All balances shown are "inclusive", ie including the balances from+ all subaccounts. Note this means some repetition in the output,+ which requires explanation when sharing reports with+ non-plaintextaccounting-users. A tree mode report's final total is+ the sum of the top-level balances shown, not of all the balances+ shown.++ * Each group of sibling accounts (ie, under a common parent) is+ sorted separately.++ In list mode, '--no-elide' shows parent accounts as well, with their+exclusive balances. These are zero unless the parent has postings of+its own, so '-E/--empty' is usually also needed to make them visible.+Together, these flags guarantee a complete table of all posted-to+accounts and their parents, with full names:++$ hledger -f examples/sample.journal balance --no-elide -E+ 0 assets+ 0 assets:bank+ 0 assets:bank:checking+ $1 assets:bank:saving+ $-2 assets:cash+ 0 expenses+ $1 expenses:food+ $1 expenses:supplies+ 0 income+ $-1 income:gifts+ $-1 income:salary+ 0 liabilities+ $1 liabilities:debts+--------------------+ 0++ This can be useful eg when exporting to a spreadsheet which will look+up balances by account name.++ In tree mode, '--full-names' writes each account's full name instead+of indenting leaf names, while keeping tree mode's inclusive balances.+So '--tree --no-elide --full-names -E' shows the same complete table as+above, but with inclusive balances:++$ hledger -f examples/sample.journal balance --tree --no-elide --full-names -E+ $-1 assets+ $1 assets:bank+ 0 assets:bank:checking+ $1 assets:bank:saving+ $-2 assets:cash+ $2 expenses+ $1 expenses:food+ $1 expenses:supplies+ $-2 income+ $-1 income:gifts+ $-1 income:salary+ $1 liabilities+ $1 liabilities:debts+--------------------+ 0++ Note that in this variant, parent and subaccount balances overlap, so+(as in any tree mode report) the rows sum to more than the final total.+++File: hledger.info, Node: Depth limiting, Next: Dropping top-level accounts, Prev: List or tree mode, Up: balance++9.4.6 Depth limiting+--------------------++With a 'depth:NUM' query, or '--depth NUM' option, or just '-NUM' (eg:+'-3') balance reports will show accounts only to the specified depth,+hiding the deeper subaccounts. This can be useful for getting an+overview without too much detail.++ Account balances at the depth limit always include the balances from+any deeper subaccounts (even in list mode). Eg, limiting to depth 1:++$ hledger -f examples/sample.journal balance -1+ $-1 assets+ $2 expenses+ $-2 income+ $1 liabilities+--------------------+ 0 +++File: hledger.info, Node: Dropping top-level accounts, Next: Showing declared accounts, Prev: Depth limiting, Up: balance++9.4.7 Dropping top-level accounts+---------------------------------++You can also hide one or more top-level account name parts, using+'--drop NUM'. This can be useful for hiding repetitive top-level+account names:++$ hledger -f examples/sample.journal bal expenses --drop 1+ $1 food+ $1 supplies+--------------------+ $2 +++File: hledger.info, Node: Showing declared accounts, Next: Sorting by amount, Prev: Dropping top-level accounts, Up: balance++9.4.8 Showing declared accounts+-------------------------------++With '--declared', accounts which have been declared with an account+directive will be included in the balance report, even if they have no+transactions. (Since they will have a zero balance, you will also need+'-E/--empty' to see them.)++ More precisely, _leaf_ declared accounts (with no subaccounts) will+be included, since those are usually the more useful in reports.++ The idea of this is to be able to see a useful "complete" balance+report, even when you don't have transactions in all of your declared+accounts yet.+++File: hledger.info, Node: Sorting by amount, Next: Percentages, Prev: Showing declared accounts, Up: balance++9.4.9 Sorting by amount+-----------------------++With '-S/--sort-amount', accounts with the largest (most positive)+balances are shown first. Eg: 'hledger bal expenses -MAS' shows your+biggest averaged monthly expenses first. When more than one commodity+is present, they will be sorted by the alphabetically earliest commodity+first, and then by subsequent commodities (if an amount is missing a+commodity, it is treated as 0).++ Revenues and liability balances are typically negative, however, so+'-S' shows these in reverse order. To work around this, you can add+'--invert' to flip the signs. Or you could use one of the higher-level+balance reports ('bs', 'is'..), which flip the sign automatically (eg:+'hledger is -MAS').+++File: hledger.info, Node: Percentages, Next: Multi-period balance report, Prev: Sorting by amount, Up: balance++9.4.10 Percentages+------------------++With '-%/--percent', balance reports show each account's value expressed+as a percentage of the (column) total.++ Note it is not useful to calculate percentages if the amounts in a+column have mixed signs. In this case, make a separate report for each+sign, eg:++$ hledger bal -% amt:`>0`+$ hledger bal -% amt:`<0`++ Similarly, if the amounts in a column have mixed commodities, convert+them to one commodity with '-B', '-V', '-X' or '--value', or make a+separate report for each commodity:++$ hledger bal -% cur:\\$+$ hledger bal -% cur:€+++File: hledger.info, Node: Multi-period balance report, Next: Balance change end balance, Prev: Percentages, Up: balance++9.4.11 Multi-period balance report+----------------------------------++With a report interval (set by the '-D/--daily', '-W/--weekly',+'-M/--monthly', '-Q/--quarterly', '-Y/--yearly', or '-p/--period' flag),+'balance' shows a tabular report, with columns representing successive+time periods (and a title):++$ hledger -f examples/sample.journal bal --quarterly income expenses -E+Balance changes in 2008:++ || 2008q1 2008q2 2008q3 2008q4 +===================++=================================+ expenses:food || 0 $1 0 0 + expenses:supplies || 0 $1 0 0 + income:gifts || 0 $-1 0 0 + income:salary || $-1 0 0 0 +-------------------++---------------------------------+ || $-1 $1 0 0 ++ Notes:++ * The report's start/end dates will be expanded, if necessary, to+ fully encompass the displayed subperiods (so that the first and+ last subperiods have the same duration as the others).+ * Leading and trailing periods (columns) containing all zeroes are+ not shown, unless '-E/--empty' is used.+ * Accounts (rows) containing all zeroes are not shown, unless+ '-E/--empty' is used.+ * Amounts with many commodities are shown in abbreviated form, unless+ '--no-elide' is used.+ * Average and/or total columns can be added with the '-A/--average'+ and '-T/--row-total' flags.+ * The '--transpose' flag can be used to exchange rows and columns.+ Repeating it reverses its effect (an even number of '--transpose'+ flags has no effect).+ * The '--pivot FIELD' option causes a different transaction field to+ be used as "account name". See PIVOTING.+ * The '--summary-only' flag ('--summary' also works) hides all but+ the Total and Average columns (those should be enabled with+ '--row-total' and '-A/--average').++ Multi-period reports with many periods can be too wide for easy+viewing in the terminal. Here are some ways to handle that:++ * Hide the totals row with '-N/--no-total'+ * Filter to a single currency with 'cur:'+ * Convert to a single currency with '-V [--infer-market-price]'+ * Use a more compact layout like '--layout=bare'+ * Maximize the terminal window+ * Reduce the terminal's font size+ * View with a pager like less, eg: 'hledger bal -D --color=yes | less+ -RS'+ * Output as CSV and use a CSV viewer like visidata ('hledger bal -D+ -O csv | vd -f csv'), Emacs' csv-mode ('M-x csv-mode, C-c C-a'), or+ a spreadsheet ('hledger bal -D -o a.csv && open a.csv')+ * Output as HTML and view with a browser: 'hledger bal -D -o a.html+ && open a.html'+++File: hledger.info, Node: Balance change end balance, Next: Balance report modes, Prev: Multi-period balance report, Up: balance++9.4.12 Balance change, end balance+----------------------------------++It's important to be clear on the meaning of the numbers shown in+balance reports. Here is some terminology we use:++ A *_balance change_* is the net amount added to, or removed from, an+account during some period.++ An *_end balance_* is the amount accumulated in an account as of some+date (and some time, but hledger doesn't store that; assume end of day+in your timezone). It is the sum of previous balance changes.++ We call it a *_historical end balance_* if it includes all balance+changes since the account was created. For a real world account, this+means it will match the "historical record", eg the balances reported in+your bank statements or bank web UI. (If they are correct!)++ In general, balance changes are what you want to see when reviewing+revenues and expenses, and historical end balances are what you want to+see when reviewing or reconciling asset, liability and equity accounts.++ 'balance' shows balance changes by default. To see accurate+historical end balances:++ 1. Initialise account starting balances with an "opening balances"+ transaction (a transfer from equity to the account), unless the+ journal covers the account's full lifetime.++ 2. Include all of of the account's prior postings in the report, by+ not specifying a report start date, or by using the+ '-H/--historical' flag. ('-H' causes report start date to be+ ignored when summing postings.)+++File: hledger.info, Node: Balance report modes, Next: Budget report, Prev: Balance change end balance, Up: balance++9.4.13 Balance report modes+---------------------------++The balance command is quite flexible; here is the full detail on how to+control what it reports. If the following seems complicated, don't+worry - this is for advanced reporting, and it does take time and+experimentation to get familiar with all the report modes.++ There are three important option groups:++ hledger balance [CALCULATIONMODE] [ACCUMULATIONMODE] [VALUATIONMODE] ...++* Menu:++* Calculation mode::+* Accumulation mode::+* Valuation mode::+* Combining balance report modes::+++File: hledger.info, Node: Calculation mode, Next: Accumulation mode, Up: Balance report modes++9.4.13.1 Calculation mode+.........................++The basic calculation to perform for each table cell. It is one of:++ * '--sum' : sum the posting amounts (*default*)+ * '--budget' : sum the amounts, but also show the budget goal amount+ (for each account/period)+ * '--valuechange' : show the change in period-end historical balance+ values (caused by deposits, withdrawals, and/or market price+ fluctuations)+ * '--gain' : show capital gain/loss for each account: the current+ valued balance minus its cost. For lot-tracked commodities the+ cost is the cost basis of the units still held, so this is the+ unrealised gain. For other commodities it is the net of postings'+ transacted costs (acquisition costs minus disposal proceeds): where+ nothing has been sold this too is the unrealised gain, but once+ disposals exist the figure also includes the realised gain on the+ disposed units, so it is best read as "total gain since inception"+ (to separate realised and unrealised gains, track lots). Compare+ '--valuechange', which shows how much the value moved in a period,+ from price changes and from buying and selling. See Unrealised+ gains for examples.+ * '--count' : show the count of postings+++File: hledger.info, Node: Accumulation mode, Next: Valuation mode, Prev: Calculation mode, Up: Balance report modes++9.4.13.2 Accumulation mode+..........................++How amounts should accumulate across a report's subperiods/columns.+Another way to say it: which time period's postings should contribute to+each cell's calculation. It is one of:++ * '--change' : calculate with postings from column start to column+ end, ie "just this column". Typically used to see+ revenues/expenses. (*default for balance, cashflow,+ incomestatement*)++ * '--cumulative' : calculate with postings from report start to+ column end, ie "previous columns plus this column". Typically used+ to show changes accumulated since the report's start date. Not+ often used.++ * '--historical/-H' : calculate with postings from journal start to+ column end, ie "all postings from before report start date until+ this column's end". Typically used to see historical end balances+ of assets/liabilities/equity. (*default for balancesheet,+ balancesheetequity*)+++File: hledger.info, Node: Valuation mode, Next: Combining balance report modes, Prev: Accumulation mode, Up: Balance report modes++9.4.13.3 Valuation mode+.......................++Which kind of value or cost conversion should be applied, if any, before+displaying the report. See Cost reporting and Value reporting for more+about conversions.++ A valuation (or cost) mode can be selected with the -value option:++ * no conversion : don't convert to cost or value (*default*)+ * '--value=cost[,COMM]' : convert amounts to cost (then optionally to+ some other commodity)+ * '--value=then[,COMM]' : convert amounts to market value on+ transaction dates+ * '--value=end[,COMM]' : convert amounts to market value on period+ end date(s)+ (*default with '--valuechange', '--gain'*)+ * '--value=now[,COMM]' : convert amounts to market value on today's+ date+ * '--value=YYYY-MM-DD[,COMM]' : convert amounts to market value on+ another date++ or with the legacy -B/-V/-X options, which are equivalent and easier+to type:++ * '-B'/'--cost' : like -value=cost+ * '-V'/'--market' : like -value=end+ * '-X COMM'/'--exchange COMM' : like -value=end,COMM++ Note that -value can also convert to cost, as a convenience; but+actually -cost and -value are independent options, and could be used+together.+++File: hledger.info, Node: Combining balance report modes, Prev: Valuation mode, Up: Balance report modes++9.4.13.4 Combining balance report modes+.......................................++Most combinations of these modes produce reasonable reports. The+following restrictions are applied:++ * '--valuechange' implies '--value=end'+ * '--valuechange' makes '--change' the default when used with the+ 'balancesheet'/'balancesheetequity' commands+ * '--cumulative' or '--historical' disables '--row-total/-T'++ For reference, here is what the combinations of accumulation and+valuation show:++Valuation:>no valuation '--value= then' '--value= end' '--value=+Accumulation:v YYYY-MM-DD+ /now'+-----------------------------------------------------------------------------+'--change'change in sum of period-end DATE-value+ period posting-date value of of change in+ market values change in period+ in period period+'--cumulative'change from sum of period-end DATE-value+ report start to posting-date value of of change+ period end market values change from from report+ from report report start start to+ start to period to period end period end+ end+'--historicalchange from sum of period-end DATE-value+/-H' journal start posting-date value of of change+ to period end market values change from from journal+ (historical end from journal journal start start to+ balance) start to period to period end period end+ end+++File: hledger.info, Node: Budget report, Next: Balance report layout, Prev: Balance report modes, Up: balance++9.4.14 Budget report+--------------------++The 'balance --budget' report is like a regular balance report, but with+two main differences:++ * Budget goals and performance percentages are also shown, in+ brackets+ * Accounts which don't have budget goals are hidden by default.++ This is useful for comparing planned and actual income, expenses,+time usage, etc.++ Periodic transaction rules are used to define budget goals. For+example, here's a periodic rule defining monthly goals for bus travel+and food expenses:++;; Budget+~ monthly+ (expenses:bus) $30+ (expenses:food) $400++ After recording some actual expenses,++;; Two months worth of expenses+2017-11-01+ income $-1950+ expenses:bus $35+ expenses:food:groceries $310+ expenses:food:dining $42+ expenses:movies $38+ assets:bank:checking++2017-12-01+ income $-2100+ expenses:bus $53+ expenses:food:groceries $380+ expenses:food:dining $32+ expenses:gifts $100+ assets:bank:checking++ we can see a budget report like this:++$ hledger bal -M --budget+Budget performance in 2017-11-01..2017-12-31:++ || Nov Dec +===============++============================================+ <unbudgeted> || $-425 $-565 + expenses || $425 [ 99% of $430] $565 [131% of $430] + expenses:bus || $35 [117% of $30] $53 [177% of $30] + expenses:food || $352 [ 88% of $400] $412 [103% of $400] +---------------++--------------------------------------------+ || 0 [ 0% of $430] 0 [ 0% of $430] ++ This is "goal-based budgeting"; you define goals for accounts and+periods, often recurring, and hledger shows performance relative to the+goals. This contrasts with "envelope budgeting", which is more detailed+and strict - useful when cash is tight, but also quite a bit more work.+https://plaintextaccounting.org/Budgeting has more on this topic.++* Menu:++* Using the budget report::+* Budget date surprises::+* Selecting budget goals::+* Budgeting vs forecasting::+++File: hledger.info, Node: Using the budget report, Next: Budget date surprises, Up: Budget report++9.4.14.1 Using the budget report+................................++Historically this report has been confusing and fragile. hledger's+version should be relatively robust and intuitive, but you may still+find surprises. Here are more notes to help with learning and+troubleshooting.++ * In the above example, 'expenses:bus' and 'expenses:food' are shown+ because they have budget goals during the report period.++ * Their parent 'expenses' is also shown, with budget goals aggregated+ from the children.++ * The subaccounts 'expenses:food:groceries' and+ 'expenses:food:dining' are not shown since they have no budget goal+ of their own, but they contribute to 'expenses:food''s actual+ amount.++ * Unbudgeted accounts 'expenses:movies' and 'expenses:gifts' are also+ not shown, but they contribute to 'expenses''s actual amount.++ * The other unbudgeted accounts 'income' and 'assets:bank:checking'+ are grouped as '<unbudgeted>'.++ * '--depth' or 'depth:' can be used to limit report depth in the+ usual way (but will not reveal unbudgeted subaccounts).++ * Amounts are always inclusive of subaccounts (even in '-l/--list'+ mode).++ * Numbers displayed in a -budget report will not always agree with+ the totals, because of hidden unbudgeted accounts; this is normal.+ '-E/--empty' can be used to reveal the hidden accounts.++ * In the periodic rules used for setting budget goals, unbalanced+ postings are convenient.++ * You can filter budget reports with the usual queries, eg to focus+ on particular accounts. It's common to restrict them to just+ expenses. (The '<unbudgeted>' account is occasionally hard to+ exclude; this is because of date surprises, discussed below.)++ * Only the account, account type, depth, date and commodity parts of+ the query are applied to the budget goals; the other parts+ ('status:'/'-U'/'-P'/'-C', 'code:', 'desc:', 'payee:', 'note:',+ 'tag:', 'real:', 'amt:') select actual transactions and postings+ only. So eg '--budget --cleared' compares your cleared spending+ against the full budget goals.++ * When you have multiple currencies, you may want to convert them to+ one ('-X COMM --infer-market-prices') and/or show just one at a+ time ('cur:COMM'). If you do need to show multiple currencies at+ once, '--layout bare' can be helpful.++ * You can "roll over" amounts (actual and budgeted) to the next+ period with '--cumulative'.++ See also: https://hledger.org/budgeting.html.+++File: hledger.info, Node: Budget date surprises, Next: Selecting budget goals, Prev: Using the budget report, Up: Budget report++9.4.14.2 Budget date surprises+..............................++With small data, or when starting out, some of the generated budget goal+transaction dates might fall outside the report periods. Eg with the+following journal and report, the first period appears to have no+'expenses:food' budget. (Also the '<unbudgeted>' account should be+excluded by the 'expenses' query, but isn't.):++~ monthly in 2020+ (expenses:food) $500++2020-01-15+ expenses:food $400+ assets:checking++$ hledger bal --budget expenses+Budget performance in 2020-01-15:++ || 2020-01-15 +===============++====================+ <unbudgeted> || $400 + expenses:food || 0 [ 0% of $500] +---------------++--------------------+ || $400 [80% of $500] ++ In this case, the budget goal transactions are generated on first+days of of month (this can be seen with 'hledger print --forecast+tag:generated expenses'). Whereas the report period defaults to just+the 15th day of january (this can be seen from the report table's column+headings).++ To fix this kind of thing, be more explicit about the report period+(and/or the periodic rules' dates). In this case, adding '-b 2020' does+the trick.+++File: hledger.info, Node: Selecting budget goals, Next: Budgeting vs forecasting, Prev: Budget date surprises, Up: Budget report++9.4.14.3 Selecting budget goals+...............................++By default, the budget report uses all available periodic transaction+rules to generate goals. This includes rules with a different report+interval from your report. Eg if you have daily, weekly and monthly+periodic rules, all of these will contribute to the goals in a monthly+budget report.++ You can select a subset of periodic rules by providing an argument to+the '--budget' flag. '--budget=DESCPAT' will match all periodic rules+whose description contains DESCPAT, a case-insensitive substring (not a+regular expression or query). This means you can give your periodic+rules descriptions (remember that two spaces are needed between period+expression and description), and then select from multiple budgets+defined in your journal.+++File: hledger.info, Node: Budgeting vs forecasting, Prev: Selecting budget goals, Up: Budget report++9.4.14.4 Budgeting vs forecasting+.................................++'--forecast' and '--budget' both use the periodic transaction rules in+the journal to generate temporary transactions for reporting purposes.+However they are separate features - though you can use both at the same+time if you want. Here are some differences between them:++-forecast -budget+--------------------------------------------------------------------------+is a general option; it enables is a balance command option;+forecasting with all reports it selects the balance+ report's budget mode+generates visible transactions which generates invisible+appear in reports transactions which produce+ goal amounts+generates forecast transactions from generates budget goal+after the last regular transaction, to transactions throughout the+the end of the report period; or with report period, optionally+an argument '--forecast=PERIODEXPR' restricted by periods+generates them throughout the specified in the periodic+specified period, both optionally transaction rules+restricted by periods specified in the+periodic transaction rules+uses all periodic rules uses all periodic rules; or+ with an argument+ '--budget=DESCPAT' uses just+ the rules matched by DESCPAT+++File: hledger.info, Node: Balance report layout, Next: Balance report output, Prev: Budget report, Up: balance++9.4.15 Balance report layout+----------------------------++The '--layout' option affects how 'balance' and the other balance-like+commands show multi-commodity amounts and commodity symbols. It can+improve readability, for humans and/or machines (other software). It+has four possible values:++ * '--layout=wide[,WIDTH]': commodities are shown on a single line,+ optionally elided to WIDTH+ * '--layout=tall': each commodity is shown on a separate line+ * '--layout=bare': commodity symbols are in their own column, amounts+ are bare numbers+ * '--layout=barewide': commodities are shown on a single line, all in+ separate columns, amounts are bare numbers+ * '--layout=tidy': data is normalised to easily-consumed "tidy" form,+ with one row per data value. (This one is currently supported only+ by the 'balance' command.)++ Here are the '--layout' modes supported by each output format Only+CSV output supports all of them:++- txt csv html json sql+-------------------------------------------+wide Y Y Y+tall Y Y Y+bare Y Y Y+barewide Y Y Y+tidy Y++ Choice of layouts for budget reports is more restricted:++- txt csv html json sql+-------------------------------------------+wide Y Y Y+tall Y+bare Y Y Y+barewide Y Y+tidy++ Examples:++* Menu:++* Wide layout::+* Tall layout::+* Bare layout::+* Barewide layout::+* Tidy layout::+++File: hledger.info, Node: Wide layout, Next: Tall layout, Up: Balance report layout++9.4.15.1 Wide layout+....................++With many commodities, reports can be very wide:++$ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -T -Y --layout=wide+Balance changes in 2012-01-01..2014-12-31:++ || 2012 2013 2014 Total +==================++====================================================================================================================================================================================================================+ Assets:US:ETrade || 10.00 ITOT, 337.18 USD, 12.00 VEA, 106.00 VHT 70.00 GLD, 18.00 ITOT, -98.12 USD, 10.00 VEA, 18.00 VHT -11.00 ITOT, 4881.44 USD, 14.00 VEA, 170.00 VHT 70.00 GLD, 17.00 ITOT, 5120.50 USD, 36.00 VEA, 294.00 VHT +------------------++--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ || 10.00 ITOT, 337.18 USD, 12.00 VEA, 106.00 VHT 70.00 GLD, 18.00 ITOT, -98.12 USD, 10.00 VEA, 18.00 VHT -11.00 ITOT, 4881.44 USD, 14.00 VEA, 170.00 VHT 70.00 GLD, 17.00 ITOT, 5120.50 USD, 36.00 VEA, 294.00 VHT ++ A width limit reduces the width, but some commodities will be hidden:++$ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -T -Y --layout=wide,32+Balance changes in 2012-01-01..2014-12-31:++ || 2012 2013 2014 Total +==================++===========================================================================================================================+ Assets:US:ETrade || 10.00 ITOT, 337.18 USD, 2 more.. 70.00 GLD, 18.00 ITOT, 3 more.. -11.00 ITOT, 3 more.. 70.00 GLD, 17.00 ITOT, 3 more.. +------------------++---------------------------------------------------------------------------------------------------------------------------+ || 10.00 ITOT, 337.18 USD, 2 more.. 70.00 GLD, 18.00 ITOT, 3 more.. -11.00 ITOT, 3 more.. 70.00 GLD, 17.00 ITOT, 3 more.. +++File: hledger.info, Node: Tall layout, Next: Bare layout, Prev: Wide layout, Up: Balance report layout++9.4.15.2 Tall layout+....................++Each commodity gets a new line (may be different in each column), and+account names are repeated:++$ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -T -Y --layout=tall+Balance changes in 2012-01-01..2014-12-31:++ || 2012 2013 2014 Total +==================++==================================================+ Assets:US:ETrade || 10.00 ITOT 70.00 GLD -11.00 ITOT 70.00 GLD + Assets:US:ETrade || 337.18 USD 18.00 ITOT 4881.44 USD 17.00 ITOT + Assets:US:ETrade || 12.00 VEA -98.12 USD 14.00 VEA 5120.50 USD + Assets:US:ETrade || 106.00 VHT 10.00 VEA 170.00 VHT 36.00 VEA + Assets:US:ETrade || 18.00 VHT 294.00 VHT +------------------++--------------------------------------------------+ || 10.00 ITOT 70.00 GLD -11.00 ITOT 70.00 GLD + || 337.18 USD 18.00 ITOT 4881.44 USD 17.00 ITOT + || 12.00 VEA -98.12 USD 14.00 VEA 5120.50 USD + || 106.00 VHT 10.00 VEA 170.00 VHT 36.00 VEA + || 18.00 VHT 294.00 VHT +++File: hledger.info, Node: Bare layout, Next: Barewide layout, Prev: Tall layout, Up: Balance report layout++9.4.15.3 Bare layout+....................++Commodity symbols are kept in one column, each commodity has its own+row, amounts are bare numbers, account names are repeated:++$ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -T -Y --layout=bare+Balance changes in 2012-01-01..2014-12-31:++ || Commodity 2012 2013 2014 Total +==================++=============================================+ Assets:US:ETrade || GLD 0 70.00 0 70.00 + Assets:US:ETrade || ITOT 10.00 18.00 -11.00 17.00 + Assets:US:ETrade || USD 337.18 -98.12 4881.44 5120.50 + Assets:US:ETrade || VEA 12.00 10.00 14.00 36.00 + Assets:US:ETrade || VHT 106.00 18.00 170.00 294.00 +------------------++---------------------------------------------+ || GLD 0 70.00 0 70.00 + || ITOT 10.00 18.00 -11.00 17.00 + || USD 337.18 -98.12 4881.44 5120.50 + || VEA 12.00 10.00 14.00 36.00 + || VHT 106.00 18.00 170.00 294.00 ++ Bare layout also affects CSV output, which is useful for producing+data that is easier to consume, eg for making charts:++$ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -O csv --layout=bare+"account","commodity","balance"+"Assets:US:ETrade","GLD","70.00"+"Assets:US:ETrade","ITOT","17.00"+"Assets:US:ETrade","USD","5120.50"+"Assets:US:ETrade","VEA","36.00"+"Assets:US:ETrade","VHT","294.00"+"Total:","GLD","70.00"+"Total:","ITOT","17.00"+"Total:","USD","5120.50"+"Total:","VEA","36.00"+"Total:","VHT","294.00"++ Bare layout will sometimes display an extra row for the no-symbol+commodity, because of zero amounts (hledger treats zeroes as+commodity-less, usually). This can break 'hledger-bar' confusingly+(workaround: add a 'cur:' query to exclude the no-symbol row).+++File: hledger.info, Node: Barewide layout, Next: Tidy layout, Prev: Bare layout, Up: Balance report layout++9.4.15.4 Barewide layout+........................++Commodity symbols are spread in the table headers, each commodity has+its own column, all column groups share the same set of commodities even+if in one commodity column all values are zero. For consistency you may+think of layout 'bare' as 'baretall'.++$ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -T -Y --layout=barewide+Balance changes in 2012-01-01..2014-12-31:++ || 2012 (GLD) 2012 (ITOT) 2012 (USD) 2012 (VEA) 2012 (VHT) 2013 (GLD) 2013 (ITOT) 2013 (USD) 2013 (VEA) 2013 (VHT) 2014 (GLD) 2014 (ITOT) 2014 (USD) 2014 (VEA) 2014 (VHT) Total (GLD) Total (ITOT) Total (USD) Total (VEA) Total (VHT) +==================++===================================================================================================================================================================================================================================================================+ Assets:US:ETrade || 0 10.00 337.18 12.00 106.00 70.00 18.00 -98.12 10.00 18.00 0 -11.00 4881.44 14.00 170.00 70.00 17.00 5120.50 36.00 294.00 +------------------++-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ || 0 10.00 337.18 12.00 106.00 70.00 18.00 -98.12 10.00 18.00 0 -11.00 4881.44 14.00 170.00 70.00 17.00 5120.50 36.00 294.00 ++ Barewide layout is very useful for FODS and CSV output, since you can+easily use LibreOffice's 'VLOOKUP' function for accessing numbers in a+table with mixed commodities.+++File: hledger.info, Node: Tidy layout, Prev: Barewide layout, Up: Balance report layout++9.4.15.5 Tidy layout+....................++This produces normalised "tidy data" (see+https://cran.r-project.org/web/packages/tidyr/vignettes/tidy-data.html)+where every variable has its own column and each row represents a single+data point. This is the easiest kind of data for other software to+consume:++$ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -Y -O csv --layout=tidy+"account","period","start_date","end_date","commodity","value"+"Assets:US:ETrade","2012","2012-01-01","2012-12-31","GLD","0"+"Assets:US:ETrade","2012","2012-01-01","2012-12-31","ITOT","10.00"+"Assets:US:ETrade","2012","2012-01-01","2012-12-31","USD","337.18"+"Assets:US:ETrade","2012","2012-01-01","2012-12-31","VEA","12.00"+"Assets:US:ETrade","2012","2012-01-01","2012-12-31","VHT","106.00"+"Assets:US:ETrade","2013","2013-01-01","2013-12-31","GLD","70.00"+"Assets:US:ETrade","2013","2013-01-01","2013-12-31","ITOT","18.00"+"Assets:US:ETrade","2013","2013-01-01","2013-12-31","USD","-98.12"+"Assets:US:ETrade","2013","2013-01-01","2013-12-31","VEA","10.00"+"Assets:US:ETrade","2013","2013-01-01","2013-12-31","VHT","18.00"+"Assets:US:ETrade","2014","2014-01-01","2014-12-31","GLD","0"+"Assets:US:ETrade","2014","2014-01-01","2014-12-31","ITOT","-11.00"+"Assets:US:ETrade","2014","2014-01-01","2014-12-31","USD","4881.44"+"Assets:US:ETrade","2014","2014-01-01","2014-12-31","VEA","14.00"+"Assets:US:ETrade","2014","2014-01-01","2014-12-31","VHT","170.00"+++File: hledger.info, Node: Balance report output, Next: Balance charts, Prev: Balance report layout, Up: balance++9.4.16 Balance report output+----------------------------++As noted in Output format, if you choose HTML output (by using '-O html'+or '-o somefile.html'), you can create a 'hledger.css' file in the same+directory to customise the report's appearance.++ The HTML and FODS output formats can generate hyperlinks to+'hledger-web' register views: an account name links to the account's+transactions, a period heading to the period's transactions, and, in the+default layout, a figure to the transactions it is made of, in a+register whose final balance is that figure (a historical balance report+asks the register for its historical mode). The two can differ when a+transaction's postings have dates of their own, since the report counts+such a posting in its own period while the register shows its whole+transaction. Each link says where it leads in its title, which browsers+show on hover. E.g. if your 'hledger-web' server is reachable at+'http://localhost:5000' then you might run the 'balance' command with+the extra option '--base-url=http://localhost:5000'. You can also+produce relative links, like '--base-url="some/path"' or+'--base-url=""'.)+++File: hledger.info, Node: Balance charts, Next: Some useful balance reports, Prev: Balance report output, Up: balance++9.4.17 Balance charts+---------------------++With '--chart', 'balance' shows a chart of the report instead of a+table, choosing a useful kind of chart automatically. In the terminal,+this is a bar chart drawn with text characters:++$ hledger -f examples/bcexample.journal bal -M expenses:food -b 2013 -e 2013-04 cur:USD --chart -w 70+Balance changes in 2013Q1:++█ Expenses:Food:Groceries ▓ Expenses:Food:Restaurant++Jan 396.46 USD █████████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓+Feb 481.48 USD ████████████████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓+Mar 603.32 USD ██████████████████████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓++ * A multi-period report of balance changes is charted as stacked bars+ per period, showing the net total as the value (and with 'net', see+ below, as a line mark, '┃' in text).+ * A multi-period report of end balances ('--cumulative', '-H') is+ charted the same way in text (and as lines in graphical charts).+ * With '--chart=grouped', the accounts are stacked in a bar for each+ account type (assets, liabilities, equity, revenues, expenses, then+ any accounts of unknown type), side by side in each period, so that+ the types can be compared. Amounts keep their signs (eg+ liabilities are usually below zero), and end balances are drawn as+ bars too. In text charts, each period has a row for each type, and+ one for the total. Without a report interval, the whole report+ period is charted this way, as one period.+ * A single-period report is charted as one bar per account, with the+ total below the chart (as a number only, since it belongs to no+ account's bar, even with 'net').++ Negative amounts grow left from an axis, positive amounts right.+Each account has its own colour (when colour is enabled) and fill+character; fill characters repeat after four accounts. The legend lists+the accounts visible in the chart (an account too small to fill a+character cell is left out). Accounts are coloured by their account+type, with conventional colours: assets blue, liabilities amber, equity+violet, revenues green, expenses red; several accounts of one type get+different shades of its colour (up to eight; beyond that, shades are+shared). (In terminals which advertise 24-bit colour support, by+setting 'COLORTERM=truecolor', these are the same exact colours as in+SVG charts; otherwise they are the terminal's basic blue, yellow,+magenta, green and red, whose shades depend on its colour theme.)+Accounts of unknown type get distinct colours instead. But when it+shows just one account (in each panel), there is nothing to tell apart,+so the account has its type's colour, or if its type is unknown, cyan, a+colour no account type uses. A chart showing just a total (eg with+'-0', or of all accounts' transaction counts) is also cyan. Colours and+fill characters are chosen by account name, not by position, so an+account usually keeps its colour in other charts: with or without '-S',+or when you exclude other accounts to see more detail. (Not always,+since there are only a few colours: an account may get a different one+when some accounts are added or removed.) The chart fills the terminal+width, or the width set by '-w'/'--width' (except for posting counts,+with '--count', which use at most one character per posting). It is+drawn with unicode block characters, or with ASCII characters if the+system's text encoding is not UTF-8.++ There is one chart panel per commodity. You can reduce this by+converting to one commodity (eg '-X USD') or selecting some (eg+'cur:USD'); hledger suggests this when there are more than 8 panels. In+tree mode, each account's own amounts are stacked, excluding its+subaccounts', so that nothing is counted twice. At most 8 accounts are+shown per panel; the smallest are combined into "other" series, one for+each account type (so eg assets and liabilities are never combined), and+each type keeps at least its largest account. "other" series are grey,+or when coloured by type, a greyed version of their type's colour. The+total is omitted with '-N' or '--percent'. Charts draw it (as a line or+marks) only with 'net', eg '--chart=net' (or '--chart=grouped,net').+'net' draws the total where a bar combines several amounts; a chart of+one account, or with one bar per account, does not draw it. (Text+charts show it as a number either way.)++ In a chart of balance changes per period, '-T'/'--row-total' and+'-A'/'--average' show the net total's total and average per period on a+line below the chart, eg 'Total 11, Average 0.9'; and in graphical+charts, the average is also drawn as a dashed line across the chart,+with an entry in the legend. In a chart of end balances (eg with '-H',+or 'bs'), '-A' shows the average of the net total's period-end balances+in the same way (there is no total).++ Each chart is scaled to fit its values. To draw charts at a fixed+scale instead, so that you can compare them (eg this month's chart with+last month's), add a SCALE amount: '--chart=SCALE'. This is the amount+that the chart spans; eg with '--chart=5000', a bar of 5000 fills the+chart. If the chart also has negative values, they take the room they+need and positive values get the rest. Bars that don't fit are clipped,+with a mark at the edge ('▸' or '◂' in text, a small triangle in SVG);+lines go off the edge. A SCALE with a commodity symbol (eg+'--chart='5000 USD'') applies to that commodity's panel, and one+without, to the others. SCALE can follow KIND and 'net', and several+SCALEs can be given, separated by commas (eg '--chart='auto,5000+USD,4000 EUR''); so a SCALE can't contain a comma: write it without+digit group marks, or with spaces or periods (eg '10 000 EUR'). A+number like '10.000' is read using that commodity's decimal mark, as it+is shown in the report: eg in a journal where EUR is written with a+decimal comma, '10.000 EUR' is ten thousand. For the same scale in text+charts, use the same width too ('-w').++ With SVG output ('-o FILE.svg' or '-O svg'), 'balance' always shows a+chart, as a graphical image. Time runs along the x axis, and end+balances are drawn as lines. A single-period report is drawn as+vertical bars, one per account, with the account names below (angled if+needed) and values above the bars (where they fit); or with more than 30+accounts, as horizontal bars. The y axis shows the unit only on its top+(or bottom) label. In an HTML page, the chart shrinks to fit a narrower+window.++ With HTML output, '--chart' shows the chart (as SVG), with the+report's table collapsed below it (click Report details to show it).++ With '-O csv', '-O tsv' or '-O json', '--chart' shows the chart's+data, eg to inspect it or chart it with other tools.++ The compound balance commands ('balancesheet', 'balancesheetequity',+'cashflow', 'incomestatement') can show charts in the same ways. They+chart their sections' accounts, with the net total (as a number in text+charts, and with 'net', as a mark in text charts or a line in SVG+charts), in one of two layouts:++ * *diverging* (the default, or with '--chart=diverging'): at each+ period, all accounts are stacked in one bar, showing each amount as+ its contribution to the net total: sections that add to it (eg+ assets, revenues) above zero, and sections that subtract from it+ (eg liabilities, expenses) below zero. (This is also why an 'is'+ chart draws expenses below zero while 'bal' draws them above, as+ their raw amounts are positive; 'bal --invert' gives the same+ signs.) In text charts, each period is a row showing the net+ total, the totals of the sections on each side at the ends of the+ bar (as the report's table shows them; headed by the sections'+ names), and with 'net', a mark at the net total's position.++ * *grouped* (with '--chart=grouped'): at each period, each section's+ accounts are stacked in a bar of their own, side by side, so that+ the sections' sizes can be compared. Amounts are shown as the+ tables show them, eg expenses as well as revenues are positive. In+ text charts, each period has a row for each section, showing its+ total, and a row showing the net total (and with 'net', marking+ it).++ Contra amounts - those with the opposite sign to their section's+usual sign, like a refund recorded as a negative expense, or a contra+account like accumulated depreciation - are drawn next to the zero line,+hatched in their account's colour (below zero in the grouped layout, and+on the other side from their section in the diverging layout). They are+included in their section's totals. (Cash flows, in 'cf', have no usual+sign: decreases are drawn like increases, below zero.) Each section+shows at most five accounts, combining the smallest into "other"; use a+depth limit (eg '-1' or '-2') for less detail. A single-period report+is charted the same way, with one period. The chart data has one record+per value, with fields: commodity, series (usually an account name),+role ('item', 'other' or 'total'), mark ('bar', 'line' or 'marker'), x+(a period heading, period end date, or account name), and value. With+'-T' or '-A', each commodity's total or average follows, with role+'rowtotal' or 'average', and an empty mark and x. Eg:++$ hledger -f examples/sample.journal bal -M expenses -N --chart -O csv+"commodity","series","role","mark","x","value"+"$","expenses:food","item","bar","Jan","0"+"$","expenses:food","item","bar","Feb","0"+...+++File: hledger.info, Node: Some useful balance reports, Prev: Balance charts, Up: balance++9.4.18 Some useful balance reports+----------------------------------++Some frequently used 'balance' options/reports are:++ * 'bal -M revenues expenses'+ Show revenues/expenses in each month. Also available as the+ 'incomestatement' command.++ * 'bal -M -H assets liabilities'+ Show historical asset/liability balances at each month end. Also+ available as the 'balancesheet' command.++ * 'bal -M -H assets liabilities equity'+ Show historical asset/liability/equity balances at each month end.+ Also available as the 'balancesheetequity' command.++ * 'bal -M assets not:receivable'+ Show changes to liquid assets in each month. Also available as the+ 'cashflow' command.++ Also:++ * 'bal -M expenses -2 -SA'+ Show monthly expenses summarised to depth 2 and sorted by average+ amount.++ * 'bal -M --budget expenses'+ Show monthly expenses and budget goals.++ * 'bal -M --valuechange investments'+ Show monthly change in market value of investment assets.++ * 'bal -M -H --gain investments'+ Show unrealised gain on investment assets (market value minus cost)+ at each month end.++ * 'bal investments --valuechange -D date:lastweek amt:'>1000' -STA+ [--invert]'+ Show top gainers [or losers] last week+++File: hledger.info, Node: balancesheet, Next: balancesheetequity, Prev: balance, Up: Report commands++9.5 balancesheet+================++(bs)++ Show the end balances in asset and liability accounts. Amounts are+shown with normal positive sign, as in conventional financial+statements.++Flags:+ --sum calculation mode: show sum of posting amounts+ (default)+ --valuechange calculation mode: show total change of value+ of period-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ --gain calculation mode: show unrealised capital+ gain/loss (historical balance value minus cost+ basis)+ --count calculation mode: show the count of postings+ --change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports)+ --cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. -b/--begin) to+ column end+ -H --historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date) (default)+ -l --flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth-clipped.+ -t --tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ --drop=N in list mode, omit N leading account name+ parts+ --declared include non-parent declared accounts (best+ used with -E)+ -A --average show a row average column (in multicolumn+ reports)+ -T --row-total show a row total column (in multicolumn+ reports)+ --summary-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ -N --no-total omit the final total row+ --no-elide in tree mode, don't squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without -E)+ --full-names in tree mode, show full account names instead+ of indented leaf names+ --format=FORMATSTR use this custom line format (in simple+ reports)+ -S --sort-amount sort by amount instead of account code/name+ -% --percent express values in percentage of each column's+ total+ --layout=ARG how to show multi-commodity amounts:+ 'wide[,WIDTH]': all commodities on one line+ 'tall' : each commodity on a new line+ 'bare' : bare numbers, symbols in a+ column+ --base-url=URLPREFIX in html output, generate hyperlinks to+ hledger-web, with this prefix. (Usually the base+ url shown by hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ -o --output-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ --view write output to FILE, or to view.FMT in+ hledger's cache directory, and open it in the+ system's default viewer for its format (eg a web+ browser for html). The default format is html.+ --chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: diverging (sections above and below zero;+ the default) or grouped (sections side by side).+ net: also draw the net total (a line, or marks+ in text charts). SCALE: the amount that fills+ the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)++ This command displays a balance sheet, showing historical ending+balances of asset and liability accounts. (To see equity as well, use+the balancesheetequity command.)++ Accounts declared with the 'Asset', 'Cash' or 'Liability' type are+shown (see account types). Or if no such accounts are declared, it+shows top-level accounts named 'asset' or 'liability' (case insensitive,+plurals allowed) and their subaccounts.++ Example:++$ hledger balancesheet+Balance Sheet 2008-12-31++ || 2008-12-31 +====================++============+ Assets || +--------------------++------------+ assets:bank:saving || $1 + assets:cash || $-2 +--------------------++------------+ || $-1 +====================++============+ Liabilities || +--------------------++------------+ liabilities:debts || $-1 +--------------------++------------+ || $-1 +====================++============+ Net: || 0 ++ This command is a higher-level variant of the 'balance' command, and+supports many of that command's features, such as multi-period reports.+It is similar to 'hledger balance -H assets liabilities', but with+smarter account detection, and liabilities displayed with their sign+flipped.++ This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', 'tsv', 'html',+'json', and 'svg' (a chart; see Balance charts).+++File: hledger.info, Node: balancesheetequity, Next: cashflow, Prev: balancesheet, Up: Report commands++9.6 balancesheetequity+======================++(bse)++ Show a balance sheet, with historical ending balances of asset,+liability and equity accounts. Amounts are shown with normal positive+sign, as in conventional financial statements.++Flags:+ --sum calculation mode: show sum of posting amounts+ (default)+ --valuechange calculation mode: show total change of value+ of period-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ --gain calculation mode: show unrealised capital+ gain/loss (historical balance value minus cost+ basis)+ --count calculation mode: show the count of postings+ --change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports)+ --cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. -b/--begin) to+ column end+ -H --historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date) (default)+ -l --flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth-clipped.+ -t --tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ --drop=N in list mode, omit N leading account name+ parts+ --declared include non-parent declared accounts (best+ used with -E)+ -A --average show a row average column (in multicolumn+ reports)+ -T --row-total show a row total column (in multicolumn+ reports)+ --summary-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ -N --no-total omit the final total row+ --no-elide in tree mode, don't squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without -E)+ --full-names in tree mode, show full account names instead+ of indented leaf names+ --format=FORMATSTR use this custom line format (in simple+ reports)+ -S --sort-amount sort by amount instead of account code/name+ -% --percent express values in percentage of each column's+ total+ --layout=ARG how to show multi-commodity amounts:+ 'wide[,WIDTH]': all commodities on one line+ 'tall' : each commodity on a new line+ 'bare' : bare numbers, symbols in a+ column+ --base-url=URLPREFIX in html output, generate hyperlinks to+ hledger-web, with this prefix. (Usually the base+ url shown by hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ -o --output-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ --view write output to FILE, or to view.FMT in+ hledger's cache directory, and open it in the+ system's default viewer for its format (eg a web+ browser for html). The default format is html.+ --chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: diverging (sections above and below zero;+ the default) or grouped (sections side by side).+ net: also draw the net total (a line, or marks+ in text charts). SCALE: the amount that fills+ the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)++ This report shows accounts declared with the 'Asset', 'Cash',+'Liability' or 'Equity' type (see account types). Or if no such+accounts are declared, it shows top-level accounts named 'asset',+'liability' or 'equity' (case insensitive, plurals allowed) and their+subaccounts.++ Example:++$ hledger balancesheetequity+Balance Sheet With Equity 2008-12-31++ || 2008-12-31 +====================++============+ Assets || +--------------------++------------+ assets:bank:saving || $1 + assets:cash || $-2 +--------------------++------------+ || $-1 +====================++============+ Liabilities || +--------------------++------------+ liabilities:debts || $-1 +--------------------++------------+ || $-1 +====================++============+ Equity || +--------------------++------------+--------------------++------------+ || 0 +====================++============+ Net: || 0 ++ This command is a higher-level variant of the 'balance' command, and+supports many of that command's features, such as multi-period reports.+It is similar to 'hledger balance -H assets liabilities equity', but+with smarter account detection, and liabilities/equity displayed with+their sign flipped.++ This report is the easiest way to see if the accounting equation+(A+L+E = 0) is satisfied (after you have done a 'close --retain' to+merge revenues and expenses with equity, and perhaps added+'--infer-equity' to balance your commodity conversions).++ This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', 'tsv', 'html',+'json', and 'svg' (a chart; see Balance charts).+++File: hledger.info, Node: cashflow, Next: codes, Prev: balancesheetequity, Up: Report commands++9.7 cashflow+============++(cf)++ Show a (simple) cashflow statement, with the inflows and outflows+affecting "cash" (ie, liquid, easily convertible) assets. Amounts are+shown with normal positive sign, as in conventional financial+statements.++Flags:+ --sum calculation mode: show sum of posting amounts+ (default)+ --valuechange calculation mode: show total change of value+ of period-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ --gain calculation mode: show unrealised capital+ gain/loss (historical balance value minus cost+ basis)+ --count calculation mode: show the count of postings+ --change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports) (default)+ --cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. -b/--begin) to+ column end+ -H --historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date)+ -l --flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth-clipped.+ -t --tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ --drop=N in list mode, omit N leading account name+ parts+ --declared include non-parent declared accounts (best+ used with -E)+ -A --average show a row average column (in multicolumn+ reports)+ -T --row-total show a row total column (in multicolumn+ reports)+ --summary-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ -N --no-total omit the final total row+ --no-elide in tree mode, don't squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without -E)+ --full-names in tree mode, show full account names instead+ of indented leaf names+ --format=FORMATSTR use this custom line format (in simple+ reports)+ -S --sort-amount sort by amount instead of account code/name+ -% --percent express values in percentage of each column's+ total+ --layout=ARG how to show multi-commodity amounts:+ 'wide[,WIDTH]': all commodities on one line+ 'tall' : each commodity on a new line+ 'bare' : bare numbers, symbols in a+ column+ --base-url=URLPREFIX in html output, generate hyperlinks to+ hledger-web, with this prefix. (Usually the base+ url shown by hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ -o --output-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ --view write output to FILE, or to view.FMT in+ hledger's cache directory, and open it in the+ system's default viewer for its format (eg a web+ browser for html). The default format is html.+ --chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: diverging (sections above and below zero;+ the default) or grouped (sections side by side).+ net: also draw the net total (a line, or marks+ in text charts). SCALE: the amount that fills+ the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)++ This report shows accounts declared with the 'Cash' type (see account+types). Or if no such accounts are declared, it shows accounts++ * under a top-level account named 'asset' (case insensitive, plural+ allowed)+ * whose name contains some variation of 'cash', 'bank', 'checking' or+ 'saving'.++ More precisely: all accounts matching this case insensitive regular+expression:++ ^assets?(:.+)?:(cash|bank|che(ck|que?)(ing)?|savings?|currentcash)(:|$)++ and their subaccounts.++ An example cashflow report:++$ hledger cashflow+Cashflow Statement 2008++ || 2008 +====================++======+ Cash flows || +--------------------++------+ assets:bank:saving || $1 + assets:cash || $-2 +--------------------++------+ || $-1 ++ This command is a higher-level variant of the 'balance' command, and+supports many of that command's features, such as multi-period reports.+It is similar to 'hledger balance assets not:fixed not:investment+not:receivable', but with smarter account detection.++ This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', 'tsv', 'html',+'json', and 'svg' (a chart; see Balance charts).+++File: hledger.info, Node: codes, Next: commodities, Prev: cashflow, Up: Report commands++9.8 codes+=========++List the codes seen in transactions, in the order parsed.++Flags:+no command-specific flags++ This command prints the value of each transaction's code field, in+the order transactions were parsed. The transaction code is an optional+value written in parentheses between the date and description, often+used to store a cheque number, order number or similar.++ Transactions aren't required to have a code, and missing or empty+codes will not be shown by default. With the '-E'/'--empty' flag, they+will be printed as blank lines.++ You can add a query to select a subset of transactions.++ Examples:++2022/1/1 (123) Supermarket + Food $5.00+ Checking ++2022/1/2 (124) Post Office+ Postage $8.32+ Checking++2022/1/3 Supermarket+ Food $11.23+ Checking ++2022/1/4 (126) Post Office+ Postage $3.21+ Checking++$ hledger codes+123+124+126++$ hledger codes -E+123+124++126+++File: hledger.info, Node: commodities, Next: descriptions, Prev: codes, Up: Report commands++9.9 commodities+===============++(comm)++ List the commodity symbols used or declared in the journal.++Flags:+ --used list commodities used in transactions+ --priced list commodities appearing in P directives+ --declared list commodities declared by commodity directives+ --undeclared list commodities used or priced but not declared+ --unused list commodities declared but not used or priced+ --find list the first commodity matched by the first+ argument (a case-insensitive infix regexp)+ --directives show as commodity directives (with their display+ styles), for use in journals++ Most of these flags can be combined. With '--directives', it shows+valid commodity directives, declaring each commodity's (declared or+inferred) display style, which could be pasted into a journal file.+Some kinds of query argument are supported: 'cur:', 'tag:', and 'date:'+(also '-b'/'-e'/'-p' report period options).++ Providing a date query will affect which commodities are reported, as+follows:++Flag No date query With a date query+---------------------------------------------------------------------------+(none) declared ∪ transacted ∪ (transacted ∪ priced) in the+ priced period+'--used' transacted in the journal transacted in the period+'--priced' appearing in any P appearing in a P directive in+ directive the period+'--declared'declared with a 'commodity' same+ directive+'--undeclared'(transacted ∪ priced) ∖ (transacted ∪ priced in the+ declared period) ∖ declared+'--unused' declared ∖ (transacted ∪ same+ priced)+'--find' the first commodity same+ matching the argument++ Example:++$ hledger commodities+$+AAPL+EUR+++File: hledger.info, Node: descriptions, Next: files, Prev: commodities, Up: Report commands++9.10 descriptions+=================++(desc)++ List the unique descriptions used in transactions.++Flags:+no command-specific flags++ This command lists the unique descriptions that appear in+transactions, in alphabetic order. You can add a query to select a+subset of transactions.++ Example:++$ hledger descriptions+Store Name+Gas Station | Petrol+Person A+++File: hledger.info, Node: files, Next: holdings, Prev: descriptions, Up: Report commands++9.11 files+==========++List all input files used by the journal(s), in the order they were+read. This includes the files used to read CSV data: each CSV file is+followed by its rules file and any rules files that includes, and each+rules file is followed by any rules files it includes and the data file+it read (if any). With a REGEX argument, only file names matching the+regular expression (case sensitive) are shown.++ To find the files, hledger reads them only as far as needed, without+processing their data. So this command works even when the journal has+errors, such as unbalanced entries or failing balance assertions (but+not syntax errors), and it does not run 'source' commands. If an+included file does not exist (or an include's glob pattern matches no+files), it is omitted from the list, with a warning; this is not an+error. (This helps tools which generate included files, and need to+find them before they exist.) If a rules file's 'source' pattern+matches several files, only the one it would read is shown.++ With '-t/--tree', the files are shown as a tree: each included file+is indented below the file that includes it, and shown with its path+relative to that file's directory (for a file included by name, the path+as written in the include directive). The files used to read a CSV or+rules file are shown one level below it, in the same way. A file+included more than once appears at each place it is included. With a+REGEX argument (which is matched against full paths), the files+including a matched file are also shown.++Flags:+ -l --flat list/tree mode: show files as a flat list+ (default)+ -t --tree list/tree mode: show files as a tree, indenting+ included files below the file that includes them+ -O --output-format=FMT select the output format. Supported formats:+ txt, json.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.++ With '-O json', the files are listed as JSON, for use by other tools.+Each file is an object with these fields: 'path' (the file's path, or+'-' for standard input), 'depth' (0 for a main file, 1 for a file it+includes or uses, and so on), 'parent' (the path of the file that+included or used this one, or null for a main file), and 'exists' (false+for a missing included file, or an include's glob pattern which matched+nothing). '--tree' does not affect JSON output, and a REGEX argument+selects just the matching files.++ Examples:++$ hledger -f main.journal files+/home/user/finance/main.journal+/home/user/finance/2024.journal++$ hledger -f main.journal files 2024+/home/user/finance/2024.journal++$ hledger -f main.journal files --tree+/home/user/finance/main.journal+ 2024.journal+ 2025.journal+ prices/2025.prices+ checking.rules+ common.rules+ data/checking.csv++$ hledger -f main.journal files -O json checking+[+ {+ "depth": 1,+ "exists": true,+ "parent": "/home/user/finance/main.journal",+ "path": "/home/user/finance/checking.rules"+ },+ {+ "depth": 2,+ "exists": true,+ "parent": "/home/user/finance/checking.rules",+ "path": "/home/user/finance/data/checking.csv"+ }+]+++File: hledger.info, Node: holdings, Next: incomestatement, Prev: files, Up: Report commands++9.12 holdings+=============++Show a report of investment holdings.++Flags:+ -l --flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth-clipped.+ -t --tree list/tree mode: show accounts as a tree. Amounts+ include subaccount amounts.+ --no-elide in tree mode, don't squash boring parent+ accounts; in list mode, also show parent accounts+ (usually zero, hidden without -E)+ --full-names in tree mode, show full account names instead of+ indented leaf names+ --drop=N omit N leading account name parts; in tree mode,+ remove the first N levels+ -S --sort-amount sort by value (or with -B, cost) instead of+ account name, largest first+ -N --no-total omit the final total row+ --change show gains during the report period, or with a+ report interval, during each period (default with a+ start date and no interval)+ --cumulative with a report interval, show gains from the+ report start date to each period's end+ -H --historical show gains since acquisition, ignoring the report+ start date (default with a report interval)+ --round=TYPE how much rounding or padding should be done when+ displaying amounts ?+ none - show original decimal digits+ soft - just add or remove decimal zeros+ to match precision+ hard - round amounts to precision (default)+ all - also round cost amounts to precision+ --chart[=net,SCALE] show a chart: instead of the table (txt), above+ it (html), or as data (csv, tsv, json). net: also+ draw the net total (a line, or marks in text+ charts). SCALE: the amount that fills the chart (eg+ 1000 or 1000 USD; one per commodity), for+ comparable charts.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)+ -O --output-format=FMT select the output format. Supported formats:+ txt, csv, tsv, html, fods, json, svg.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ --view write output to FILE, or to view.FMT in hledger's+ cache directory, and open it in the system's+ default viewer for its format (eg a web browser for+ html). The default format is html.++ This command shows your lot-tracked assets (see Lots and capital+gains), and their performance, as of the report end date. An example:++$ hledger holdings -e 2023-04-02+Holdings on 2023-04-01++ || Date Age Units Avg cost Unit price Total cost Total value Weight UGain UGain% RGain XIRR +===========================++===========================================================================================================================+ assets:investments:stocks || 2022-04-07 359d 10 INFY 2.00 ₹ 100.00 ₹ 20.00 ₹ 1,000.00 ₹ 6.4% 980.00 ₹ 4900.0% 5252.4% + assets:investments:stocks || 73 LTTS 4.79 ₹ 200.00 ₹ 350.00 ₹ 14,600.00 ₹ 93.6% 14,250.00 ₹ 4071.4% 140.00 ₹ 4290.2% +---------------------------++---------------------------------------------------------------------------------------------------------------------------+ || 370.00 ₹ 15,600.00 ₹ 100.0% 15,230.00 ₹ 4116.2% 140.00 ₹ 4342.1% ++ With '--lots', the individual lots are shown:++$ hledger holdings --lots -e 2023-04-02+Holdings on 2023-04-01++ || Date Age Units Unit cost Unit price Total cost Total value Weight UGain UGain% RGain XIRR +=========================================================++============================================================================================================================+ assets:investments:stocks:{2022-04-06, "0002", 10.00 ₹} || 2022-04-06 360d 13 LTTS 10.00 ₹ 200.00 ₹ 130.00 ₹ 2,600.00 ₹ 16.7% 2,470.00 ₹ 1900.0% 140.00 ₹ 3876.1% + assets:investments:stocks:{2022-04-07, 2.00 ₹} || 2022-04-07 359d 10 INFY 2.00 ₹ 100.00 ₹ 20.00 ₹ 1,000.00 ₹ 6.4% 980.00 ₹ 4900.0% 5252.4% + assets:investments:stocks:{2022-05-06, "0002", 11.00 ₹} || 2022-05-06 330d 20 LTTS 11.00 ₹ 200.00 ₹ 220.00 ₹ 4,000.00 ₹ 25.6% 3,780.00 ₹ 1718.2% 5032.7% + assets:investments:stocks:{2022-06-06, "0002", 0.00 ₹} || 2022-06-06 299d 40 LTTS 0 200.00 ₹ 0 8,000.00 ₹ 51.3% 8,000.00 ₹ +---------------------------------------------------------++----------------------------------------------------------------------------------------------------------------------------+ || 370.00 ₹ 15,600.00 ₹ 100.0% 15,230.00 ₹ 4116.2% 140.00 ₹ 4342.1% ++ The columns show:++ * each holding's acquisition date (or earlier basis date) and age+ * the number of units held+ * the unit cost basis (Unit cost; or Avg cost, the average unit cost+ of several lots, or for accounts using the AVERAGE method, the+ pool's running average on the report date)+ * the unit market price on the report date (Unit price)+ * the total cost basis (Total cost)+ * the total market value (Total value)+ * the percentage of the portfolio's total value (Weight). A holding+ with no market price has no Weight and isn't counted in that total,+ so the others' weights are a little overstated. No weights are+ shown if the holdings are valued in more than one commodity.+ * the unrealised gain and gain percent (UGain, UGain%)+ * the realised gain from disposals so far (RGain)+ * and the annualised rate of return, as of the report end date (XIRR,+ calculated from the holding's dated cashflows and current value,+ like roi's IRR; it includes realised gains). Lots received without+ a transacted cost (eg transferred from another account) count as+ invested at their cost basis on their acquisition date.++ Fully disposed commodities and accounts ("closed positions") are not+shown, unless you add '-E/--empty'. But the totals row's RGain and XIRR+always include them, so those columns may not add up to their totals; a+note below the table then says how many closed positions are not shown.++ To see a commodity's performance, a market price should be declared+for it (as of the report end date). Market prices come from P+directives or (with '--infer-market-prices') from transacted prices, as+usual. Each lot is valued in its cost commodity. A holding with no+market price has no value or gains; the totals' Total value, UGain,+UGain% and XIRR are then those of the other holdings, and a note below+the table names the excluded ones. (With a report interval, the periods+whose totals exclude some are starred; and a period's gains exclude the+holdings with no market price at either its start or its end, so that+they compare the same holdings.) In a multi-currency portfolio,+aggregated values may contain multiple currencies; use '-X COMM' for a+single-currency view.++ With '-V', '-X COMM' or '--value' (Valuation), holdings are valued in+the default or given valuation commodity instead, and the cost columns+are also converted to it (at the valuation date, so percent gain is+unaffected). Cashflows are not converted, however, so the XIRR column+is left blank for holdings whose cashflows are in a different commodity.+'--value=then' is not supported, and '-B/--cost' doesn't change the+report's figures (but see sorting and 'balance:' below).++ '-S/--sort-amount' sorts the lines by their Total value, largest+first, wherever their account. Holdings with no market price come after+the priced ones, sorted by their Total cost. In tree mode, sibling+accounts are sorted likewise by their subtree's totals, as shown on+their headings (an account sorts with the unpriced ones only when none+of its holdings has a market price), and the holdings under each account+as in list mode. With '-B', everything is sorted by Total cost. Values+in different commodities are compared by their numbers alone; to compare+them properly, convert them to one commodity with '-X COMM'.++ Amounts are displayed with their commodity's display precision.+'--round' can select another rounding strategy. The percent columns+(Weight, UGain%, XIRR) are shown with the display style configured for+the '%' commodity (eg by '-c '0.00 %''). With colour enabled, the gain+columns (UGain, UGain%, RGain, XIRR) show gains in green and losses in+red.++ Query arguments and report flags like '--depth', '--title' etc. work+as usual. 'balance:' and 'change:' query terms test each line (one+commodity in one account). A line has two amounts, its units and its+Total value, and the term's commodity symbol selects which is tested:++ * 'holdings balance:'>100'' - holdings of more than 100 units (with+ no symbol, units are tested)+ * 'holdings balance:'>100 AAPL'' - holdings of more than 100 AAPL+ * 'holdings balance:'>$1000'' - holdings worth more than $1000.+ Lines with no market price have no value, and don't match.+ * 'holdings -B balance:'>$1000'' - holdings which cost more than+ $1000 (with '-B', Total cost is tested instead of Total value)++ 'change:' tests the line's change in units during the report period+(so it needs a start date, eg '-b'), or with the value's commodity+symbol, the value of that change at the valuation date. Unlike in other+reports, '-V'/'-X' don't change which amount is tested; to test the+value, write its commodity symbol. But as in other reports, '-B' tests+cost: the line's Total cost, or the cost of its change, instead of their+value. The totals and tree mode's account headings then cover just the+lines shown. But Weight is still each line's share of all the holdings,+including the hidden ones (so the total Weight shows what share the+lines shown make up).++ With '-t/--tree', holdings are grouped into account sections: an+account with subaccounts or several commodities becomes a heading row,+showing its subtree's totals computed like the totals row, with its own+holdings beneath it named by their commodity; an account holding one+commodity with no subaccounts is a single combined row; and with+'--lots', each holding's lots appear beneath it. Boring parent accounts+are squashed into their child as usual (considering only accounts with+holdings), unless '--no-elide' is used.++ With '-O html', an HTML table is produced instead. With '-O fods', a+spreadsheet document readable by LibreOffice etc. is produced. With+'-O csv' or '-O tsv', machine-readable output is produced: one record+per holding (or lot, with '--lots'), with full account names, age in+days, bare units and gain percent numbers, and no totals or tree-mode+heading records. With '-O json', a JSON array of holding objects is+produced. In both, the cost and value fields are named 'unitcost',+'unitprice', 'totalcost' and 'totalvalue'.++* Menu:++* Gains during a period::+* Holdings over time::+* Holdings charts::+++File: hledger.info, Node: Gains during a period, Next: Holdings over time, Up: holdings++9.12.1 Gains during a period+----------------------------++Normally the gain columns show each holding's gains since it was+acquired. With a report start date (eg '-b', '-p', or 'date:'), they+show the gains during the report period instead, and the report title+says so (eg "gains in 2026-11"):++$ hledger holdings -p today # today's gains+$ hledger holdings -p thisyear # this year's gains so far+$ hledger holdings -b 2026-10-01 # gains since a date (until today)+$ hledger holdings -p 2026-q3 # gains in a past period (the report shows holdings at its end)++ The units, cost, price, value and Weight columns are unchanged; they+show holdings as of the report end date. But:++ * UGain is the change in unrealised gain during the period: the+ unrealised gain at the end, minus that on the day before the start+ date. (Note that selling realises gains: UGain decreases and RGain+ increases.)+ * UGain% is that as a percentage of the holding's value on the day+ before the start date, plus the net cost added since.+ * RGain is the realised gain from disposals during the period.+ * XIRR is the annualised rate of return for the period, counting the+ value on the day before the start date as invested then. For a+ short period this can be a very large number (or blank, when too+ large to calculate); UGain% shows the period's un-annualised gain.++ The start date is the first day of the period, so gains are measured+from the previous day's closing prices: '-p today' shows today's gains+(today's market prices compared with the latest ones before today), and+'-b yesterday' shows yesterday's and today's. This way consecutive+periods' gains add up, and a month's gains start from the previous+month's last prices, as in a broker's statement. If a market price is+missing at the start or the end, the gains depending on it are left+blank. With '-E', holdings fully disposed during the period are shown+too.++ A report start date before your first acquisition gives the same+gains as no start date. '-H/--historical' shows the gains since+acquisition despite a start date. (With a report interval, gains are+since acquisition unless you ask otherwise; see below.)+++File: hledger.info, Node: Holdings over time, Next: Holdings charts, Prev: Gains during a period, Up: holdings++9.12.2 Holdings over time+-------------------------++With a report interval (eg '-M', '-Q', '-Y'), holdings shows how your+holdings changed: their totals at the end of each period, each computed+as on that date (eg valued at its market prices). When the holdings are+all of one commodity (eg with a 'cur:' query), their Units, Avg cost and+Unit price are shown too.++ The gain columns' period is selected as in other periodic reports+(accumulation mode):++ * '-H/--historical' (the default): gains since acquisition, up to+ each period's end+ * '--change': gains during each period, as in a single-date report of+ that period (above); these add up: the periods' UGain and RGain sum+ to those of the whole report period+ * '--cumulative': gains from the report start date up to each+ period's end.++ With no end date, the periods continue up to today, even after your+last transaction (since values change with market prices), and the+current period's row shows today's holdings, like the report without an+interval. List/tree mode and '--lots' make no difference to these+totals, and are ignored. With '-O csv', 'tsv' or 'json', there is one+record per period end, whose 'unpriced' field lists the commodities+excluded from its totals for having no market price.++$ hledger holdings -M -e 2026-04-01+Monthly holdings, 2026-01-31..2026-03-31++ || Units Avg cost Unit price Total cost Total value UGain UGain% RGain XIRR +============++======================================================================================+ 2026-01-31 || 10 AAA $10 $12 $100 $120 $20 20.0% 820.5% + 2026-02-28 || 6 AAA $10 $15 $60 $90 $30 50.0% $20 1566.4% + 2026-03-31 || 6 AAA $10 $9 $60 $54 $-6 -10.0% $20 108.0% +++File: hledger.info, Node: Holdings charts, Prev: Holdings over time, Up: holdings++9.12.3 Holdings charts+----------------------++With '--chart', holdings are shown as a chart: a bar for each holding+(or lot, with '--lots'), labelled by account and commodity. A holding's+bar shows its cost basis, and its unrealised gain stacked on top,+reaching its market value (which is shown); or if it has lost value, the+part of its cost basis it is still worth, reaching its market value, and+the part lost beyond it (hatched). So the solid part of a bar always+reaches the market value. In graphical charts these are coloured like+assets (blue), revenues (green) and expenses (red). Each bar's+unrealised gain percent is shown after its value, in green if positive+or red if negative. Graphical charts show it instead of the value+(which the axis shows), at the right of the bars, which are horizontal+so that there is room for all of them. With a report interval, each+period's gain percent is above its bar, when there is room for them all.+A holding without a market price is shown as its cost basis, in grey.+There is a chart panel for each commodity the holdings are valued in;+use '-X COMM' to see them all in one. With a report interval, there is+a bar for each period end instead, showing all the holdings then: their+total cost basis, and their net unrealised gain or loss (with+'--chart=net', also their value: in graphical charts, a line joining the+periods, like other reports' totals). With '--change' or+'--cumulative', the bars show the gains the table shows instead:+realised gains, and unrealised gains (hatched, since they are not yet+final), with losses below zero, and with '--chart=net', the net gain (in+graphical charts, a line joining the periods, like other reports'+totals). As in the table, the periods whose values and gains exclude+holdings with no market price are starred, with a note below the chart.+With SVG output (eg '-o holdings.svg', or '--view') it is a graphical+chart, and with HTML output it is shown above the report's table. See+Charts for more.++$ hledger holdings --chart -w 70+Holdings on 2024-12-31++USD+█ Cost ▒ Unrealised gain ╱ Unrealised loss ▓ No market price++assets:broker AAPL 2,500.00 USD +66.7% █████████████████▒▒▒▒▒▒▒▒▒▒▒+assets:broker NEW ▓+assets:broker XYZ 450.00 USD -40.0% █████╱╱╱+++File: hledger.info, Node: incomestatement, Next: notes, Prev: holdings, Up: Report commands++9.13 incomestatement+====================++(is)++ Show revenue inflows and expense outflows during the report period.+Amounts are shown with normal positive sign, as in conventional+financial statements.++Flags:+ --sum calculation mode: show sum of posting amounts+ (default)+ --valuechange calculation mode: show total change of value+ of period-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ --gain calculation mode: show unrealised capital+ gain/loss (historical balance value minus cost+ basis)+ --count calculation mode: show the count of postings+ --change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports) (default)+ --cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. -b/--begin) to+ column end+ -H --historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date)+ -l --flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth-clipped.+ -t --tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ --drop=N in list mode, omit N leading account name+ parts+ --declared include non-parent declared accounts (best+ used with -E)+ -A --average show a row average column (in multicolumn+ reports)+ -T --row-total show a row total column (in multicolumn+ reports)+ --summary-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ -N --no-total omit the final total row+ --no-elide in tree mode, don't squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without -E)+ --full-names in tree mode, show full account names instead+ of indented leaf names+ --format=FORMATSTR use this custom line format (in simple+ reports)+ -S --sort-amount sort by amount instead of account code/name+ -% --percent express values in percentage of each column's+ total+ --layout=ARG how to show multi-commodity amounts:+ 'wide[,WIDTH]': all commodities on one line+ 'tall' : each commodity on a new line+ 'bare' : bare numbers, symbols in a+ column+ --base-url=URLPREFIX in html output, generate hyperlinks to+ hledger-web, with this prefix. (Usually the base+ url shown by hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ -o --output-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ --view write output to FILE, or to view.FMT in+ hledger's cache directory, and open it in the+ system's default viewer for its format (eg a web+ browser for html). The default format is html.+ --chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: diverging (sections above and below zero;+ the default) or grouped (sections side by side).+ net: also draw the net total (a line, or marks+ in text charts). SCALE: the amount that fills+ the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)++ This command displays an income statement, showing revenues and+expenses during one or more periods.++ It shows accounts declared with the 'Revenue' or 'Expense' type (see+account types). Or if no such accounts are declared, it shows top-level+accounts named 'revenue' or 'income' or 'expense' (case insensitive,+plurals allowed) and their subaccounts.++ Example:++$ hledger incomestatement+Income Statement 2008++ || 2008 +===================++======+ Revenues || +-------------------++------+ income:gifts || $1 + income:salary || $1 +-------------------++------+ || $2 +===================++======+ Expenses || +-------------------++------+ expenses:food || $1 + expenses:supplies || $1 +-------------------++------+ || $2 +===================++======+ Net: || 0 ++ This command is a higher-level variant of the 'balance' command, and+supports many of that command's features, such as multi-period reports.+It is similar to 'hledger balance '(revenues|income)' expenses', but+with smarter account detection, and revenues/income displayed with their+sign flipped.++ This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', 'tsv', 'html',+'json', and 'svg' (a chart; see Balance charts).+++File: hledger.info, Node: notes, Next: payees, Prev: incomestatement, Up: Report commands++9.14 notes+==========++List the unique notes that appear in transactions.++Flags:+no command-specific flags++ This command lists the unique notes that appear in transactions, in+alphabetic order. You can add a query to select a subset of+transactions. The note is the part of the transaction description after+a | character (or if there is no |, the whole description).++ Example:++$ hledger notes+Petrol+Snacks+++File: hledger.info, Node: payees, Next: prices, Prev: notes, Up: Report commands++9.15 payees+===========++List the payee/payer names used or declared in the journal.++Flags:+ --used list payees used+ --declared list payees declared+ --undeclared list payees used but not declared+ --unused list payees declared but not used+ --find list the first payee matched by the first+ argument (a case-insensitive infix regexp)+ --directives show as payee directives, for use in journals++ This command lists unique payee/payer names - all of them by default,+or just the ones which have been used in transaction descriptions, or+declared with 'payee' directives, or used but not declared, or declared+but not used, or just the first one matched by a pattern (with '--find',+returning a non-zero exit code if it fails).++ The payee/payer name is the part of the transaction description+before a | character (or if there is no |, the whole description).++ With '--directives', it shows valid payee directives, which could be+pasted into a journal file.++ You can add query arguments to select a subset of transactions or+payees. Note that transaction-specific query terms like 'date:' will+exclude declared-but-unused payees, which don't have that field.++ Example:++$ hledger payees+Store Name+Gas Station+Person A+++File: hledger.info, Node: prices, Next: print, Prev: payees, Up: Report commands++9.16 prices+===========++Print the market prices declared with P directives. With+-infer-market-prices, also show any additional prices inferred from+costs. With -show-reverse, also show additional prices inferred by+reversing known prices. With -show-aliases, also show the exchange+rates provided by commodity aliases.++Flags:+ --show-reverse also show the prices inferred by reversing known+ prices+ --show-aliases also show the exchange rates provided by+ commodity aliases+ --summary summarise declared prices per commodity instead+ of listing them+ --locations also show where prices where declared++ With '--locations', each price line gets a trailing '; location:+FILE:LINE' comment showing where it came from. Declared prices point at+their P directive; prices inferred from costs point at the parent+transaction's first line. Reversed prices keep the source position of+the directive they were derived from.++ With '--show-aliases', each commodity alias which provides an+exchange rate (between a commodity and its alias, when there are no+market prices between them) is shown as a price dated 0000-01-01 with a+'; commodity alias' comment. Its location is the commodity directive+which declared the alias. These are used only when market prices can't+provide a conversion, see Finding market price.++ Price amounts are always displayed with their full precision, except+for reverse prices which are limited to 8 decimal digits.++ Prices can be filtered by a date:, cur:, amt: or find: query.++ Generally if you run this command with -infer-market-prices+-show-reverse -show-aliases, it will show the same prices used+internally to calculate value reports. But if in doubt, you can inspect+those directly by running the value report with -debug=2.++ Examples:++$ hledger prices+P 2024-01-01 AAPL $150+P 2024-02-01 AAPL $160+P 2024-02-01 EUR $1.08++$ hledger prices --infer-market-prices+P 2024-01-01 AAPL $150+P 2024-01-05 AAPL $150+P 2024-02-01 AAPL $160+P 2024-02-01 EUR $1.08++* Menu:++* prices summary::+++File: hledger.info, Node: prices summary, Up: prices++9.16.1 prices summary+---------------------++With '--summary', instead of listing individual prices, 'prices' prints+one row per commodity used in the journal (other than the base+currency), with the following columns:++ * *Commodity* -- the commodity, as an ISO 4217 code if possible.+ * *Prices* -- the number of market price declarations for that+ commodity.+ * *Earliest* / *Latest* -- the date range of those prices.+ * *Period* -- the duration between earliest and latest.+ * *Coverage* -- the percentage of weekdays in that period that have a+ price declared (or blank when fewer than two prices).++ Summary mode is a quick way to spot gaps in your price data, and+pairs naturally with getprices. Only prices declared with P directives+are counted; prices inferred with '--show-reverse' or+'--infer-market-prices' are ignored.++ Queries ('cur:', 'date:', 'amt:', 'find:') can be used to narrow the+prices that are summarised.+++File: hledger.info, Node: print, Next: register, Prev: prices, Up: Report commands++9.17 print+==========++Show transactions' journal entries, or export journal data to another+format.++Flags:+ -a --all show all details (--explicit --lots+ --verbose-tags)+ -x --explicit show all inferred info explicitly+ --verbose-tags add tags indicating generated/modified data+ --invert display all amounts with reversed sign+ --locations add tags showing file paths and line numbers+ --export reproduce the whole journal, with directives and+ comments preserved and included files inlined+ -m --match=DESC fuzzy search for one recent transaction with+ description closest to DESC+ --new show only newer-dated transactions added in each+ file since last run+ --round=TYPE how much rounding or padding should be done when+ displaying amounts ?+ none - show original decimal digits,+ as in journal (default)+ soft - just add or remove decimal zeros+ to match precision+ hard - round posting amounts to precision+ (can unbalance transactions)+ all - also round cost amounts to precision+ (can unbalance transactions)+ --layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 - right-align amounts, as in hledger 1+ COL - align decimal marks at column COL+ (default: 53)+ --base-url=URLPREFIX in html output, generate links to hledger-web,+ with this prefix. (Usually the base url shown by+ hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ journal, ledger, beancount, csv, tsv, html, fods,+ json, sql.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ --view write output to FILE, or to view.FMT in hledger's+ cache directory, and open it in the system's+ default viewer for its format (eg a web browser for+ html). The default format is html.++ The print command displays full journal entries (transactions) from+the journal file, sorted by date (or with '--date2', by secondary date).+(For a compact one-line-per-transaction overview, see the 'transactions'+command.)++ By default, directives and inter-transaction comments are not shown+(except for comment lines immediately preceding a transaction, which are+shown with it), and entries are sorted by date. So the default print+output is somewhat lossy. To reproduce the whole journal, including+directives and comments, use '--export' (see below).++ Eg:++$ hledger print -f examples/sample.journal date:200806+2008/06/01 gift+ assets:bank:checking $1+ income:gifts $-1++2008/06/02 save+ assets:bank:saving $1+ assets:bank:checking $-1++2008/06/03 * eat & shop+ expenses:food $1+ expenses:supplies $1+ assets:cash $-2++* Menu:++* print explicitness::+* print layout::+* print amount style::+* print parseability::+* print export mode::+* print other features::+* print output format::+++File: hledger.info, Node: print explicitness, Next: print layout, Up: print++9.17.1 print explicitness+-------------------------++Normally, whether posting amounts are implicit or explicit is preserved.+For example, when an amount is omitted in the journal, it will not+appear in the output. Similarly, if a conversion cost is implied but+not written, it will not appear in the output.++ You can use the '-x'/'--explicit' flag to force explicit display of+all amounts and costs. This can be useful for troubleshooting or for+making your journal more readable and robust against data entry errors.+'-x' is also implied by using any of '-B','-V','-X','--value'.++ The '-x'/'--explicit' flag will cause any postings with a+multi-commodity amount (which can arise when a multi-commodity+transaction has an implicit amount) to be split into multiple+single-commodity postings, keeping the output parseable.++ To see more details -- not just inferred amounts and costs, but also+lot subaccounts and postings, and the hidden tags that hledger adds to+classify things -- use '-a'/'--all', which is equivalent to '--explicit+--lots --verbose-tags'.+++File: hledger.info, Node: print layout, Next: print amount style, Prev: print explicitness, Up: print++9.17.2 print layout+-------------------++By default, 'print' aligns posting amounts so that their decimal mark is+at column 53 (or would be if they had a decimal mark). If needed, it+will shift a transaction's amounts further to the right to ensure at+least 2 spaces between account names and amounts. Also, any balance+assertion/assignment operators ('=', '=*' etc.) are aligned to the+right of the posting amounts; and the assertion/assignment amounts will+be aligned by their decimal marks.++ You can customise this with '--layout':++ * '--layout=COL' -- sets a different target column for posting+ amounts' decimal mark+ * '--layout=hledger1' -- use hledger 1 layout (right-aligned posting+ amounts in each transaction).++ If you want to change the default, put something like this in+'~/.hledger.conf':++[print]+--layout=hledger1++ Other print-like commands (close, import, rewrite, add) also accept+'--layout'.+++File: hledger.info, Node: print amount style, Next: print parseability, Prev: print layout, Up: print++9.17.3 print amount style+-------------------------++Amounts will be displayed mostly in their commodity's display style,+with standardised symbol placement, decimal mark, and digit group marks.+This does not apply to their decimal digits; 'print' normally shows the+same decimal digits that are recorded in each journal entry.+(Calculated amounts with a repeating decimal, eg from converting '10+min' to hours, are shown with 8 decimal places.)++ You can override the decimal precisions with 'print''s special+'--round' option. '--round' tries to show amounts with their+commodities' standard decimal precisions, increasingly strongly:++ * '--round=none' show amounts with original precisions (default)+ * '--round=soft' add/remove decimal zeros in amounts (except costs)+ * '--round=hard' round amounts (except costs), possibly hiding+ significant digits+ * '--round=all' round all amounts and costs++ 'soft' is good for non-lossy cleanup, displaying more consistent+decimals where possible, without making entries unbalanced.++ 'hard' or 'all' can be good for stronger cleanup, when decimal+rounding is wanted. Note rounding can produce unbalanced journal+entries, perhaps requiring manual fixup.+++File: hledger.info, Node: print parseability, Next: print export mode, Prev: print amount style, Up: print++9.17.4 print parseability+-------------------------++Usually, print's output is a valid hledger journal, which you can pipe+into a second hledger command for further processing. This is sometimes+convenient for rewriting journal entries:++# Make today's shopping entry explicit. (-f - means read from standard input.)+$ hledger print date:today desc:shop | hledger -f- print -x++ or for achieving certain kinds of query:++# Show running total of food expenses paid from cash.+$ hledger print assets:cash | hledger -f- reg expenses:food++ But here are some things which can cause print's output to become+unparseable:++ * '--round' (see above) can disrupt transaction balancing.+ * Account aliases or pivoting can disrupt account names, balance+ assertions, or balance assignments.+ * Value reporting also can disrupt balance assertions or balance+ assignments.+ * Auto postings can generate too many amountless postings.+ * '--infer-costs or --infer-equity' can generate too-complex+ redundant costs.+ * Because print always shows transactions in date order, balance+ assertions involving non-date-ordered transactions (and same-day+ postings) could be disrupted.++ Also, printing a subset of journal entries can disrupt validation of+balance assertions or lot entries. And print does not reproduce+directives (unless '--export' is used). Lot entries are printed with+their inferred cost basis annotations, so they can still be read without+the commodity's 'lots:' declaration when the default cost basis method+is used; but with other methods, or 'lots: NONE' accounts, the missing+declarations will change how they are read. ('--export' output keeps+lot entries as written, since it reproduces the declarations.) To+suppress errors from these, we often use the '-I' flag (short for+'--ignore-assertions --ignore-lots'). So any time you are reading from+standard input with '-f-', consider adding '-I' also.+++File: hledger.info, Node: print export mode, Next: print other features, Prev: print parseability, Up: print++9.17.5 print export mode+------------------------++With '--export', print reproduces the whole journal in its original+order, with directives, top-level comment lines and 'comment' blocks+preserved verbatim, and with each transaction shown as print normally+shows it (so '-x', '--round', '--layout' etc. still apply). Blank+lines are normalised: there is one blank line between transactions, and+between groups of directive or comment lines. The output can be read by+hledger as an equivalent journal, so this is the mode to use when+reformatting or regenerating a journal file. Some details:++ * Included files are inlined at the position of their 'include'+ directive, and the 'include' line itself is dropped. If you want+ to preserve a multi-file structure rather than flattening it,+ currently the best way is: comment out the 'include' directives+ (they will be preserved as comments), export each file+ individually, then uncomment the 'include' directives in the+ exported main file. (A file which depends on directives in its+ parent file, such as 'Y' or 'decimal-mark', might need those added+ temporarily while it is exported.)+ * 'apply account', 'alias' and their 'end' directives are dropped,+ since their effect is already applied to the account names shown.+ (An 'account' declaration inside an 'apply account' block is+ reproduced as written, without the parent account prefix.)+ * Directives which hledger ignores (for compatibility with Ledger)+ are not exported.+ * By default, periodic transaction rules ('~') and auto posting rules+ ('=') are exported as directives. With '--forecast' and/or+ '--auto', the generated transactions (at the end of the output) and+ postings are exported instead, and the rules are not. In other+ words, these flags materialise the rules. Postings generated by+ '--infer-equity' are exported too. (In Beancount output, these+ rules are never exported, only whatever has been generated.)+ * A query still selects which transactions are shown, but all+ directives and comments are kept.+ * Transactions from non-journal files (eg an included CSV file) are+ added at the end.+ * The 'journal' (default), 'ledger' and 'beancount' output formats+ are supported. With '-O ledger', transactions use Ledger's lot+ syntax, and directives which hledger accepts but Ledger does not+ ('decimal-mark', a one-line 'commodity' directive with an amount, a+ periodic transaction rule with a description, an auto posting rule+ with '*N' amount multipliers) are commented out, with an+ explanatory comment. Other hledger-specific syntax may remain; see+ Ledger output. With '-O beancount', Beancount 'option',+ 'commodity', 'open' and 'price' directives are generated from the+ journal's declarations and data, other directives (which have no+ Beancount equivalent) are dropped, and comments are converted to+ Beancount comments; see Beancount output. Note for both Ledger and+ Beancount, manual fixups may still be required in some cases; but+ the export will be a good start.+++File: hledger.info, Node: print other features, Next: print output format, Prev: print export mode, Up: print++9.17.6 print, other features+----------------------------++With '-B'/'--cost', amounts with costs are shown converted to cost.++ With '--invert', posting amounts are shown with their sign flipped.+It could be useful if you have accidentally recorded some transactions+with the wrong signs.++ With '--new', print shows only transactions it has not seen on a+previous run. This uses the same deduplication system as the 'import'+command. (See import's docs for details.)++ With '-m DESC'/'--match=DESC', print shows one recent transaction+whose description is most similar to DESC. DESC should contain at least+two characters. If there is no similar-enough match, no transaction+will be shown and the program exit code will be non-zero.++ With '--locations', print adds the source file and line number to+every transaction, as a tag.+++File: hledger.info, Node: print output format, Prev: print other features, Up: print++9.17.7 print output format+--------------------------++This command also supports the output destination and output format+options The output formats supported are 'journal' (the default; 'txt'+is also accepted), 'ledger', 'beancount', 'csv', 'tsv', 'html', 'fods',+'json' and 'sql'.++ The 'ledger' format is currently the same as 'journal' except it+renders amounts' cost basis using Ledger's lot syntax ('[DATE] (LABEL)+{COST}') instead of hledger's ('{DATE, "LABEL", COST}').++ The 'beancount' format tries to produce Beancount-compatible output,+as follows:++ * Transaction and postings with unmarked status are converted to+ cleared ('*') status.+ * Transactions' payee and note are backslash-escaped and+ double-quote-escaped and wrapped in double quotes.+ * Transaction and posting tags are converted to Beancount metadata+ lines.+ * Commodity symbols are converted to upper case, and a small number+ of currency symbols like '$' are converted to the corresponding+ currency names.+ * Account name parts are capitalised and unsupported characters are+ replaced with '-'. The first part must be one of Assets,+ Liabilities, Equity, Income or Expenses; if it is not, but the+ account's type is known (declared or inferred), the corresponding+ one of those is prepended; otherwise an error is raised. (Or, use+ '--alias' options to bring your accounts into compliance.)+ * Balance assignments are converted to explicit amounts.+ * Virtual and balanced virtual postings are dropped.++ By default only transactions are shown. With '--export', the+directives Beancount needs are also generated: options (a commented-out+tolerance option, and 'operating_currency' for the currencies used in+costs), a 'commodity' directive for each declared commodity, an 'open'+directive for each declared or used account (on the account's earliest+posting date, or the earliest transaction date), and 'price' directives.+Account and commodity tags become metadata on those directives, and an+account's 'lots:' tag becomes the Beancount booking method. Other+hledger directives are dropped, and top-level comments are converted to+Beancount comments.++ Here's an example of print's CSV output:++$ hledger print -Ocsv+"txnidx","date","date2","status","code","description","comment","account","amount","commodity","debit","credit","posting-status","posting-comment"+"1","2008/01/01","","","","income","","assets:bank:checking","1","$","1","","",""+"1","2008/01/01","","","","income","","income:salary","-1","$","","1","",""+"2","2008/06/01","","","","gift","","assets:bank:checking","1","$","1","","",""+"2","2008/06/01","","","","gift","","income:gifts","-1","$","","1","",""+"3","2008/06/02","","","","save","","assets:bank:saving","1","$","1","","",""+"3","2008/06/02","","","","save","","assets:bank:checking","-1","$","","1","",""+"4","2008/06/03","","*","","eat & shop","","expenses:food","1","$","1","","",""+"4","2008/06/03","","*","","eat & shop","","expenses:supplies","1","$","1","","",""+"4","2008/06/03","","*","","eat & shop","","assets:cash","-2","$","","2","",""+"5","2008/12/31","","*","","pay off","","liabilities:debts","1","$","1","","",""+"5","2008/12/31","","*","","pay off","","assets:bank:checking","-1","$","","1","",""++ * There is one CSV record per posting, with the parent transaction's+ fields repeated.+ * The "txnidx" (transaction index) field shows which postings belong+ to the same transaction. (This number might change if transactions+ are reordered within the file, files are parsed/included in a+ different order, etc.)+ * The amount is separated into "commodity" (the symbol) and "amount"+ (numeric quantity) fields.+ * The numeric amount is repeated in either the "debit" or "credit"+ column, for convenience. (Those names are not accurate in the+ accounting sense; it just puts zero or greater amounts under debit+ and negative amounts under credit.)+++File: hledger.info, Node: register, Next: roi, Prev: print, Up: Report commands++9.18 register+=============++(reg)++ Show postings & running total across accounts.++Flags:+ --cumulative accumulation mode: show running total from report+ start date (default)+ -H --historical accumulation mode: show historical running+ total/balance (includes postings before report+ start date)+ -A --average show running average of posting amounts instead+ of total (implies --empty)+ -m --match=DESC fuzzy search for one recent posting with+ description closest to DESC+ -r --related show postings' siblings instead+ --invert display all amounts with reversed sign+ --drop=N omit N leading account name parts+ --sort=FIELDS sort by: date, desc, account, amount, absamount,+ or a comma-separated combination of these. For a+ descending sort, prefix with -. (Default: date)+ -w --width=N set output width (default: terminal width). -wN,M+ sets description width as well.+ --align-all guarantee alignment across all lines (slower)+ --base-url=URLPREFIX in html output, generate links to hledger-web,+ with this prefix. (Usually the base url shown by+ hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ txt, csv, tsv, html, fods, json, svg.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ --view write output to FILE, or to view.FMT in hledger's+ cache directory, and open it in the system's+ default viewer for its format (eg a web browser for+ html). The default format is html.+ --chart[=net,SCALE] show a chart: instead of the table (txt), above+ it (html), or as data (csv, tsv, json). net: also+ draw the net total (a line, or marks in text+ charts). SCALE: the amount that fills the chart (eg+ 1000 or 1000 USD; one per commodity), for+ comparable charts.++ The register command displays matched postings, across all accounts,+in date order, with their running total or running historical balance.+(See also the 'aregister' command, which shows matched transactions in a+specific account.)++ register normally shows line per posting, but note that+multi-commodity amounts will occupy multiple lines (one line per+commodity).++ It is typically used with a query selecting a particular account, to+see that account's activity:++$ hledger register checking+2008/01/01 income assets:bank:checking $1 $1+2008/06/01 gift assets:bank:checking $1 $2+2008/06/02 save assets:bank:checking $-1 $1+2008/12/31 pay off assets:bank:checking $-1 0++ With '--date2', it shows and sorts by secondary date instead.++ Postings with a zero amount (including amounts inferred from a+balance assignment) are not shown by default; use the '--empty'/'-E'+flag to see them.++ For performance reasons, column widths are chosen based on the first+1000 lines; this means unusually wide values in later lines can cause+visual discontinuities as column widths are adjusted. If you want to+ensure perfect alignment, at the cost of more time and memory, use the+'--align-all' flag.++ The '--historical'/'-H' flag adds the balance from any undisplayed+prior postings to the running total. This is useful when you want to+see only recent activity, with a historically accurate running balance:++$ hledger register checking -b 2008/6 --historical+2008/06/01 gift assets:bank:checking $1 $2+2008/06/02 save assets:bank:checking $-1 $1+2008/12/31 pay off assets:bank:checking $-1 0++ The '--depth' option limits the amount of sub-account detail+displayed.++ The '--drop' option will trim leading segments from account names.++ The '--average'/'-A' flag shows the running average posting amount+instead of the running total (so, the final number displayed is the+average for the whole report period). This flag implies '--empty' (see+below). It is affected by '--historical'. It works best when showing+just one account and one commodity.++ The '--related'/'-r' flag shows the _other_ postings in the+transactions of the postings which would normally be shown.++ The '--invert' flag negates all amounts. For example, it can be used+on an income account where amounts are normally displayed as negative+numbers. It's also useful to show postings on the checking account+together with the related account:++ The '--sort=FIELDS' flag sorts by the fields given, which can be any+of 'account', 'amount', 'absamount', 'date', or 'desc'/'description',+optionally separated by commas. For example, '--sort account,amount'+will group all transactions in each account, sorted by transaction+amount. Each field can be negated by a preceding '-', so '--sort+-amount' will show transactions ordered from smallest amount to largest+amount.++$ hledger register --related --invert assets:checking++ With a reporting interval, register shows summary postings, one per+interval, aggregating the postings to each account:++$ hledger register --monthly income+2008/01 income:salary $-1 $-1+2008/06 income:gifts $-1 $-2++ Here too, periods with no activity, and summary postings with a zero+amount, are not shown by default; use the '--empty'/'-E' flag to see+them:++$ hledger register --monthly income -E+2008/01 income:salary $-1 $-1+2008/02 0 $-1+2008/03 0 $-1+2008/04 0 $-1+2008/05 0 $-1+2008/06 income:gifts $-1 $-2+2008/07 0 $-2+2008/08 0 $-2+2008/09 0 $-2+2008/10 0 $-2+2008/11 0 $-2+2008/12 0 $-2++ Often, you'll want to see just one line per interval. The '--depth'+option helps with this, causing subaccounts to be aggregated:++$ hledger register --monthly assets --depth 1+2008/01 assets $1 $1+2008/06 assets $-1 0+2008/12 assets $-1 $-1++ Note when using report intervals, if you specify start/end dates+these will be adjusted outward if necessary to contain a whole number of+intervals. This ensures that the first and last intervals are full+length and comparable to the others in the report.++ If you have a deeply nested account tree some reports might benefit+from trimming leading segments from the account names using '--drop'.++$ hledger register --monthly income --drop 1+2008/01 salary $-1 $-1+2008/06 gifts $-1 $-2++ With '-m DESC'/'--match=DESC', register does a fuzzy search for one+recent posting whose description is most similar to DESC. DESC should+contain at least two characters. If there is no similar-enough match,+no posting will be shown and the program exit code will be non-zero.++* Menu:++* Custom register output::+* Register charts::+++File: hledger.info, Node: Custom register output, Next: Register charts, Up: register++9.18.1 Custom register output+-----------------------------++register normally uses the full terminal width (or 80 columns if it+can't detect that). You can override this with the '--width'/'-w'+option.++ The description and account columns normally share the space equally+(about half of (width - 40) each). You can adjust this by adding a+description width as part of -width's argument, comma-separated:+'--width W,D' . Here's a diagram (won't display correctly in -help):++<--------------------------------- width (W) ---------------------------------->+date (10) description (D) account (W-41-D) amount (12) balance (12)+DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA++ and some examples:++$ hledger reg # use terminal width (or 80 on windows)+$ hledger reg -w 100 # use width 100+$ hledger reg -w 100,40 # set overall width 100, description width 40++ This command also supports the output destination and output format+options The output formats supported are 'txt', 'csv', 'tsv', 'html',+'fods', 'json', and 'svg'.+++File: hledger.info, Node: Register charts, Prev: Custom register output, Up: register++9.18.2 Register charts+----------------------++With '--chart', or with 'svg' output ('-o FILE.svg'), it shows a chart+instead. Without a report interval, this is the running total (or+average) after each posting, as a line over time; with postings to+several accounts, each account's own running total is shown too, in its+account type's colour (starting from its balance before the report+period, with '-H'), at most eight of them, the smallest combined into+"other". A text chart has a row per posting, with the accounts' running+totals stacked. With a report interval, it is each account's amount in+each period, as stacked bars, with the period's total. Charts draw the+overall running total (with several accounts) or the periods' totals+only with '--chart=net'. With '--chart -O csv' (or tsv or json) it+shows the chart's data. See also Balance charts.+++File: hledger.info, Node: roi, Next: stats, Prev: register, Up: Report commands++9.19 roi+========++Show the money-weighted (IRR) and time-weighted (TWR) rate of return on+your investments.++Flags:+ --cashflow show all amounts that were used to compute+ returns+ --investment=QUERY query to select your investment transactions+ --profit-loss=QUERY --pnl query to select profit-and-loss or+ appreciation/valuation transactions (optional)++ At a minimum, you need to supply a query (which could be just an+account name) to select your investment(s) with '--inv'.++ An optional second query to identify your profit and loss+transactions could be given with '--pnl'. If your investment's value+changes are captured solely through price directives (rather than manual+P&L journal entries), or if you do not need TWR, you can simply omit+'--pnl', and no transactions will be classed as profit and loss in this+case.++ This command will compute and display the internal rate of return+(IRR, also known as money-weighted rate of return) and time-weighted+rate of return (TWR) for your investments for the time period requested.+IRR is always annualized due to the way it is computed, but TWR is+reported both as a rate over the chosen reporting period and as an+annual rate.++ Price directives will be taken into account if you supply appropriate+'--cost' or '--value' flags (see Value reporting).++ Some special cases of IRR have no solution in the usual sense, and+are reported as:++ * 0%, when there are no cash flows, or when they all fall on the same+ day and add up to zero (nothing is gained or lost, and no time+ passes)+ * -100%, when money is put in, but nothing comes out of the+ investment or is left in it (all of it is lost). A total loss is+ -100% however long the money was invested, even for a day. (But a+ partial loss within one day is an error, below, since its annual+ rate depends on how much time passes.)++ In some cases a rate of return can't be computed. Then its cell in+the report shows 'error', the rest of the report is still shown, and the+reasons (each with its period) are printed after it as a warning. The+reasons can be:++ * No solution for Internal Rate of Return (IRR). Possible causes: IRR+ is huge (>1000000%), balance of investment becomes negative at some+ point in time.+ * No solution for Internal Rate of Return (IRR), because money only+ came out of the investment in that period (or is still in it at the+ end), and none was put in (counting its value at the start as put+ in), so the IRR is infinite.+ * No solution for Internal Rate of Return (IRR), because all of a+ period's cash flows (including the values at its start and end)+ fall on the same day, so no time passes for the gain or loss to+ happen in.+ * Failed to find solution for Internal Rate of Return (IRR). Either+ search does not converge to a solution, or converges too slowly.+ * Cannot compute the time-weighted return for DATES (PART): the+ investment's value at the start (...) plus deposits (...) is+ negative. Possible cause: the balance of the investment becomes+ negative, eg more is sold than is held (a short position).++ And in some cases the whole report can't be produced:++ * Error: Could not value the investment on DATE: no market price ...+ is known for COMMODITY on or before that date. A holding has no+ market price, and none of the investment's transactions on or+ before that date records a price for buying or selling it. Add a P+ directive for it, or record the price of its purchase.+ * Error: Period ... has multiple commodities: ... The investment,+ its cash flows or its profit and loss are in more than one+ commodity. Use -value to convert them to one (eg '--value=end,$+ --infer-market-prices').++ Examples:++ * Using roi to compute total return of investment in stocks:+ https://github.com/hledgerorg/hledger/blob/main/examples/investing/roi-unrealised.ledger++ * Cookbook > Return on Investment: https://hledger.org/roi.html++* Menu:++* Spaces and special characters in --inv and --pnl::+* Semantics of --inv and --pnl::+* Using roi with lots::+* IRR and TWR explained::+* Checking the results::+++File: hledger.info, Node: Spaces and special characters in --inv and --pnl, Next: Semantics of --inv and --pnl, Up: roi++9.19.1 Spaces and special characters in '--inv' and+---------------------------------------------------++'--pnl' Note that '--inv' and '--pnl''s argument is a query, and queries+could have several space-separated terms (see QUERIES).++ To indicate that all search terms form single command-line argument,+you will need to put them in quotes (see Special characters):++$ hledger roi --inv 'term1 term2 term3 ...'++ If any query terms contain spaces themselves, you will need an extra+level of nested quoting, eg:++$ hledger roi --inv="'Assets:Test 1' cur:USD" --pnl="'Equity:Unrealized Profit and Loss'"+++File: hledger.info, Node: Semantics of --inv and --pnl, Next: Using roi with lots, Prev: Spaces and special characters in --inv and --pnl, Up: roi++9.19.2 Semantics of '--inv' and '--pnl'+---------------------------------------++Query supplied to '--inv' has to match all transactions that are related+to your investment. Transactions not matching '--inv' will be ignored.++ In these transactions, ROI will consider postings that match '--inv'+to be "investment postings" and other postings (not matching '--inv')+will be sorted into two categories: "cash flow" and "profit and loss",+as ROI needs to know which part of the investment value is your+contributions and which is due to the return on investment.++ * "Cash flow" is depositing or withdrawing money, buying or selling+ assets, or otherwise converting between your investment commodity+ and any other commodity. Example:++ 2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil+ + 2020-01-01 Selling my Snake Oil+ assets:cash $10+ investment:snake oil = 0++ * "Profit and loss" is change in the value of your investment:++ 2019-06-01 Snake Oil falls in value+ investment:snake oil = $57+ equity:unrealized profit or loss++ All non-investment postings are assumed to be "cash flow", unless+they match '--pnl' query. Changes in value of your investment due to+"profit and loss" postings will be considered as part of your investment+return.++ The amount of each cash flow is measured from the investment's+perspective: it is the cost of the transaction's investment postings,+minus any profit and loss in that transaction. Its date is the date of+those investment postings, even if the money's posting has a different+date (eg a settlement date). This means that other postings in the same+transaction, such as fees, don't change the amount of the cash flow.++ In this example, the investment receives $100, so without '--pnl' the+cash flow is a $100 deposit, and the $1 fee is not part of the+investment at all. With '--pnl expenses', the fee counts as part of the+investment's return instead: the cash flow is a $101 deposit, of which+$1 is immediately lost (shown as profit/loss of -$1):++2019-01-01 Buying Snake Oil, with a fee+ assets:cash -$101+ expenses:fees $1+ investment:snake oil $100++ Example: if you use '--inv snake --pnl equity:unrealized', then+postings in the example below would be classifed as:++2019-01-01 Snake Oil #1+ assets:cash -$100 ; cash flow posting+ investment:snake oil ; investment posting++2019-03-01 Snake Oil #2+ equity:unrealized pnl -$100 ; profit and loss posting+ snake oil ; investment posting++2019-07-01 Snake Oil #3+ equity:unrealized pnl ; profit and loss posting+ cash -$100 ; cash flow posting+ snake oil $50 ; investment posting+++File: hledger.info, Node: Using roi with lots, Next: IRR and TWR explained, Prev: Semantics of --inv and --pnl, Up: roi++9.19.3 Using roi with lots+--------------------------++If your journal records lots, each disposal transaction has a realised+gain posting, by default to 'revenues:gain'. Make sure '--pnl' matches+that account, eg '--pnl revenues:gain', so realised gains are counted as+profit. Cash flows are measured at the investment postings' cost, which+for lots is their cost basis, so without '--pnl' a sale is a withdrawal+of its cost basis only, and its gain is not counted at all: IRR and TWR+will understate the return (eg showing 0% for a buy and a sale at a+profit).+++File: hledger.info, Node: IRR and TWR explained, Next: Checking the results, Prev: Using roi with lots, Up: roi++9.19.4 IRR and TWR explained+----------------------------++"ROI" stands for "return on investment". Traditionally this was+computed as a difference between current value of investment and its+initial value, expressed in percentage of the initial value.++ However, this approach is only practical in simple cases, where the+investment receives no in-flows or out-flows of money and the rate of+growth is fixed over time. For more complex scenarios you need+different ways to compute rate of return, and this command implements+two of them: IRR and TWR.++ *Internal rate of return (IRR)*, also called money-weighted rate of+return, answers the question: _what single constant annual interest+rate, applied to your actual sequence of deposits and withdrawals, would+produce exactly the ending balance you have?_++ IRR is inherently personal. If you deposited a large sum right+before a bad period, your IRR is dragged down - not because the+investment was poorly managed, but because your timing was bad.+Conversely, investing heavily just before a rally makes your IRR look+great. This is what makes IRR "money-weighted": periods when more of+your money is at stake contribute more to the result.++ In technical terms, IRR uses the same approach as computation of net+present value, and tries to find a discount rate that makes the net+present value of all the cash flows of your investment add up to zero.+The implementation in hledger produces results that match the '=XIRR'+formula in Excel.++ *Time-weighted rate of return (TWR)* strips out the effect of your+deposit and withdrawal timing, measuring the investment's own+performance rather than your experience of it.++ hledger computes TWR from the value of your investment at the end of+each day: its balance at the end of the day, valued (with '--value')+using the prices in effect on that day. The order of transactions and+prices within a day doesn't matter.++ * The days between two days with cash flows form one stretch, which+ starts at the end of the earlier cash flow day and ends at the end+ of the day before the later one. Its return is the ratio of the+ investment's values at those two moments. For example, with cash+ flows on March 1 and March 10, the stretch is March 2 to 9, and its+ return is (value at the end of March 9) / (value at the end of+ March+ 1. * 1. (March 10 itself is+ a day with cash flows, handled as below.)++ * A day with cash flows is split in two parts:+ 1. The day's price changes: the return of the holdings carried+ over from the previous day, from their value at the previous+ day's prices to their value at this day's prices. (This part+ is skipped if no prices changed.)+ 2. The cash flows, as if all of the day's trades were made at the+ day's closing prices. Its return is (value at the end of the+ day - withdrawals) / (value after part 1 + deposits) - 1, with+ withdrawals negative. That is, the day's deposits count as+ invested during this part, as if made at its start, and its+ withdrawals count as still invested during it, as if made at+ its end. So any difference between the prices you traded at+ and the closing prices shows up in this part's return.++ * Times when nothing is invested earn nothing. That includes a day+ on which something arrives in an empty investment only as profit+ and loss (eg a stock grant, booked to an account matched by+ '--pnl'): there is nothing to compute a return on, so that day's+ return is 0%.+ * A holding which has no market price is valued at the price of the+ investment's latest purchase or sale of it, on or before that day+ (as '--infer-market-prices' would do, but only from the+ investment's own transactions, and only while no market price is+ known). If there are several on a day, the last one recorded is+ used. Like any price, it applies to the whole holding on that day,+ including what was held before the trade, so a trade at a new price+ can show up in '--cashflow' output as a "prices" row, before its+ cash flows. And a trade recorded at zero cost (eg a gift, recorded+ with '@ $0') gives a price of 0, so such a holding is worth nothing+ until a market price is known; add a P directive for it.++ All these returns are then multiplied together (geometrically+chained) to give the TWR for the full period. In multi-period reports,+each period begins with the value the previous one ended with, so the+periods' returns chain to the total.++ Use '--value=then' for TWR, so that each day is valued with the+prices of that day. With '--value=end', '--value=now' or+'--value=DATE', all the values in a period use the same prices, so its+TWR only reflects recorded profit and loss and the differences between+the prices you traded at and those prices. With '--value=end', each+period is also valued with its own end's prices, so the periods' returns+don't chain to the total.++ TWR can only be as good as the values your journal gives for each+day. If you record changes in value only occasionally (with '--pnl'+transactions, or with sparse price directives), the growth since the+previous record is attributed to the day you record it, and so is+counted on whatever was invested on that day. If you made a large+deposit or withdrawal in between, that can make TWR quite different from+what it would be if the growth had been spread out. So record a+valuation around large deposits and withdrawals (professional+performance standards require this too), or use price directives, or+'--infer-market-prices' if your transactions record their prices.++ *In short:* TWR tells you how good the investment was; IRR tells you+how good your experience of the investment was.+++File: hledger.info, Node: Checking the results, Prev: IRR and TWR explained, Up: roi++9.19.5 Checking the results+---------------------------++'--cashflow' shows everything that IRR and TWR are computed from, so+that you can check them against your journal, against other hledger+reports, or in a spreadsheet:++ * *IRR cash flows*: one row per cash flow, with the transaction's+ description, the cost of its investment postings, and its profit or+ loss, between the investment's value at the start and its value at+ the end (dated the day after the period's last day, since it is the+ value at the end of that day). Amounts are from your point of+ view: what you put in is negative, what you take out or still have+ is positive. The dates and amounts can be given to Excel's '=XIRR'+ as they are.++ * *TWR returns*: one row for each stretch without cash flows, and for+ each day with cash flows, a row for its price changes (if any) and+ a row for its cash flows. Each row's Value (begin) is the previous+ row's Value (end), and each row's return is++ (Value (end) - Withdrawals) / (Value (begin) + Deposits) - 1++ where withdrawals are negative. The Cumulative column chains the+ returns by multiplication: each row's (1 + Cumulative) is the+ previous row's (1 + Cumulative) times (1 + Return). Its last row+ is the period's TWR.++ The values can be checked with 'hledger balance': the value at the+end of a day D is the investment's historical balance at the end of that+day, valued then. For example, if you ran 'roi --value=then,$', check+the value at the end of day D with:++$ hledger balance --historical --value=end,$ -e D+1 INVESTMENTQUERY++ (where 'D+1' is the day after D; '--value=end' values at the end of+the report period, which is day D). Holdings which have no market price+are the exception, as 'roi' values them at the price of their latest+purchase or sale.++ *When each matters*++ Use IRR when you want to know your actual personal return - what you+earned on your money, accounting for when you chose to move it. It is+the right measure when evaluating your own deposit and withdrawal timing+decisions.++ Use TWR when you want to evaluate the investment vehicle itself,+independent of your deposit timing. It is the right measure when+comparing two funds or strategies, or when asking whether you would have+been better off elsewhere. TWR is the standard that professional+investment managers use to report fund performance, precisely because it+removes the distortion caused by investor cash flows.++ References:++ * Explanation of rate of return+ * Explanation of IRR+ * Explanation of TWR+ * IRR vs TWR+ * Examples of computing IRR and TWR and discussion of the limitations+ of both metrics+++File: hledger.info, Node: stats, Next: tags, Prev: roi, Up: Report commands++9.20 stats+==========++Show journal and performance statistics.++Flags:+ -q --oneline show a single line of output+ -v --verbose show more detailed output+ -o --output-file=FILE write output to FILE.++ The stats command shows summary information for the whole journal, or+a matched part of it. With a reporting interval, it shows a report for+each report period.++ It also shows some performance statistics:++ * how long the program ran for+ * the number of transactions processed per second+ * the peak live memory in use by the program to do its work+ * the peak allocated memory as seen by the program++ By default, the output is reasonably discreet; it reveals the main+file name, your activity level, and the speed of your machine.++ With '-v/--verbose', more details are shown: the full paths of all+files, and the names of the commodities you work with.++ With '-q/--oneline', only one line of output is shown, in a+machine-friendly tab-separated format: the program version, the main+journal file name, and the performance stats,++ The run time of 'stats' is similar to that of a balance report.++ Example:++$ hledger stats -f examples/1ktxns-1kaccts.journal +Main file : .../1ktxns-1kaccts.journal+Included files : 0+Txns span : 2000-01-01 to 2002-09-27 (1000 days)+Last txn : 2002-09-26 (7827 days ago)+Txns : 1000 (1.0 per day)+Txns last 30 days : 0 (0.0 per day)+Txns last 7 days : 0 (0.0 per day)+Payees/descriptions : 1000+Accounts : 1000 (depth 10)+Commodities : 26+Base currency : B+Market prices : 1000+Runtime stats : 0.12 s elapsed, 8266 txns/s, 4 MB live, 16 MB alloc++$ hledger stats -q -f examples/10ktxns-1kaccts.journal+1.50.99-g0835a2485-20251119, mac-aarch64 10ktxns-1kaccts.journal 0.66 s elapsed 15244 txns/s 28 MB live 86 MB alloc++ This command supports the -o/-output-file option (but not+-O/-output-format).+++File: hledger.info, Node: tags, Next: transactions, Prev: stats, Up: Report commands++9.21 tags+=========++List the tag names used or declared in the journal, or their values.++Flags:+ --used list tags used+ --declared list tags declared+ --undeclared list tags used but not declared+ --unused list tags declared but not used+ --find list the first tag whose name is matched by the+ first argument (a case-insensitive infix regexp)+ --values list tag values instead of tag names+ --parsed show them in the order they were parsed (mostly),+ including duplicates+ --directives show tag names as tag directives, for use in+ journals++ This command lists tag names - all of them by default, or just the+ones which have been used on transactions/postings/accounts, or declared+with 'tag' directives, or used but not declared, or declared but not+used, or just the first one matched by a pattern (with '--find',+returning a non-zero exit code if it fails).++ Note this command's non-standard first argument: it is a+case-insensitive infix regular expression for matching tag names, which+limits the tags shown. Any additional arguments are standard query+arguments, which limit the transactions, postings, or accounts providing+tags.++ With '--values', the tags' unique non-empty values are listed+instead.++ With '-E'/'--empty', blank/empty values are also shown.++ With '--parsed', tags or values are shown in the order they were+parsed, with duplicates included. (Except, tags from account+declarations are always shown first.)++ With '--directives', tag names are shown as valid tag directives,+which could be pasted into a journal file.++ Remember that accounts also acquire tags from their parents; postings+also acquire tags from their account and transaction; and transactions+also acquire tags from their postings.++ Examples:++$ hledger tags+broker+receipt+trip++$ hledger tags --values+acme+paris+++File: hledger.info, Node: transactions, Prev: tags, Up: Report commands++9.22 transactions+=================++(tx)++ List transactions, one per line.++Flags:+ -m --match=DESC fuzzy search for one recent transaction with+ description closest to DESC++ This command shows each transaction's first line only (the date,+status, code, description, and any same-line comment), giving a compact+overview of a journal, in the manner of 'git log --oneline'. You can+add a query to select a subset of transactions. (To see full journal+entries, use the 'print' command.)++ Example:++$ hledger transactions -f examples/sample.journal+2008-01-01 income+2008-06-01 gift+2008-06-02 save+2008-06-03 * eat & shop+2008-12-31 * pay off+++File: hledger.info, Node: Maintenance commands, Next: Data generation commands, Prev: Report commands, Up: Top++10 Maintenance commands+***********************++* Menu:++* setup::+* init::+* check::+* diff::+++File: hledger.info, Node: setup, Next: init, Up: Maintenance commands++10.1 setup+==========++Check the status of the hledger installation.++Flags:+no command-specific flags++ 'setup' tests your hledger installation and prints a list of results,+sometimes with helpful hints. This is a good first command to run after+installing hledger. Also after upgrading, or when something's not+working, or just when you want a reminder of where things are.++ It makes one network request to detect the latest hledger release+version. It's ok if this fails or times out. It will use ANSI color by+default, unless disabled by NO_COLOR or -color=n. It does not use a+pager or a config file.++ It expects that the hledger version you are running is installed in+your PATH. If not, it will stop until you have done that (to keep things+simple).++ Example:++$ hledger setup+Checking your setup (and contacting hledger.org to find out the current release):+hledger+ is running on macos 27.0 on aarch64+ is built with a supported compiler/RTS yes ghc 9.14.1, using threaded RTS+ is a native binary for this machine ? yes aarch64+ is a released version ? yes hledger 1.52.4, mac-aarch64+ is up to date ? checking latest... yes latest is 1.52.4, 1.52.4 is installed+ is installed in PATH (this version) ? yes /Users/user/.local/bin/hledger+ has a system text encoding configured ? yes UTF-8, data files must use this encoding+ has a user config file ? yes /Users/user/.hledger.conf+ has a local config file ? no + the config file is readable ? yes +terminal+ the TERM variable is defined ? yes xterm-256color+ the terminal supports ANSI color ? yes + ...+journal+ the LEDGER_FILE variable is defined ? yes /Users/user/finance/main.journal+ a default journal file is readable ? yes /Users/user/finance/main.journal+ ...+++File: hledger.info, Node: init, Next: check, Prev: setup, Up: Maintenance commands++10.2 init+=========++Create starter files for a new hledger setup, or add missing ones to an+existing setup.++Flags:+ --layout=LAYOUT which file layout to write: simple, default, years+ (default: default)+ --dry-run just show the files that would be created++ With no argument, or a directory argument, 'init' writes a set of+files in that directory (the current directory by default), creating it+if needed. Which files depends on the layout chosen with '--layout'.+Note, these are just to help you get started; you can always change the+file layout to suit your needs.++ *simple*:++ Just one file. Good if you want simplicity and manual data entry.++ * 'main.journal' - the journal file, with optional declarations++ *default* (the default):++ Declarations are kept separate; subdirectories and starter scripts+for data-fetching are provided. This is a good maintainable layout that+hledger commands understand well.++ * 'main.journal' - the main journal file, with a few example+ transactions+ * 'accounts.journal', 'commodities.journal', 'payees.journal' -+ declarations+ * 'data/' - downloaded CSV files go here, with 'data/getdata', a+ starter script for get+ * 'prices/' - market prices go here, with 'prices/getprices', a+ starter script for get+ * 'rules/' - CSV rules files go here+ * an example CSV file and rules file++ *years*:++ Like default, but each year has its own journal file. This gives you+a choice of loading all years or one year at a time (see close). It+makes life a little more complicated, but it is worthwhile if you have+enough data that a single file becomes slow on your machine; or if you+want to compartmentalise the data for other reasons.++ * 'YEAR.journal' (eg '2026.journal') - this year's journal, with a+ few example transactions.+ * 'all.journal' - includes all the year journals, for multi-year+ reports+ * the same declaration files, directories and examples as default++ With a journal file argument (a path ending with '.journal', '.j',+'.hledger' or '.ledger'), you'll get the simple layout, written to that+file.++ Files that already exist are never changed; they are skipped, with a+warning. So you can run 'init' again to add missing files. After+writing the files, it suggests some next steps.++ These and other file layouts can also be seen in the hledger repo's+examples/file-layouts directory.++ Examples:++$ hledger init --dry-run # show what would be created in the current directory+$ hledger init ~/finance # create a standard setup in ~/finance+$ hledger init --layout years ~/finance # create a setup with a journal per year in ~/finance+$ hledger init 2026.journal # create a single journal file+++File: hledger.info, Node: check, Next: diff, Prev: init, Up: Maintenance commands++10.3 check+==========++Check that your data is valid, using hledger's built-in correctness+checks.++Flags:+no command-specific flags++ hledger provides a number of built-in correctness checks to help+validate your data and prevent errors. Some are run automatically, some+when you enable '--strict' mode; or you can run any of them on demand by+providing them as arguments to the 'check' command. 'check' produces no+output and a zero exit code if all is well. Eg:++hledger check # run default checks+hledger check -s # run default and strict checks+hledger check ordereddates payees # run default checks and two others+hledger check 'assert none daily type:A balance:<0' # run default checks and a custom rule++ If you are an Emacs user, you can also configure flycheck-hledger to+run these checks, providing instant feedback as you edit the journal.++ Here are the checks currently available. They are generally checked+in the order they are shown here, and only the first failure will be+reported.++* Menu:++* Default checks::+* Strict checks::+* Other checks::+* Assert rules::+* Custom checks::+++File: hledger.info, Node: Default checks, Next: Strict checks, Up: check++10.3.1 Default checks+---------------------++These important checks are performed by default, by almost all hledger+commands:++ * *parseable* - data files are in a supported format, with no syntax+ errors and no invalid include directives. This ensures that all+ files exist and are readable.++ * *autobalanced* - all transactions are balanced, after automatically+ inferring missing amounts and conversion rates and then converting+ amounts to cost. This ensures that each transaction's journal+ entry is well formed.++ * *assertions* - all balance assertions and assert directives in the+ journal are passing. Balance assertions are a strong defense+ against errors, catching many problems; assert directives check+ standing rules, like "no asset account is ever negative". This+ check is on by default, but if it gets in your way, you can disable+ it temporarily with '-I' or '--ignore-assertions', or as a default+ by adding that flag to your config file. If you put it in your+ config file, you can override that with '-s'/'--strict' or 'hledger+ check assertions'. When a journal has both kinds of problem, lot+ errors are reported before assertion failures, and balance+ assertion failures before assert directive failures.++ * *lots* - all lot entries are valid. Checks lot posting+ classifications, lot movements, that an acquisition writing both a+ cost basis and a transacted cost has them agree (a mismatch would+ silently miscalculate gains), and that any user-written realised+ gain amount on a disposal matches the calculated gain. This check+ can be disabled by '-I' or '--ignore-lots'. If you put it in your+ config file, you can override that with '-s'/'--strict' or 'hledger+ check lots'.+++File: hledger.info, Node: Strict checks, Next: Other checks, Prev: Default checks, Up: check++10.3.2 Strict checks+--------------------++When the '-s'/'--strict' flag is used (AKA strict mode), all commands+will perform the following additional checks. These provide extra+error-catching power to help you keep your data clean and correct:++ * *balanced* - like 'autobalanced', but implicit conversions between+ commodities are not allowed; all conversion transactions must use+ cost notation or equity postings. This prevents wrong conversions+ caused by typos.++ * *commodities* - all commodity symbols used must be declared. This+ guards against mistyping or omitting commodity symbols.++ * *accounts* - all account names used must be declared. This+ prevents the use of mis-spelled or outdated account names. (Except+ lot subaccounts, like ':{2026-01-15, $50}', which are automatically+ exempt; only their base account needs to be declared. And the+ accounts of postings generated by hledger, such as equity+ conversion, gain, and imbalance postings.)++ Also, strict mode ensures that the 'assertions' and 'lots' checks run+(overriding their ignore flags).+++File: hledger.info, Node: Other checks, Next: Assert rules, Prev: Strict checks, Up: check++10.3.3 Other checks+-------------------++These are not wanted by everyone, but can be run using the 'check'+command:++ * *tags* - all tags used must be declared (tags on transactions,+ postings, and account and commodity directives; except the special+ tags). This prevents mis-spelled tag names. Note hledger fairly+ often finds unintended tags in comments.++ * *payees* - all payees used in transactions must be declared. This+ will force you to declare any new payee name before using it. Most+ people will probably find this a bit too strict.++ * *ordereddates* - within each file, transactions must be ordered by+ date. (Forecast transactions are not checked.) This is a simple+ and effective error catcher. It's not included in strict mode, but+ you can add it by running 'hledger check -s ordereddates'. If+ enabled, this check is performed before balance assertions.++ * *recentassertions* - all accounts with balance assertions must have+ one that's within the 7 days before their latest posting. This+ will encourage adding balance assertions for your active+ asset/liability accounts, which in turn should encourage you to+ reconcile regularly with those real world balances - another strong+ defense against errors. ('hledger close --assert >>$LEDGER_FILE'+ is a convenient way to add new balance assertions. Later these+ become quite redundant, and you might choose to remove them to+ reduce clutter.)++ * *uniqueleafnames* - no two accounts may have the same last account+ name part (eg the 'checking' in 'assets:bank:checking'). This+ ensures each account can be matched by a unique short name, easier+ to remember and to type.+++File: hledger.info, Node: Assert rules, Next: Custom checks, Prev: Other checks, Up: check++10.3.4 Assert rules+-------------------++You can also check custom rules, written like assert directives. Give+each one as a single quoted argument, written exactly as the directive+would be written in the journal. Eg:++hledger check 'assert none daily type:A balance:<0'+hledger check 'assert some monthly income:salary' 'assert none assets:oldbank date:2025-'++ This is a convenient way to try out a rule before adding it to the+journal, or to check rules you don't want to keep there. Unlike assert+directives, these rules check all of the data files read, combined (not+each file tree separately), and they are checked even with '-I'. They+are checked after any other checks requested. (A plain 'assert'+argument, with nothing after it, is short for the 'assertions' check.)+++File: hledger.info, Node: Custom checks, Prev: Assert rules, Up: check++10.3.5 Custom checks+--------------------++You can build your own custom checks with add-on command scripts. See+also Cookbook > Scripting. Here are some examples from hledger/bin/:++ * *hledger-check-tagfiles* - all tag values containing '/' exist as+ file paths+++File: hledger.info, Node: diff, Prev: check, Up: Maintenance commands++10.4 diff+=========++Compare a particular account's transactions in two input files. It+shows any transactions to this account which are in one file but not in+the other.++Flags:+no command-specific flags++ More precisely: for each posting affecting this account in either+file, this command looks for a corresponding posting in the other file+which posts the same amount to the same account (ignoring date,+description, etc).++ Since it compares postings, not transactions, this also works when+multiple bank transactions have been combined into a single journal+entry.++ This command is useful eg if you have downloaded an account's+transactions from your bank (eg as CSV data): when hledger and your bank+disagree about the account balance, you can compare the bank data with+your journal to find out the cause.++ Examples:++$ hledger diff -f $LEDGER_FILE -f bank.csv assets:bank:giro +These transactions are in the first file only:++2014/01/01 Opening Balances+ assets:bank:giro EUR ...+ ...+ equity:opening balances EUR -...++These transactions are in the second file only:+++File: hledger.info, Node: Data generation commands, Next: PART 3 DATA FORMATS, Prev: Maintenance commands, Up: Top++11 Data generation commands+***************************++* Menu:++* close::+* rewrite::+++File: hledger.info, Node: close, Next: rewrite, Up: Data generation commands++11.1 close+==========++(equity)++ Print several kinds of "closing" and/or "opening" transactions,+useful eg when migrating balances to a new journal file, retaining+earnings into equity, consolidating balances, or viewing lot costs.+Like 'print', it prints valid journal entries. You can copy these into+your journal file(s) when you are happy with how they look.++Flags:+ --clopen[=TAGVAL] show closing and opening balances transactions,+ for AL accounts by default+ --close[=TAGVAL] show just a closing balances transaction+ --open[=TAGVAL] show just an opening balances transaction+ --assert[=TAGVAL] show a balance assertions transaction+ --assign[=TAGVAL] show a balance assignments transaction+ --retain[=TAGVAL] show a retain earnings transaction, for RX+ accounts by default+ -x --explicit show all amounts explicitly+ --show-costs show amounts with different costs separately+ --interleaved show source and destination postings together+ --assertion-type=TYPE =, ==, =* or ==*+ --close-desc=DESC set closing transaction's description+ --close-acct=ACCT set closing transaction's destination account+ --open-desc=DESC set opening transaction's description+ --open-acct=ACCT set opening transaction's source account+ --round=TYPE how much rounding or padding should be done when+ displaying amounts ?+ none - show original decimal digits,+ as in journal (default)+ soft - just add or remove decimal zeros+ to match precision+ hard - round posting amounts to precision+ (can unbalance transactions)+ all - also round cost amounts to precision+ (can unbalance transactions)+ --layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 - right-align amounts, as in hledger 1+ COL - align decimal marks at column COL+ (default: 53)++ 'close' has six modes, selected by choosing one of the mode flags:+'--clopen', '--close' (default), '--open', '--assert', '--assign', or+'--retain'. They are all doing the same kind of operation, but with+different defaults for different situations.++ The journal entries generated by 'close' will have a 'clopen:' tag,+which is helpful when you want to exclude them from reports. If the+main journal file name contains a number, the tag's value will be that+base file name with the number incremented. Eg if the journal file is+2025.journal, the tag will be 'clopen:2026'. Or you can set the tag+value by providing an argument to the mode flag. Eg '--close=foo' or+'--clopen=2025-main'.++* Menu:++* close --clopen::+* close --close::+* close --open::+* close --assert::+* close --assign::+* close --retain::+* close customisation::+* close and balance assertions::+* close examples::+++File: hledger.info, Node: close --clopen, Next: close --close, Up: close++11.1.1 close -clopen+--------------------++This is useful if migrating balances to a new journal file at the start+of a new year. It prints a "closing balances" transaction that zeroes+out account balances (Asset and Liability accounts, by default), and an+opposite "opening balances" transaction that restores them again.+Typically, you would run++hledger close --clopen -e NEWYEAR >> $LEDGER_FILE++ and then move the opening transaction from the old file to the new+file (and probably also update your LEDGER_FILE environment variable).++ Why might you do this ? If your reports are fast, you may not need+it. But at some point you will probably want to partition your data by+time, for performance or data integrity or regulatory reasons. A new+file or set of files per year is common. Then, having each file/fileset+"bookended" with opening and closing balance transactions will allow you+to freely pick and choose which files to read - just the current year,+any past year, any sequence of years, or all of them - while showing+correct account balances in each case. The earliest opening balances+transaction sets correct starting balances, and any later+closing/opening pairs will harmlessly cancel each other out.++ The balances will be transferred to and from 'equity:opening/closing+balances' by default. You can override this by using '--close-acct'+and/or '--open-acct'.++ You can select a different set of accounts to close/open by providing+an account query. Eg to add Equity accounts, provide arguments like+'assets liabilities equity' or 'type:ALE'. When migrating to a new+file, you'll usually want to bring along the AL or ALE accounts, but not+the RX accounts (Revenue, Expense).++ Assertions will be added indicating and checking the new balances of+the closed/opened accounts.+++File: hledger.info, Node: close --close, Next: close --open, Prev: close --clopen, Up: close++11.1.2 close -close+-------------------++This prints just the closing balances transaction of '--clopen'. It is+the default if you don't specify a mode.++ More customisation options are described below. Among other things,+you can use 'close --close' to generate a transaction moving the+balances from any set of accounts, to a different account. (If you need+to move just a portion of the balance, see hledger-move.)+++File: hledger.info, Node: close --open, Next: close --assert, Prev: close --close, Up: close++11.1.3 close -open+------------------++This prints just the opening balances transaction of '--clopen'. (It is+similar to Ledger's equity command.)+++File: hledger.info, Node: close --assert, Next: close --assign, Prev: close --open, Up: close++11.1.4 close -assert+--------------------++This prints a transaction that asserts the account balances as they are+on the end date (and adds an 'assert:' tag). It could be useful as+documention and to guard against changes.+++File: hledger.info, Node: close --assign, Next: close --retain, Prev: close --assert, Up: close++11.1.5 close -assign+--------------------++This prints a transaction that assigns the account balances as they are+on the end date (and adds an "assign:" tag). Unlike balance assertions,+assignments will post changes to balances as needed to reach the+specified amounts.++ This is another way to set starting balances when migrating to a new+file, and it will set them correctly even in the presence of earlier+files which do not have a closing balances transaction. However, it can+hide errors, and disturb the accounting equation, so '--clopen' is+usually recommended.+++File: hledger.info, Node: close --retain, Next: close customisation, Prev: close --assign, Up: close++11.1.6 close -retain+--------------------++This is like '--close', but it closes Revenue and Expense account+balances by default. They will be transferred to 'equity:retained+earnings', or another account specified with '--close-acct'.++ Revenues and expenses correspond to changes in equity. They are+categorised separately for reporting purposes, but traditionally at the+end of each accounting period, businesses consolidate them into equity,+This is called "retaining earnings", or "closing the books".++ In personal accounting, there's not much reason to do this, and most+people don't. (One reason to do it is to help the 'balancesheetequity'+report show a zero total, demonstrating that the accounting equation+(A-L=E) is satisfied.)+++File: hledger.info, Node: close customisation, Next: close and balance assertions, Prev: close --retain, Up: close++11.1.7 close customisation+--------------------------++In all modes, the following things can be overridden:++ * the accounts to be closed/opened, with account query arguments+ * the closing/opening dates, with '-e OPENDATE'+ * the balancing account, with '--close-acct=ACCT' and/or+ '--open-acct=ACCT'+ * the transaction descriptions, with '--close-desc=DESC' and+ '--open-desc=DESC'+ * the transactions' 'clopen' tag value, with a 'TAGVAL' argument for+ the mode flag (see above).++ By default, the closing date is yesterday, or the journal's end date,+whichever is later; and the opening date is always one day after the+closing date. You can change these by specifying a report end date; the+closing date will be the last day of the report period. Eg '-e 2024'+means "close on 2023-12-31, open on 2024-01-01".++ With '--x/--explicit', the balancing amount will be shown explicitly,+and if it involves multiple commodities, a separate posting will be+generated for each of them (similar to 'print -x').++ With '--interleaved', each individual transfer is shown with source+and destination postings next to each other (perhaps useful for+troubleshooting).++ With '--show-costs', balances' costs are also shown, with different+costs kept separate. This may generate very large journal entries, if+you have many currency conversions or investment transactions. 'close+--show-costs' is currently the best way to view investment lots with+hledger. (To move or dispose of lots, see the more capable+'hledger-move' script.) With '--lots', lot subaccount balances are+always shown without costs, even under '--show-costs': their cost+information is carried by the lot name itself, and transacted costs on+lot postings would prevent the output from being read back. For lots+using the AVERAGE or AVERAGEALL cost basis method, whose lot names+normally leave out the cost, the pool's average cost as of the closing+date is added to each lot name (eg '{2026-01-15, $55}'), so that the+output can be read back, eg to start a new file. A non-terminating+average is written with up to 8 decimal places, so the re-opened lots'+total cost basis may differ from the original by a tiny amount.+++File: hledger.info, Node: close and balance assertions, Next: close examples, Prev: close customisation, Up: close++11.1.8 close and balance assertions+-----------------------------------++'close' adds balance assertions verifying that the accounts have been+reset to zero in a closing transaction or restored to their previous+balances in an opening transaction. These provide useful error+checking, but you can ignore them temporarily with '-I', or remove them+if you prefer.++ With '--lots', balance assertions are not generated for the lot+subaccount postings in closing transactions (assertions on lot postings+get confusing, because they apply to the parent account).++ Single-commodity, subaccount-exclusive balance assertions ('=') are+generated by default. This can be changed with '--assertion-type='==*''+(eg).++ When running 'close' you should probably avoid using '-C', '-R',+'status:' (filtering by status or realness) or '--auto' (generating+postings), since the generated balance assertions would then require+these.++ Transactions with multiple dates (eg posting dates) spanning the file+boundary also can disrupt the balance assertions:++2023-12-30 a purchase made in december, cleared in january+ expenses:food 5+ assets:bank:checking -5 ; date: 2023-01-02++ To solve this you can transfer the money to and from a temporary+account, splitting the multi-day transaction into two single-day+transactions:++; in 2022.journal:+2022-12-30 a purchase made in december, cleared in january+ expenses:food 5+ equity:pending -5++; in 2023.journal:+2023-01-02 last year's transaction cleared+ equity:pending 5 = 0+ assets:bank:checking -5+++File: hledger.info, Node: close examples, Prev: close and balance assertions, Up: close++11.1.9 close examples+---------------------++* Menu:++* Retain earnings::+* Migrate balances to a new file::+* More detailed close examples::+++File: hledger.info, Node: Retain earnings, Next: Migrate balances to a new file, Up: close examples++11.1.9.1 Retain earnings+........................++Record 2022's revenues/expenses as retained earnings on 2022-12-31,+appending the generated transaction to the journal:++$ hledger close --retain -f 2022.journal -p 2022 >> 2022.journal++ After this, to see 2022's revenues and expenses you must exclude the+retain earnings transaction:++$ hledger -f 2022.journal is not:desc:'retain earnings'+++File: hledger.info, Node: Migrate balances to a new file, Next: More detailed close examples, Prev: Retain earnings, Up: close examples++11.1.9.2 Migrate balances to a new file+.......................................++Close assets/liabilities on 2022-12-31 and re-open them on 2023-01-01:++$ hledger close --clopen -f 2022.journal -p 2022+# copy/paste the closing transaction to the end of 2022.journal+# copy/paste the opening transaction to the start of 2023.journal++ After this, to see 2022's end-of-year balances you must exclude the+closing balances transaction:++$ hledger -f 2022.journal bs not:desc:'closing balances'++ For more flexibility, it helps to tag closing and opening+transactions with eg 'clopen:NEWYEAR', then you can ensure correct+balances by excluding all opening/closing transactions except the first,+like so:++$ hledger bs -Y -f 2021.j -f 2022.j -f 2023.j expr:'tag:clopen=2021 or not tag:clopen'+$ hledger bs -Y -f 2021.j -f 2022.j expr:'tag:clopen=2021 or not tag:clopen'+$ hledger bs -Y -f 2022.j -f 2023.j expr:'tag:clopen=2022 or not tag:clopen'+$ hledger bs -Y -f 2021.j expr:'tag:clopen=2021 or not tag:clopen'+$ hledger bs -Y -f 2022.j expr:'tag:clopen=2022 or not tag:clopen'+$ hledger bs -Y -f 2023.j # unclosed file, no query needed+++File: hledger.info, Node: More detailed close examples, Prev: Migrate balances to a new file, Up: close examples++11.1.9.3 More detailed close examples+.....................................++See examples/multi-year.+++File: hledger.info, Node: rewrite, Prev: close, Up: Data generation commands++11.2 rewrite+============++Print all transactions, adding auto postings to some of them. For now+the only rewrite available is adding new postings, like print -auto.++Flags:+ --add-posting='ACCT AMTEXPR' add a posting to ACCT, which may be+ parenthesised. AMTEXPR is either a literal+ amount, or *N which means the transaction's+ first matched amount multiplied by N (a+ decimal number). Two spaces separate ACCT+ and AMTEXPR.+ --diff generate diff suitable as an input for+ patch tool+ --verbose-tags add tags indicating generated/modified+ data+ --layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 - right-align amounts, as in+ hledger 1+ COL - align decimal marks at column+ COL (default: 53)++ This is a start at a generic rewriter of transaction entries. It+reads the default journal and prints the transactions, like print, but+adds one or more specified postings to any transactions matching QUERY.+The posting amounts can be fixed, or a multiplier of the existing+transaction's first posting amount.++ Examples:++$ hledger-rewrite.hs ^income --add-posting '(liabilities:tax) *.33 ; income tax' --add-posting '(reserve:gifts) $100'+$ hledger-rewrite.hs expenses:gifts --add-posting '(reserve:gifts) *-1"'+$ hledger-rewrite.hs -f rewrites.hledger++ rewrites.hledger may consist of entries like:++= ^income amt:<0 date:2017+ (liabilities:tax) *0.33 ; tax on income+ (reserve:grocery) *0.25 ; reserve 25% for grocery+ (reserve:) *0.25 ; reserve 25% for grocery++ Note the single quotes to protect the dollar sign from bash, and the+two spaces between account and amount.++ More:++$ hledger rewrite [QUERY] --add-posting "ACCT AMTEXPR" ...+$ hledger rewrite ^income --add-posting '(liabilities:tax) *.33'+$ hledger rewrite expenses:gifts --add-posting '(budget:gifts) *-1"'+$ hledger rewrite ^income --add-posting '(budget:foreign currency) *0.25 JPY; diversify'++ Argument for '--add-posting' option is a usual posting of transaction+with an exception for amount specification. More precisely, you can use+''*'' (star symbol) before the amount to indicate that that this is a+factor for an amount of original matched posting. If the amount+includes a commodity name, the new posting amount will be in the new+commodity; otherwise, it will be in the matched posting amount's+commodity.++* Menu:++* Re-write rules in a file::+* Diff output format::+* rewrite vs print --auto::+++File: hledger.info, Node: Re-write rules in a file, Next: Diff output format, Up: rewrite++11.2.1 Re-write rules in a file+-------------------------------++During the run this tool will execute so called "Automated Transactions"+found in any journal it process. I.e instead of specifying this+operations in command line you can put them in a journal file.++$ rewrite-rules.journal++ Make contents look like this:++= ^income+ (liabilities:tax) *.33++= expenses:gifts+ budget:gifts *-1+ assets:budget *1++ Note that ''='' (equality symbol) that is used instead of date in+transactions you usually write. It indicates the query by which you+want to match the posting to add new ones.++$ hledger rewrite -f input.journal -f rewrite-rules.journal > rewritten-tidy-output.journal++ This is something similar to the commands pipeline:++$ hledger rewrite -f input.journal '^income' --add-posting '(liabilities:tax) *.33' \+ | hledger rewrite -f - expenses:gifts --add-posting 'budget:gifts *-1' \+ --add-posting 'assets:budget *1' \+ > rewritten-tidy-output.journal++ It is important to understand that relative order of such entries in+journal is important. You can re-use result of previously added+postings.+++File: hledger.info, Node: Diff output format, Next: rewrite vs print --auto, Prev: Re-write rules in a file, Up: rewrite++11.2.2 Diff output format+-------------------------++To use this tool for batch modification of your journal files you may+find useful output in form of unified diff.++$ hledger rewrite --diff -f examples/sample.journal '^income' --add-posting '(liabilities:tax) *.33'++ Output might look like:++--- /tmp/examples/sample.journal++++ /tmp/examples/sample.journal+@@ -28,13 +28,15 @@+ ; declare commodities:+ ; commodity $+ +-2008/01/01 income+- assets:bank:checking $1++2008-01-01 income++ assets:bank:checking $1+ income:salary++ (liabilities:tax) $0+ +-2008/06/01 gift+- assets:bank:checking $1++2008-06-01 gift++ assets:bank:checking $1+ income:gifts++ (liabilities:tax) $0+ + 2008/06/02 save+ assets:bank:saving $1++ If you'll pass this through 'patch' tool you'll get transactions+containing the posting that matches your query be updated. Note that+multiple files might be update according to list of input files+specified via '--file' options and 'include' directives inside of these+files.++ Changed transactions are re-rendered in 'print''s standard format, so+the diff shows any reformatting as well as the postings you added:+amounts are realigned, and dates are written with '-' separators.+Transactions you didn't change are left exactly as they are. '--layout'+selects the amount alignment, so choosing one which matches your journal+will keep the diff small. Here is the example above again, with+'--layout=26' to match this journal's own alignment:++@@ -28,13 +28,15 @@+ ; declare commodities:+ ; commodity $+ +-2008/01/01 income++2008-01-01 income+ assets:bank:checking $1+ income:salary++ (liabilities:tax) $0+ +-2008/06/01 gift++2008-06-01 gift+ assets:bank:checking $1+ income:gifts++ (liabilities:tax) $0+ + 2008/06/02 save+ assets:bank:saving $1++ Only transactions which exist as journal entries in a file can be+patched this way. Transactions read from other data formats, such as+CSV or timeclock, and transactions generated by a periodic transaction+rule, have no journal entry of their own; these are left out of the+diff, and reported on stderr. To rewrite those, convert them to journal+entries first, eg with 'hledger print' or 'hledger import'.++ Be careful. Whole transaction being re-formatted in a style of+output from 'hledger print'.++ See also:++ https://github.com/hledgerorg/hledger/issues/99+++File: hledger.info, Node: rewrite vs print --auto, Prev: Diff output format, Up: rewrite++11.2.3 rewrite vs. print -auto+------------------------------++This command predates print -auto, and currently does much the same+thing, but with these differences:++ * with multiple files, rewrite lets rules in any file affect all+ other files. print -auto uses standard directive scoping; rules+ affect only child files.++ * rewrite's query limits which transactions can be rewritten; all are+ printed. print -auto's query limits which transactions are+ printed.++ * rewrite applies rules specified on command line or in the journal.+ print -auto applies rules specified in the journal.+++File: hledger.info, Node: PART 3 DATA FORMATS, Next: Journal, Prev: Data generation commands, Up: Top++12 PART 3: DATA FORMATS+***********************+++File: hledger.info, Node: Journal, Next: CSV, Prev: PART 3 DATA FORMATS, Up: Top++13 Journal+**********++hledger's usual data source is a plain text file containing journal+entries in hledger 'journal' format. If you're looking for a quick+reference, jump ahead to the journal cheatsheet.++ This file represents an accounting General Journal. The '.journal'+file extension is most often used, though not strictly required. The+journal file contains a number of transaction entries, each describing a+transfer of money (or any commodity) between two or more named accounts,+in a simple format readable by both hledger and humans.++ hledger's journal format is compatible with most of Ledger's journal+format, but not all of it. The differences and interoperation tips are+described at hledger and Ledger. With some care, and by avoiding+incompatible features, you can keep your hledger journal readable by+Ledger and vice versa. This can useful eg for comparing the behaviour+of one app against the other.++ You can use hledger without learning any more about this file; just+use the add or web or import commands to create and update it.++ Many users, though, edit the journal file with a text editor, and+track changes with a version control system such as git. Editor add-ons+such as ledger-mode or hledger-mode for Emacs, vim-ledger for Vim, and+hledger-vscode for Visual Studio Code, make this easier, adding colour,+formatting, tab completion, and useful commands. See Editors at+hledger.org for the full list.++ A hledger journal file can contain three kinds of thing: comment+lines, transactions, and/or directives (including periodic transaction+rules and auto posting rules). Understanding the journal file format+will also give you a good understanding of hledger's data model. Here's+a quick cheatsheet/overview, followed by detailed descriptions of each+part.++* Menu:++* Journal cheatsheet::+* Comments::+* Transactions::+* Dates::+* Status::+* Code::+* Description::+* Transaction comments::+* Postings::+* Account names::+* Amounts::+* Costs::+* Cost basis::+* Balance assertions::+* Posting comments::+* Tags::+* Directives::+* account directive::+* alias directive::+* assert directive::+* comment directive::+* commodity directive::+* decimal-mark directive::+* include directive::+* P directive::+* payee directive::+* tag directive::+* Periodic transactions::+* Auto postings::+* Other syntax::+++File: hledger.info, Node: Journal cheatsheet, Next: Comments, Up: Journal++13.1 Journal cheatsheet+=======================++# Here is the main syntax of hledger's journal format+# (omitting extra Ledger compatibility syntax).++###############################################################################++# 1. These are comment lines, for notes or temporarily disabling things.+; They begin with # or ;++comment+Or, lines can be enclosed within "comment" / "end comment".+This is a block of +commented lines.+end comment++# Some journal entries can have semicolon comments at end of line ; like this+# Some of them require 2 or more spaces before the semicolon.++###############################################################################++# 2. Directives customise processing or output in some way.+# You don't need any directives to get started.+# But they can add more error checking, or change how things are displayed.+# They begin with a word, letter, or symbol. +# They are most often placed at the top, before transactions.++account assets ; Declare valid account names and display order.+account assets:savings ; A subaccount. This one represents a bank account.+account assets:checking ; Another. Note, 2+ spaces after the account name.+account assets:receivable ; Accounting type is inferred from english names,+account passifs ; or declared with a "type" tag, type:L+account expenses ; type:X+ ; A follow-on comment line, indented.+account expenses:rent ; Expense and revenue categories are also accounts.+ ; Subaccounts inherit their parent's type.++commodity $0.00 ; Declare valid commodities and their display styles.+commodity 1.000,00 EUR++decimal-mark . ; The decimal mark used in this file (if ambiguous).++payee Whole Foods ; Declare a valid payee name.++tag trip ; Declare a valid tag name.++P 2024-03-01 AAPL $179 ; Declare a market price for AAPL in $ on this date.++include other.journal ; Include another journal file here.++# Declare a recurring "periodic transaction", for budget/forecast reports+~ monthly set budget goals ; <- Note, 2+ spaces before the description.+ (expenses:rent) $1000+ (expenses:food) $500++# Declare an auto posting rule, to modify existing transactions in reports+= revenues:consulting+ liabilities:tax:2024:us *0.25 ; Add a tax liability & expense+ expenses:tax:2024:us *-0.25 ; for 25% of the revenue.++###############################################################################++# 3. Transactions are what it's all about.+# They are dated events, usually movements of money between 2 or more accounts.+# They begin with a numeric date.+# Here is their basic shape:+#+# DATE DESCRIPTION ; The transaction's date and optional description.+# ACCOUNT1 AMOUNT ; A posting of an amount to/from this account, indented.+# ACCOUNT2 AMOUNT ; A second posting, balancing the first.+# ... ; More if needed. Amounts must sum to zero.+# ; Note, 2+ spaces between account names and amounts.++2024-01-01 opening balances ; At the start, declare pre-existing balances this way.+ assets:savings $10000 ; Account names can be anything. lower case is easy to type.+ assets:checking $1000 ; assets, liabilities, equity, revenues, expenses are common.+ liabilities:credit card $-500 ; liabilities, equity, revenues balances are usually negative.+ equity:start ; One amount can be left blank. $-10500 is inferred here.+ ; Some of these accounts we didn't declare above,+ ; so -s/--strict would complain.++2024-01-03 ! (12345) pay rent+ ; Additional transaction comment lines, indented.+ ; There can be a ! or * after the date meaning "pending" or "cleared".+ ; There can be a parenthesised (code) after the date/status.+ ; Amounts' sign shows direction of flow.+ assets:checking $-500 ; Minus means removed from this account (credit).+ expenses:rent $500 ; Plus means added to this account (debit).++; Keeping transactions in date order is optional (but helps error checking).++2024-01-02 Gringott's Bank | withdrawal ; Description can be PAYEE | NOTE+ assets:bank:gold -10 gold+ assets:pouch 10 gold++2024-01-02 shopping+ expenses:clothing 1 gold+ expenses:wands 5 gold+ assets:pouch -6 gold++2024-01-02 receive gift+ revenues:gifts -3 "Chocolate Frogs" ; Complex commodity symbols+ assets:pouch 3 "Chocolate Frogs" ; must be in double quotes.++2024-01-15 buy some shares, in two lots ; Cost can be noted.+ assets:investments:2024-01-15 2.0 AAAA @ $1.50 ; @ means per-unit cost+ assets:investments:2024-01-15-02 3.0 AAAA @@ $4 ; @@ means total cost+ ; ^ Per-lot subaccounts are sometimes useful.+ assets:checking $-7++2024-01-15 assert some account balances on this date+ ; Balances can be asserted in any transaction, with =, for extra error checking.+ ; Assertion txns like this one can be made with hledger close --assert --show-costs+ ;+ assets:savings $0 = $10000+ assets:checking $0 = $493+ assets:bank:gold 0 gold = -10 gold+ assets:pouch 0 gold = 4 gold+ assets:pouch 0 "Chocolate Frogs" = 3 "Chocolate Frogs"+ assets:investments:2024-01-15 0.0 AAAA = 2.0 AAAA @ $1.50+ assets:investments:2024-01-15-02 0.0 AAAA = 3.0 AAAA @@ $4+ liabilities:credit card $0 = $-500++2024-02-01 note some event, or a transaction not yet fully entered, on this date+ ; Postings are not required.++# Consistent YYYY-MM-DD date format is recommended,+# but you can use . or / and omit leading zeros if you prefer.+2024.01.01+2024/1/1+++File: hledger.info, Node: Comments, Next: Transactions, Prev: Journal cheatsheet, Up: Journal++13.2 Comments+=============++Lines in the journal will be ignored if they begin with a hash ('#') or+a semicolon (';'). (See also Other syntax.) hledger will also ignore+regions beginning with a 'comment' line, and ending with an 'end+comment' line or file end. Here's a suggestion for choosing between+them:++ * '#' for top-level notes+ * ';' for commenting out things temporarily+ * 'comment' for quickly commenting large regions (remember it's+ there, or you might get confused)++ Eg:++# a comment line+; another commentline+comment+A multi-line comment block,+continuing until "end comment" directive+or the end of the current file.+end comment++ Some hledger entries can have same-line comments attached to them,+from ; (semicolon) to end of line. See Transaction comments, Posting+comments, and Account comments below.++ Comment lines immediately preceding a transaction (with no blank line+in between) are attached to that transaction, and are shown before it,+as written, in 'print' output.+++File: hledger.info, Node: Transactions, Next: Dates, Prev: Comments, Up: Journal++13.3 Transactions+=================++Transactions are the main unit of information in a journal file. They+represent events, typically a movement of some quantity of commodities+between two or more named accounts.++ Each transaction is recorded as a journal entry, beginning with a+simple date in column 0. This can be followed by any of the following+optional fields, separated by spaces:++ * a status character (empty, '!', or '*')+ * a code (any short number or text, enclosed in parentheses)+ * a description (any remaining text until end of line or a semicolon)+ * a comment (any remaining text following a semicolon until end of+ line, and any following indented lines beginning with a semicolon)+ * 0 or more indented _posting_ lines, describing what was transferred+ and the accounts involved (indented comment lines are also allowed,+ but not blank lines or non-indented lines).++ Here's a simple journal file containing one transaction:++2008/01/01 income+ assets:bank:checking $1+ income:salary $-1+++File: hledger.info, Node: Dates, Next: Status, Prev: Transactions, Up: Journal++13.4 Dates+==========++* Menu:++* Simple dates::+* Posting dates::+++File: hledger.info, Node: Simple dates, Next: Posting dates, Up: Dates++13.4.1 Simple dates+-------------------++Dates in the journal file use _simple dates_ format: 'YYYY-MM-DD' or+'YYYY/MM/DD' or 'YYYY.MM.DD', with leading zeros optional. The year may+be omitted, in which case it will be inferred from the context: the+current transaction, the default year set with a 'Y' directive, or the+current date when the command is run. Some examples: '2010-01-31',+'2010/01/31', '2010.1.31', '1/31'.++ (On the command line and in the UIs, you can also use the more+flexible smart dates.)+++File: hledger.info, Node: Posting dates, Prev: Simple dates, Up: Dates++13.4.2 Posting dates+--------------------++You can give individual postings a different date from their parent+transaction, by adding a posting comment containing a tag (see below)+like '; date:DATE'. (There's also a Ledger-compatible syntax, ';+[DATE]', which can be convenient.)++ This is probably the best way to control posting dates precisely. Eg+in this example the expense should appear in May reports, and the+deduction from checking should be reported on 6/1 for easy bank+reconciliation:++2015/5/30+ expenses:food $10 ; food purchased on saturday 5/30+ assets:checking ; bank cleared it on monday, date:6/1++$ hledger -f t.j register food+2015-05-30 expenses:food $10 $10++$ hledger -f t.j register checking+2015-06-01 assets:checking $-10 $-10++ DATE should be a simple date; if the year is not specified it will+use the year of the transaction's date.+A non-empty 'date:' tag value must begin with a valid simple date. A+'date:' tag with an empty value is allowed, and sets no date. (To+disable a date tag temporarily, without removing the date, insert a+comma before the date.)+++File: hledger.info, Node: Status, Next: Code, Prev: Dates, Up: Journal++13.5 Status+===========++Transactions (or individual postings within a transaction) can have a+status mark, which is a single character before the transaction+description (or posting account name), separated from it by a space,+indicating one of three statuses:++mark status+ +-----------------+ unmarked+'!' pending+'*' cleared++ When reporting, you can filter by status with the '-U/--unmarked',+'-P/--pending', and '-C/--cleared' flags (and you can combine these, eg+'-UP' to match all except cleared things). Or you can use the+'status:', 'status:!', and 'status:*' queries, or the U, P, C keys in+hledger-ui.++ (Note: in Ledger the "unmarked" state is called "uncleared"; in+hledger we renamed it to "unmarked" for semantic clarity.)++ Status marks are optional, but can be helpful eg for reconciling with+real-world accounts. Some editor modes provide highlighting and+shortcuts for working with status. Eg in Emacs ledger-mode, you can+toggle transaction status with C-c C-e, or posting status with C-c C-c.++ What "uncleared", "pending", and "cleared" actually mean is up to+you. Here's one suggestion:++status meaning+--------------------------------------------------------------------------+uncleared recorded but not yet reconciled; needs review+pending tentatively reconciled (if needed, eg during a big+ reconciliation)+cleared complete, reconciled as far as possible, and considered+ correct++ With this scheme, you would use '-PC' to see the current balance at+your bank, '-U' to see things which will probably hit your bank soon+(like uncashed checks), and no flags to see the most up-to-date state of+your finances.+++File: hledger.info, Node: Code, Next: Description, Prev: Status, Up: Journal++13.6 Code+=========++After the status mark, but before the description, you can optionally+write a transaction "code", such as a check number or transaction id,+enclosed in parentheses.++ This has a few limitations: The code must not contain a closing+parenthesis (or it will be truncated). Codes tend to disrupt alignment+of the register report, making it harder to scan visually. And you+can't store more than one value there per transaction. For these+reasons you might want to avoid the code field and use tags instead.+++File: hledger.info, Node: Description, Next: Transaction comments, Prev: Code, Up: Journal++13.7 Description+================++After the date, status mark and/or code fields, the rest of the line (or+until a comment is begun with ';') is the transaction's description.+Here you can describe the transaction (called the "narration" in+traditional bookkeeping), or you can record a payee/payer name, or you+can leave it empty.++ Transaction descriptions show up in print output and in register+reports, and can be listed with the descriptions command.++ You can query by description with 'desc:DESCREGEX', or pivot on+description with '--pivot desc'.++* Menu:++* Payee and note::+++File: hledger.info, Node: Payee and note, Up: Description++13.7.1 Payee and note+---------------------++Sometimes people want a dedicated payee/payer field that can be queried+and checked more strictly. If you want that, you can write a '|' (pipe)+character in the description. This divides it into a "payee" field on+the left, and a "note" field on the right. (Either can be empty.)++ You can query these with 'payee:PAYEEREGEX' and 'note:NOTEREGEX',+list their values with the payees and notes commands, or pivot on+'payee' or 'note'.++ Note: in transactions with no '|' character, description, payee, and+note all have the same value. Once a '|' is added, they become+distinct.++ If you want more strict error checking, you can declare the valid+payee names with payee directives, and then enforce these with hledger+check payees. (Note: because of the above, for this you'll need to+ensure every transaction description contains a '|' and therefore a+checkable payee name, even if it's empty.)+++File: hledger.info, Node: Transaction comments, Next: Postings, Prev: Description, Up: Journal++13.8 Transaction comments+=========================++Text following ';', after a transaction description, and/or on indented+lines immediately below it, form comments for that transaction. They+are reproduced by 'print' but otherwise ignored, except they may contain+tags, which are not ignored.++2012-01-01 something ; a transaction comment+ ; a second line of transaction comment+ expenses 1+ assets+++File: hledger.info, Node: Postings, Next: Account names, Prev: Transaction comments, Up: Journal++13.9 Postings+=============++A posting is an addition of some amount to, or removal of some amount+from, an account. Each posting line begins with at least one space or+tab (2 or 4 spaces is common), followed by:++ * (optional) a status character (empty, '!', or '*'), followed by a+ space+ * (required) an account name (any text, optionally including single+ spaces. If anything follows the account name on the same line, the+ account name must be ended by *two or more spaces*.)+ * (optional) an amount+ * (optional) a same-line posting comment, beginning with a semicolon+ (';').++ If the amount is positive, it is being added to the account; if+negative, it is being removed from the account.++ The posting amounts in a transaction must sum up to zero, indicating+that the inflows and outflows are equal. We call this a balanced+transaction. (You can read more about the details of transaction+balancing below.)++ If no amount is written, it will be calculated automatically from the+other postings in the transaction, so as to balance the transaction. In+other words, in any transaction you can leave one posting amountless to+save typing.++* Menu:++* Debits and credits::+++File: hledger.info, Node: Debits and credits, Up: Postings++13.9.1 Debits and credits+-------------------------++The traditional accounting concepts of debit and credit of course exist+in hledger, but we represent them with numeric sign. Positive and+negative posting amounts represent debits and credits respectively.++ You don't need to remember that, but if you would like to - eg for+helping newcomers or for talking with your accountant - here's a handy+mnemonic:++ _'debit / plus / left / short words'_+_'credit / minus / right / longer words'_+++File: hledger.info, Node: Account names, Next: Amounts, Prev: Postings, Up: Journal++13.10 Account names+===================++Accounts are the main way of categorising things in hledger. As in+Double Entry Bookkeeping, they can represent real world accounts (such+as a bank account), or more abstract categories such as "money spent on+food" or "money borrowed from Frank".++ Account names are flexible. They may be capitalised or not; they may+contain letters, numbers, punctuation, symbols, or single spaces; they+may be in any language. Their parts, separated by ':', can't be empty;+so an account name can't begin or end with ':', or contain '::'.++ Typically we use the five traditional accounting categories as the+starting point for account names. In english they are:++ 'assets', 'liabilities', 'equity', 'revenues', 'expenses'++ These will be discussed more in Account types below. In hledger docs+you may see them referred to as A, L, E, R, X for short.++* Menu:++* Two space delimiter::+* Account hierarchy::+* Other account name features::+++File: hledger.info, Node: Two space delimiter, Next: Account hierarchy, Up: Account names++13.10.1 Two space delimiter+---------------------------++Note that hledger's account names, like Ledger's, may contain single+spaces. Because of this, they must be separated from anything following+them on the same line by *two or more spaces*. (Two or more tabs also+work; but spaces are preferred. A single tab is not a separator, unlike+in Ledger.)++ This lets us use expressive account names, while still keeping the+syntax light. Here are some examples:++ assets:accounts receivable ; bad, only one space before the comment+ assets:accounts receivable ; good++ assets:accounts receivable $10 ; bad, one space before the amount+ assets:accounts receivable $10 ; good++ assets:accounts receivable = $1000 ; bad, one space before the balance assignment+ assets:accounts receivable = $1000 ; good++ The two-space delimiter is also required in periodic transaction+rules, between period expression and description:++~ every 5th day YouTube Premium ; bad, one space before the description+~ every 5th day YouTube Premium ; good++ When you are starting out, you can expect this delimiter will trip+you up once or twice. (If it happens too much, you can check account+names strictly to prevent it.)+++File: hledger.info, Node: Account hierarchy, Next: Other account name features, Prev: Two space delimiter, Up: Account names++13.10.2 Account hierarchy+-------------------------++For more precise reporting, we usually divide accounts into more+detailed subaccounts, subsubaccounts, and so on, by writing a full colon+between account name parts. For example, instead of writing 'assets'+and 'expenses', we might write 'assets:bank:checking' and+'expenses:food'. From these names hledger will infer this hierarchy of+five accounts:++assets+assets:bank+assets:bank:checking+expenses+expenses:food++ Or as an outline:++assets+ bank+ checking+expenses+ food++ hledger reports can summarise the account tree to any depth, so you+can make your subcategories as detailed as you like. But don't go+overboard, especially when getting started; simpler categories can be+less work.+++File: hledger.info, Node: Other account name features, Prev: Account hierarchy, Up: Account names++13.10.3 Other account name features+-----------------------------------++Enclosing the account name in parentheses or brackets, like+'(expenses:food)', enables a non-standard bookkeeping feature: virtual+postings.++ Account names can be rewritten and restructured, temporarily or+permanently, by account aliases.+++File: hledger.info, Node: Amounts, Next: Costs, Prev: Account names, Up: Journal++13.11 Amounts+=============++After the account name, there is usually an amount. (Remember: between+account name and amount, there must be two or more spaces.)++ hledger's amount format is flexible, supporting several international+formats. Here are some examples. Amounts have a number (the+"quantity"):++1++ ..and usually a currency symbol or commodity name (more on this+below), to the left or right of the quantity, with or without a+separating space:++$1+4000 AAPL+3 "green apples"++ Amounts can be preceded by a minus sign (or a plus sign, though plus+is the default), The sign can be written before or after a left-side+commodity symbol:++-$1+$-1++ One or more spaces between the sign and the number are acceptable+when parsing (but they won't be displayed in output):+++ $1+$- 1++ Scientific E notation is allowed:++1E-6+EUR 1E3++* Menu:++* Decimal marks::+* Digit group marks::+* Commodity::+++File: hledger.info, Node: Decimal marks, Next: Digit group marks, Up: Amounts++13.11.1 Decimal marks+---------------------++A _decimal mark_ can be written as a period or a comma:++1.23+1,23++ Both of these are common in international number formats, so hledger+is not biased towards one or the other. Because hledger also supports+digit group marks (eg thousands separators), this means that a number+like '1,000' or '1.000' containing just one period or comma is+ambiguous. In such cases, hledger by default assumes it is a decimal+mark, and will parse both of those as 1.++ To help hledger parse such ambiguous numbers accurately, if you use+digit group marks, we recommend declaring the decimal mark explicitly.+You can declare it per commodity with 'commodity' directives, or per+file with a 'decimal-mark' directive at the top of each journal file+(described below).++ hledger also accepts numbers like '10.' with no digits after the+decimal mark (and will sometimes display numbers that way to+disambiguate them - see Trailing decimal marks).+++File: hledger.info, Node: Digit group marks, Next: Commodity, Prev: Decimal marks, Up: Amounts++13.11.2 Digit group marks+-------------------------++In the integer part of the amount quantity (left of the decimal mark),+groups of digits can optionally be separated by a _digit group mark_ - a+comma or period (whichever is not used as decimal mark), an underscore,+an apostrophe, or a space (several Unicode space variants, like no-break+space, are also accepted). So these are all valid amounts in a journal+file:++ $1,000,000.00+ EUR 2.000.000,00+INR 9,99,99,999.00+ CHF 1'000'000.00+ 1_000_000.00+ 1 000 000.00 ; <- ordinary space+ 1 000 000.00 ; <- no-break space+++File: hledger.info, Node: Commodity, Prev: Digit group marks, Up: Amounts++13.11.3 Commodity+-----------------++Amounts in hledger have both a "quantity", which is a signed decimal+number, and a "commodity", which is a currency symbol, stock ticker, or+any word or phrase describing something you are tracking.++ If the commodity name contains non-letters (spaces, numbers, or+punctuation), you must always write it inside double quotes ('"green+apples"', '"ABC123"'). In particular, in a posting amount, a symbol+that begins with '(' before the number, or with '/' after it, or that+contains ')' inside parentheses, must be quoted, eg '"(X)" 10' or '10+"/x"', or it would be read as part of an amount expression.++ If you write just a bare number, that too will have a commodity, with+name '""'; we call that the "no-symbol commodity".++ Actually, hledger combines these single-commodity amounts into more+powerful multi-commodity amounts, which are what it works with most of+the time. A multi-commodity amount could be, eg: '1 USD, 2 EUR, 3.456+TSLA'. In practice, you will only see multi-commodity amounts in+hledger's output; you can't write them directly in the journal file.++ By default, the format of amounts in the journal influences how+hledger displays them in output. This is explained in Commodity display+style below.++ A posting amount can also be an arithmetic expression, like '$47.97 ++$15.75'; see Amount expressions.+++File: hledger.info, Node: Costs, Next: Cost basis, Prev: Amounts, Up: Journal++13.12 Costs+===========++When one commodity is exchanged for another - a currency conversion, or+a purchase or sale of stock - you can record the transacted price or+conversion rate by writing '@ UNITCOST' or '@@ TOTALCOST' after a+posting amount. (hledger docs generically call this a "cost", whether+buying or selling, though "cost" is an overloaded word. "Transacted+cost" or "transacted price" is more precise.) Eg:++2026-01-01 buy euros+ assets:dollars $-123+ assets:euros €100 @ $1.23 ; unit cost (exchange rate)++ or:++2026-01-01 buy euros+ assets:dollars $-123+ assets:euros €100 @@ $123 ; total cost++ The cost should normally be a positive amount. Negative costs are+supported, but can be confusing, as discussed at -infer-market-prices:+market prices from transactions.++ Costs participate in transaction balancing: amounts are converted to+their cost before checking if the transaction is balanced. So you could+also write the above less redundantly, like so:++2026-01-01 buy euros+ assets:dollars ; $-123 is inferred+ assets:euros €100 @ $1.23++ or:++2026-01-01 buy euros+ assets:dollars ; $-123 is inferred+ assets:euros €100 @@ $123++ or even:++2026-01-01 buy euros+ assets:euros €100 ; @@ $123 is inferred+ assets:dollars $-123++ This last form works for transactions involving exactly two+commodities, with neither cost notation nor equity postings. If one of+the postings is recognised as a lot posting, the cost will be attached+to that one. Otherwise the cost will be attached to the first (top)+posting - so it can be important to put the right one first. Here we+had to switch the order of postings, to get the same meaning as above.++ This form is the easiest to make undetected errors with; so it is+rejected by 'hledger check balanced', and by strict mode.++ Reports can show amounts converted to their cost when you add the+'-B/--cost' flag.++ Costs can also be recorded in a more traditional double entry way,+with equity postings; or with both notations at once. See Cost+reporting for a comparison of these styles, and how hledger can convert+between them.+++File: hledger.info, Node: Cost basis, Next: Balance assertions, Prev: Costs, Up: Journal++13.13 Cost basis+================++This section briefly describes the '{}' cost basis syntax, used to+record the nominal cost of an investment being acquired, or to select+lots being transferred or disposed. This is described in more detail+later in Lots and capital gains. If you're not tracking investment lots+and capital gains, you can skip this.++ hledger's cost basis annotations look like Beancount's:+comma-separated parts enclosed in curly braces, after an amount. All+parts are optional, but when present they must be in this order:++ 1. a date, in YYYY-MM-DD format+ 2. a text label, enclosed in double quotes+ 3. a cost, as a single-commodity hledger amount.++ Here are some valid hledger cost basis annotations:++{2026-01-15, "12:05", $50}+{2026-01-15, $50}+{1.000.000,33 EUR}+{$50}+{}++ This means: selling 10 AAPL, originally purchased at $50 each, for+$60 each:++-10 AAPL {$50} @ $60++ Note the preferred order is to write {} before @, as shown.++ hledger can also read Ledger's cost basis syntax. Here, the parts+are written separately, in any order, with different enclosing+characters:++10 AAPL {$50} [2026-01-15] (12:05)++ If a Ledger-style label annotation contains double quotes, they will+be stripped ('("foo")' is read as label 'foo').+++File: hledger.info, Node: Balance assertions, Next: Posting comments, Prev: Cost basis, Up: Journal++13.14 Balance assertions+========================++hledger supports Ledger-style balance assertions in journal files.+These look like, for example, '= EXPECTEDBALANCE' following a posting's+amount. Eg here we assert the expected dollar balance in accounts a and+b after each posting:++2013/1/1+ a $1 = $1+ b = $-1++2013/1/2+ a $1 = $2+ b $-1 = $-2++ After reading a journal file, hledger will check all balance+assertions and report an error if any of them fail. Balance assertions+can protect you from, eg, inadvertently disrupting reconciled balances+while cleaning up old entries. You can disable them temporarily with+the '-I' or '--ignore-assertions' flag, which can be useful for+troubleshooting or for reading Ledger files. (Note: this flag currently+does not disable balance assignments, described below).++ To check rules which should hold at all times, such as "no asset+account is ever negative", see assert directives.++* Menu:++* Assertions and ordering::+* Assertions and multiple files::+* Assertions and costs::+* Assertions and commodities::+* Assertions and subaccounts::+* Assertions and lot subaccounts::+* Assertions and status::+* Assertions and virtual postings::+* Assertions and auto postings::+* Assertions and precision::+* Assertions and hledger add::+++File: hledger.info, Node: Assertions and ordering, Next: Assertions and multiple files, Up: Balance assertions++13.14.1 Assertions and ordering+-------------------------------++hledger calculates and checks an account's balance assertions in date+order (and when there are multiple assertions on the same day, in parse+order). Note this is different from Ledger, which checks assertions+always in parse order, ignoring dates.++ This means in hledger you can freely reorder transactions, postings,+or files, and balance assertions will usually keep working. The+exception is when you reorder multiple postings on the same day, to the+same account, which have balance assertions; those will likely need+updating.+++File: hledger.info, Node: Assertions and multiple files, Next: Assertions and costs, Prev: Assertions and ordering, Up: Balance assertions++13.14.2 Assertions and multiple files+-------------------------------------++If an account has transactions appearing in multiple files, balance+assertions can still work - but _only if those files are part of a+hierarchy made by include directives_.++ If the same files are specified with two '-f' options on the command+line, the assertions in the second will not see the balances from the+first.++ To work around this, arrange your files in a hierarchy with+'include'. Or, you could concatenate the files temporarily, and process+them like one big file.++ This is for stable, predictable reports: the file hierarchy is part+of your data, while the order of command line arguments is not, and+reordering your arguments should not change whether your assertions+pass.+++File: hledger.info, Node: Assertions and costs, Next: Assertions and commodities, Prev: Assertions and multiple files, Up: Balance assertions++13.14.3 Assertions and costs+----------------------------++Balance assertions ignore costs, and should normally be written without+one:++2019/1/1+ (a) $1 @ €1 = $1++ We do allow costs to be written in balance assertion amounts,+however, and print shows them, but they don't affect whether the+assertion passes or fails. This is for backward compatibility+(hledger's close command used to generate balance assertions with+costs), and because balance _assignments_ do use costs (see below).+++File: hledger.info, Node: Assertions and commodities, Next: Assertions and subaccounts, Prev: Assertions and costs, Up: Balance assertions++13.14.4 Assertions and commodities+----------------------------------++The balance assertions described so far are "*single commodity balance+assertions*": they assert and check the balance in one commodity,+ignoring any others that may be present. This is how balance assertions+work in Ledger also.++ If an account contains multiple commodities, you can assert their+balances by writing multiple postings with balance assertions, one for+each commodity:++2013/1/1+ usd $-1+ eur €-1+ both++2013/1/2+ both 0 = $1+ both 0 = €1++ In hledger you can make a stronger "*sole commodity balance+assertion*" by writing two equals signs ('== EXPECTEDBALANCE'). This+also asserts that there are no other commodities in the account besides+the asserted one (or at least, that their current balance is zero):++2013/1/1+ usd $-1 == $-1 ; these sole commodity assertions succeed+ eur €-1 == €-1+ both ;== $1 ; this one would fail because 'both' contains $ and €++ It's less easy to make a "*sole commodities balance assertion*" (note+the plural) - ie, asserting that an account contains two or more+specified commodities and no others. It can be done by++ 1. isolating each commodity in a subaccount, and asserting those+ 2. and also asserting there are no commodities in the parent account+ itself:++2013/1/1+ usd $-1+ eur €-1+ both 0 == 0 ; nothing up my sleeve+ both:usd $1 == $1 ; a dollar here+ both:eur €1 == €1 ; a euro there+++File: hledger.info, Node: Assertions and subaccounts, Next: Assertions and lot subaccounts, Prev: Assertions and commodities, Up: Balance assertions++13.14.5 Assertions and subaccounts+----------------------------------++All of the balance assertions above (both '=' and '==') are+"*subaccount-exclusive balance assertions*"; they ignore any balances+that exist in deeper subaccounts.++ In hledger you can make "*subaccount-inclusive balance assertions*"+by adding a star after the equals ('=*' or '==*'):++2019/1/1+ equity:start+ assets:checking $10+ assets:savings $10+ assets $0 ==* $20 ; assets + subaccounts contains $20 and nothing else+++File: hledger.info, Node: Assertions and lot subaccounts, Next: Assertions and status, Prev: Assertions and subaccounts, Up: Balance assertions++13.14.6 Assertions and lot subaccounts+--------------------------------------++Lot subaccounts (a special kind of subaccount for tracking lots,+discussed in "Lots and capital gains" below) have only limited support+for balance assertions: the assertions will be checked correctly only if+all postings to that lot mention the subaccount name explicitly.++ Since it's common practice to leave lot subaccounts implicit,+generally you should avoid writing balance assertions on individual+lots. ('close --lots' also follows this rule.) If you forget, the+balance assertion failure message will remind you. If you really need a+balance assertion, you can usually write it on the parent account+instead.++ (The restriction is because transaction balancing amounts, balance+assignments, and balance assertions must be calculated and checked+before lot movements are known.) See also Lot postings and balance+assertions.+++File: hledger.info, Node: Assertions and status, Next: Assertions and virtual postings, Prev: Assertions and lot subaccounts, Up: Balance assertions++13.14.7 Assertions and status+-----------------------------++Balance assertions always consider postings of all statuses (unmarked,+pending, or cleared); they are not affected by the '-U'/'--unmarked' /+'-P'/'--pending' / '-C'/'--cleared' flags or the 'status:' query.+++File: hledger.info, Node: Assertions and virtual postings, Next: Assertions and auto postings, Prev: Assertions and status, Up: Balance assertions++13.14.8 Assertions and virtual postings+---------------------------------------++Balance assertions always consider both real and virtual postings; they+are not affected by the '--real/-R' flag or 'real:' query.+++File: hledger.info, Node: Assertions and auto postings, Next: Assertions and precision, Prev: Assertions and virtual postings, Up: Balance assertions++13.14.9 Assertions and auto postings+------------------------------------++Balance assertions _are_ affected by the '--auto' flag, which generates+auto postings, which can alter account balances. Because auto postings+are optional in hledger, accounts affected by them effectively have two+balances. But balance assertions can only test one or the other of+these. So to avoid making fragile assertions, either:++ * assert the balance calculated with '--auto', and always use+ '--auto' with that file+ * or assert the balance calculated without '--auto', and never use+ '--auto' with that file+ * or avoid balance assertions on accounts affected by auto postings+ (or avoid auto postings entirely).+++File: hledger.info, Node: Assertions and precision, Next: Assertions and hledger add, Prev: Assertions and auto postings, Up: Balance assertions++13.14.10 Assertions and precision+---------------------------------++Balance assertions compare the exactly calculated amounts, which are not+always what is shown by reports. Eg a commodity directive may limit the+display precision, but this will not affect balance assertions. Balance+assertion failure messages show exact amounts.+++File: hledger.info, Node: Assertions and hledger add, Prev: Assertions and precision, Up: Balance assertions++13.14.11 Assertions and hledger add+-----------------------------------++The 'add' command also accepts balance assertions (and assignments), and+re-checks all of the journal's assertions as you enter amounts; see add+and balance assertions.+++File: hledger.info, Node: Posting comments, Next: Tags, Prev: Balance assertions, Up: Journal++13.15 Posting comments+======================++Text following ';', at the end of a posting line, and/or on indented+lines immediately below it, form comments for that posting. They are+reproduced by 'print' but otherwise ignored, except they may contain+tags, which are not ignored.++2012-01-01+ expenses 1 ; a comment for posting 1+ assets+ ; a comment for posting 2+ ; a second comment line for posting 2+++File: hledger.info, Node: Tags, Next: Directives, Prev: Posting comments, Up: Journal++13.16 Tags+==========++Tags are a way to add extra labels or data fields to transactions,+postings, or accounts, which you can match with a 'tag:' query in+reports. (See queries below.)++ Tags are a single word or hyphenated word, immediately followed by a+full colon, written within a comment. (Yes, storing data in comments is+slightly weird.) Here's a transaction with a tag:++2025-01-01 groceries ; some-tag:+ assets:checking+ expenses:food $1++ A tag can have a value: a single line of text written after the colon+(tag values can't contain newlines):++2025-01-01 groceries ; tag1: this is tag1's value++ Multiple tags can be separated by comma (so tag values can't contain+commas):++2025-01-01 groceries ; tag1:value 1, tag2:value 2, comment text++ A tag can have multiple values:++2025-01-01 groceries ; tag1:value 1, tag1:value 2++ You can write each tag on its own line if you prefer (but they still+can't contain commas):++2025-01-01 groceries+ ; tag1: value 1+ ; tag2: value 2++ Tags can be attached to individual postings, rather than the overall+transaction:++2025-01-01 rent+ assets:checking+ expenses:rent $1000 ; postingtag:++ Tags can be attached to accounts, in their account directive:++account assets:checking ; acct-number: 123-45-6789++* Menu:++* Tag propagation::+* Displaying tags::+* When to use tags ?::+* Tag names::+* Tag values::+++File: hledger.info, Node: Tag propagation, Next: Displaying tags, Up: Tags++13.16.1 Tag propagation+-----------------------++In addition to what they are attached to, tags also affect related data+in a few ways, allowing more powerful queries:++ 1. Accounts -> postings. Postings inherit tags from their account.+ 2. Transactions -> postings. Postings inherit tags from their+ transaction.+ 3. Postings -> transactions. Transactions also acquire the tags of+ their postings.++ So when you use a 'tag:' query to match whole transactions,+individual postings, or accounts, it's good to understand how tags+behave. Here's an example showing all three kinds of propagation:++account assets:checking+account expenses:food ; atag:++2025-01-01 groceries ; ttag:+ assets:checking ; p1tag:+ expenses:food $1 ; p2tag:++data part has tags explanation+---------------------------------------------------------------------------+assets:checking account no tags attached+expenses:food atag atag: in comment+account+assets:checkingp1tag, ttag p1tag: in comment, ttag acquired from+posting transaction+expenses:food p2tag, atag, p2tag: in comment, atag from account, ttag+posting ttag from transaction+groceries ttag, p1tag, ttag: in comment, p1tag from first+transaction p2tag, atag posting, p2tag and atag from second+ posting+++File: hledger.info, Node: Displaying tags, Next: When to use tags ?, Prev: Tag propagation, Up: Tags++13.16.2 Displaying tags+-----------------------++You can use the 'tags' command to list tag names or values.++ The 'print' command also shows tags.++ You can use -pivot to display tag values in other reports, in various+ways (eg appended to account names, like pseudo subaccounts).+++File: hledger.info, Node: When to use tags ?, Next: Tag names, Prev: Displaying tags, Up: Tags++13.16.3 When to use tags ?+--------------------------++Tags provide more dimensions of categorisation, complementing accounts+and transaction descriptions. When to use each of these is somewhat a+matter of taste. Accounts have the most built-in support, and regex+queries on descriptions are also quite powerful. So you may not need+tags at all. But if you want to track multiple cross-cutting+categories, they can be a good fit. For example, you could tag+trip-related transactions with 'trip: YEAR:PLACE', without disturbing+your usual account categories.+++File: hledger.info, Node: Tag names, Next: Tag values, Prev: When to use tags ?, Up: Tags++13.16.4 Tag names+-----------------++What is allowed in a tag name ? Any sequence of non-whitespace+non-newline characters. Eg '😀:' is a valid tag.++ For extra error checking, you can declare valid tag names with the+'tag' directive, and then enforce these with the 'check' command. But+note that tags are detected quite loosely at present, sometimes where+you didn't intend them. Eg a comment like '; see https://foo.com' adds+a 'https' tag.++ There are several tag names which have special significance to+hledger. They are explained elsewhere, but here's a quick reference:++ type -- declares an account's type+ alias -- declares an account's or commodity's alias+ lots -- declares an account's or commodity's lot tracking (cost basis method)+ date -- overrides a posting's date+ date2 -- overrides a posting's secondary date+ assert -- appears on txns generated by close --assert+ retain -- appears on txns generated by close --retain+ start -- appears on txns generated by close --migrate/--close/--open/--assign+ t -- appears on postings generated from timedot letters++ generated-transaction -- appears on txns generated by a periodic rule+ modified-transaction -- appears on txns which have had auto postings added+ generated-posting -- appears on generated postings+ cost-posting -- appears on postings which have (or could have) a cost,+ and which have equivalent conversion postings in the transaction+ conversion-posting -- appears on postings which are to a V/Conversion account+ and which have an equivalent cost posting in the transaction+ ptype -- appears on lot postings, with their type (acquire, dispose, etc.)+ feesplit-posting -- appears on fee parts split off a lot transfer posting+ lotsplit-posting -- appears on the parts of a posting split across several lots (with --lots)+ lot-parent-assertion -- appears on postings carrying a balance assertion moved+ from a posting that was split across several lots++ The second group above (generated-transaction, etc.) are normally+hidden, with a '_' prefix added. This means 'print' doesn't show them+by default; but you can still use them in queries. You can add the+'--verbose-tags' flag to make them visible in 'print' output, which can+be useful for troubleshooting.+++File: hledger.info, Node: Tag values, Prev: Tag names, Up: Tags++13.16.5 Tag values+------------------++What is allowed in a tag value ? Any sequence of non-comma non-newline+characters, with surrounding whitespace removed.++ Note a tag can have multiple values, if the tag is repeated. Eg ';+foo:a, foo:b'.+++File: hledger.info, Node: Directives, Next: account directive, Prev: Tags, Up: Journal++13.17 Directives+================++You can add directives to a 'journal' file, to add error checking,+improve parsing, et cetera. Directives begin with a keyword, not a+date. Some of them can have indented subdirectives. hledger's+directives are broadly similar to Ledger's, though with differences.++* Menu:++* Directive scopes::+* Combining file trees::+* Directives summary::+++File: hledger.info, Node: Directive scopes, Next: Combining file trees, Up: Directives++13.17.1 Directive scopes+------------------------++Directives differ in which entries they affect. Some affect only the+following entries, others affect both preceding and following entries;+and some reach only the current file and its subfiles, others reach+every file. Assuming this command and file layout:++hledger -f main.journal -f other.journal++main.journal ; the parent file+ include a.journal ; a child of main.journal+ include aa.journal ; a child of a.journal+ include b.journal ; a child of main.journal, and a sibling of a.journal++other.journal ; a separate file tree++ here are the possible scopes, for a directive written in 'a.journal':++scope affects+--------------------------------------------------------------------------+*rest of file following entries in or below 'a.journal' (including++ subfiles* 'aa.journal' if it is included after the directive)+*rest of file as above, plus following entries in parent files+tree* ('main.journal' entries after the 'include a.journal'+ directive, including 'b.journal')+*file tree* all entries in 'main.journal', 'a.journal',+ 'aa.journal' and 'b.journal', before and after the+ directive+*all files* all entries in all file trees, no matter where the+ directive is written++ The limited scopes help keep reports stable and deterministic,+independent of the order of -f options or include directives. This is+sometimes inconvenient, but there are usually workarounds. In+particular, to have account aliases affect all entries in a file tree,+declare them at the start of the main file, before any 'include's. (Or+to affect all file trees specified at runtime, use '--alias' options.)+++File: hledger.info, Node: Combining file trees, Next: Directives summary, Prev: Directive scopes, Up: Directives++13.17.2 Combining file trees+----------------------------++When you read several file trees (with several '-f' options), hledger+reads and processes each one separately, then combines them. So one+file tree can't change how another's entries are read: account and+commodity aliases, decimal marks, transaction balancing, balance+assertions and assert directives, auto postings, forecast transactions+and lot tracking all work within each file tree.++ But a few declarations reach all file trees ("all files" in the table+below):++ * Account declarations, including account types and display order.+ * Commodity declarations, including display styles. If file trees+ declare a commodity's display style differently, the last one is+ used.+ * Payee and tag declarations.+ * 'P' market prices, used for valuation.+ * Commodity aliases, but only for valuation, and only as a last+ resort: when market prices can't convert an amount, eg if it's in+ an alias declared by another file tree. If file trees declare an+ alias differently (for a different commodity, or with a different+ quantity), converting to or from it this way is an error.++ So you can combine file trees that weren't designed to work together.+The interactions to watch for are conflicting display styles, account+types, and market prices.+++File: hledger.info, Node: Directives summary, Prev: Combining file trees, Up: Directives++13.17.3 Directives summary+--------------------------++directivewhat it does scope+---------------------------------------------------------------------------+*Affects+file+reading:*+*'include'*Includes entries from another file (a "subfile"),+ as if they were written inline.+*'comment'*Ignores following entries and directives, until rest of+ 'end comment'. file ++ subfiles+*'alias'*Rewrites following matched account names, until rest of+ 'end aliases'. file ++ subfiles+*'account'*Rewrites following matched account names to this rest of+'alias:' account's full name, until 'end aliases'. file ++tag subfiles+*'decimal-mark'*Declares the decimal mark for parsing followingrest of+ amounts of all commodities, until the next file ++ 'decimal-mark' (subfiles can override). subfiles+*'commodity'*Declares the decimal mark for parsing following rest of+sample amounts of this commodity ('decimal-mark' can file tree+amount override).+*Declares+data:*+*'account'*Declares an account, and its display order. all files+*'account'*Declares the account's type. all files+'type:'+tag+*'account'*Declares the account's cost basis method. file tree+'lots:'+tag+*'commodity'*Declares a commodity symbol. all files+*'commodity'*Declares the commodity's display style. all files+sample+amount+*'commodity'*Declares equivalent or related symbols for this file tree+'alias:' commodity.+tag+*'commodity'*Declares that the commodity tracks lots, and file tree+'lots:' optionally their cost basis method.+tag+*'payee'*Declares a payee name. all files+*'tag'* Declares a tag name. all files+*'P'* Declares a commodity's market price on some date, all files+ for value and gain reports.+*Generates+data:*+*'='* Generates extra postings (after matched postings), file tree+ with '--auto'. (Does not see sibling files:+ #1212.)+*'~'* Generates future transactions (after latest file tree+ transaction in file tree, by default), with+ '--forecast'.+*'~'* Generates budget goals and actual/goal percentages, all files+ with 'balance --budget'.+*Checks+data:*+*'assert'*Declares a standing rule, a query that must match file tree+ no rows or some rows, checked like balance+ assertions.+*File+reading+(legacy/deprecated):*+'apply Prepends a common parent account to all following rest of+account' account names, until 'end apply account'. file ++ subfiles+'apply Sets a default year for following yearless dates, rest of+year' until 'end apply year'. file ++ subfiles+'D' Sets a default commodity for following no-symbol rest of+ amounts. Also sets its parsing decimal mark file ++ (overridden by 'commodity' or 'decimal-mark') and subfiles+ display style (overridden by 'commodity').+'Y' Sets a default year for following yearless dates. rest of+ file ++ subfiles+other These other Ledger directives are accepted but+ ignored.+++File: hledger.info, Node: account directive, Next: alias directive, Prev: Directives, Up: Journal++13.18 'account' directive+=========================++'account' directives can be used to declare accounts (ie, the places+that amounts are transferred from and to). Though not required, these+declarations can provide several benefits:++ * They can document your intended chart of accounts, providing a+ reference.+ * They can store additional account information as comments, or as+ tags which can be used to filter or pivot reports.+ * They can restrict which accounts may be posted to by transactions,+ eg in strict mode, which helps prevent errors.+ * They influence account display order in reports, allowing+ non-alphabetic sorting (eg Revenues to appear above Expenses).+ * They can help hledger know your accounts' types (asset, liability,+ equity, revenue, expense), enabling reports like balancesheet and+ incomestatement.+ * They help with account name completion (in hledger add,+ hledger-web, hledger-iadd, ledger-mode, etc.)++ They are written as the word 'account' followed by a hledger-style+account name. Eg:++account assets:bank:checking++ Any indented subdirectives are ignored, except Ledger's 'alias'+subdirective (see Account aliases).++* Menu:++* Account comments::+* Account tags::+* Account aliases::+* Account error checking::+* Account display order::+* Account types::+++File: hledger.info, Node: Account comments, Next: Account tags, Up: account directive++13.18.1 Account comments+------------------------++Text following *two or more spaces* and ';' at the end of an account+directive line, and/or following ';' on indented lines immediately below+it, form comments for that account.++ Same-line account comments require two+ spaces before ';' because+that character can appear in account names.++account assets:bank:checking ; same-line comment, at least 2 spaces before the semicolon+ ; next-line comment+ ; some tags - type:A, acctnum:12345+++File: hledger.info, Node: Account tags, Next: Account aliases, Prev: Account comments, Up: account directive++13.18.2 Account tags+--------------------++An account directive's comment may contain tags. These will be+inherited by all postings using that account, except where the posting+already has a value for that tag. (A posting tag overrides an account+tag.) Note, these tags will be queryable but won't be shown in 'print'+output, even with -verbose-tags.+++File: hledger.info, Node: Account aliases, Next: Account error checking, Prev: Account tags, Up: account directive++13.18.3 Account aliases+-----------------------++An 'alias:' tag on an account directive declares an alternate, usually+shorter, name for that account. This could make data entry quicker, and+your journal less verbose (but also adds more names for you to+remember). Eg:++account assets:bank:checking ; alias: checking++2024-01-01+ expenses:food 5+ checking++ When hledger reads this, it rewrites 'checking' to+'assets:bank:checking'. Reports, queries and 'print' output show only+the full name. Subaccounts are rewritten too: 'checking:pending'+becomes 'assets:bank:checking:pending'. (The alias must match the whole+account name or its leading components, exactly and case sensitively;+'Checking', 'checkingfoo' or 'old:checking' would not be affected.)++ To declare multiple aliases, add more 'alias:' tags. A Ledger-style+'alias' subdirective, indented below the account directive, is also+accepted, and treated as an 'alias:' tag. To list the accounts with+their aliases, run 'hledger accounts --show-aliases'; to find the+account(s) with a certain alias, run 'hledger accounts --show-aliases+ALIAS'.++ An alias affects the entries which follow it, in the current file and+any files it includes (see directive scopes), until an 'end aliases'+directive. So it's best to declare accounts at the start of your main+file, before any 'include' directives.++ More powerful aliases, such as regular expression aliases which+rewrite many accounts at once, can be declared with the 'alias'+directive, described below. An alias: tag is equivalent to a basic+alias directive written just after the account directive:++account assets:bank:checking ; alias: checking++account assets:bank:checking+alias checking = assets:bank:checking++ You can also apply aliases at runtime, without editing your files,+using the '--alias' option.+++File: hledger.info, Node: Account error checking, Next: Account display order, Prev: Account aliases, Up: account directive++13.18.4 Account error checking+------------------------------++By default, accounts need not be declared; they come into existence when+a posting references them. This is convenient, but it means hledger+can't warn you when you mis-spell an account name in the journal.+Usually you'll find that error later, as an extra account in balance+reports, or an incorrect balance when reconciling.++ In strict mode, enabled with the '-s'/'--strict' flag, or when you+run 'hledger check accounts', hledger will report an error if any+transaction uses an account name that has not been declared by an+account directive. Some notes:++ * The declaration is case-sensitive; transactions must use the+ correct account name capitalisation.+ * Account declarations affect all files (see directive scopes). The+ position of account directives within the file does not matter,+ though it's usual to put them at the top.+ * Accounts can only be declared in 'journal' files, but will affect+ included files of all types.+ * It's currently not possible to declare "all possible subaccounts"+ with a wildcard; every account posted to must be declared.+ * As an exception: lot subaccounts (a final account name component+ like ':{2026-01-15, $50}') are always ignored by 'check accounts',+ and need not be declared.+ * Also exempt are the accounts which hledger chooses for the postings+ it generates: equity conversion postings (from '--infer-equity'),+ gain postings (in lot disposals), and imbalance postings (from+ '--infer-imbalance'). Postings which you write to those accounts+ are checked as usual.+++File: hledger.info, Node: Account display order, Next: Account types, Prev: Account error checking, Up: account directive++13.18.5 Account display order+-----------------------------++Account directives also cause hledger to display accounts in a+particular order, not just alphabetically. Eg, here is a conventional+ordering for the top-level accounts:++account assets+account liabilities+account equity+account revenues+account expenses++ Now hledger displays them in that order:++$ hledger accounts+assets+liabilities+equity+revenues+expenses++ If there are undeclared accounts, those will be displayed last, in+alphabetical order.++ Sorting is done within each group of sibling accounts, at each level+of the account tree. Eg, a declaration like 'account parent:child'+influences 'child''s position among its siblings.++ Note, it does not affect 'parent''s position; for that, you need an+'account parent' declaration.++ Sibling accounts are always displayed together; hledger won't display+'x:y' in between 'a:b' and 'a:c'.++ An account directive both declares an account as a valid posting+target, and declares its display order; you can't easily do one without+the other.+++File: hledger.info, Node: Account types, Prev: Account display order, Up: account directive++13.18.6 Account types+---------------------++hledger knows that in accounting there are three main account types:++'Asset' 'A' things you own+'Liability' 'L' things you owe+'Equity' 'E' owner's investment, balances the two above++ and two more representing changes in these:++'Revenue' 'R' inflows (also known as 'Income')+'Expense' 'X' outflows++ hledger also uses a few subtypes:++'Cash' 'C' liquid assets (subtype+ of Asset)+'Conversion' 'V' commodity conversions+ equity (subtype of+ Equity)+'Gain' 'G' realised capital+ gains/losses (subtype+ of Revenue)+'UnrealisedGain' 'U' accumulated unrealised+ capital gains (subtype+ of Equity)+'Imbalance' 'M' transactions'+ tolerated imbalances,+ shown by+ '--infer-imbalance'+ (subtype of Equity)++ As a convenience, hledger will detect these types automatically from+english account names. But it's better to declare them explicitly by+adding a 'type:' tag in the account directives. The tag's value can be+any of the types or one-letter abbreviations above.++ Here is a typical set of account type declarations. Subaccounts will+inherit their parent's type, or can override it:++account assets ; type: A+account liabilities ; type: L+account equity ; type: E+account revenues ; type: R+account expenses ; type: X++account assets:bank ; type: C+account assets:cash ; type: C++account equity:conversion ; type: V+account equity:unrealised-gain ; type: U++account revenues:gain ; type: G++ This enables the easy balancesheet, balancesheetequity, cashflow and+incomestatement reports, and querying by type:.++ Tips:++ * You can list accounts and their types, for troubleshooting:++ $ hledger accounts --types [ACCTPAT] [type:TYPECODES] [-DEPTH] [--locations]++ * It's a good idea to declare at least one account for each account+ type. Having some types declared and some inferred can disrupt+ certain reports.++ * The rules for inferring types from account names are as follows+ (using Regular expressions).+ If they don't work for you, just ignore them and declare your types+ with 'type:' tags.++ If account's name contains this case insensitive regular expression | its type is+ --------------------------------------------------------------------|-------------+ ^assets?(:.+)?:(cash|bank|che(ck|que?)(ing)?|savings?|current)(:|$) | Cash+ ^assets?(:|$) | Asset+ ^(debts?|liabilit(y|ies))(:|$) | Liability+ ^equity:(trad(e|ing)|conversion)s?(:|$) | Conversion+ ^equity:unreali[sz]ed([- ](capital[- ])?gains?)?(:|$) | UnrealisedGain+ ^equity:imbalances?(:|$) | Imbalance+ ^equity(:|$) | Equity+ ^(income|revenue)s?:(capital[- ]?)?(gains?|loss(es)?)(:|$) | Gain+ ^(income|revenue)s?(:|$) | Revenue+ ^expenses?(:|$) | Expense++ * As mentioned above, subaccounts will inherit a type from their+ parent account. To be precise, an account's type is decided by the+ first of these that exists:++ 1. A 'type:' declaration for this account.+ 2. A 'type:' declaration in the parent accounts above it,+ preferring the nearest.+ 3. An account type inferred from this account's name.+ 4. An account type inferred from a parent account's name,+ preferring the nearest parent.+ 5. Otherwise, it will have no type.++ * Account aliases can disrupt account types.+++File: hledger.info, Node: alias directive, Next: assert directive, Prev: account directive, Up: Journal++13.19 'alias' directive+=======================++(Note: this section is about account aliases, not commodity aliases or+command aliases.)++ 'alias' directives are a more general and powerful form of the+account aliases tags described above. (There is also a runtime variant,+defined with the '--alias' option.)++ Account alias rules rewrite your account names, or parts of them,+after reading the journal (affecting both directives and transactions),+before generating reports. They do not affect account names being+entered via hledger add or hledger-web.++ Account aliases can be useful for:++ * expanding shorthand account names to their full form, allowing+ easier data entry and a less verbose journal+ * adapting old journals to your current chart of accounts+ * experimenting with new account organisations, like a new hierarchy+ * combining two accounts into one, eg to see their sum or difference+ on one line+ * customising reports++* Menu:++* Basic aliases::+* Regex aliases::+* --alias option::+* Combining aliases::+* Aliases and multiple files::+* end aliases directive::+* Aliases can generate bad account names::+* Aliases and account types::+++File: hledger.info, Node: Basic aliases, Next: Regex aliases, Up: alias directive++13.19.1 Basic aliases+---------------------++To set an account alias, use the 'alias' directive in your journal file.+This affects all subsequent journal entries in the current file or its+included files (but note: not sibling or parent files; see directive+scopes). The spaces around the = are optional:++alias OLD = NEW++ Or, you can use '--alias 'OLD=NEW'' on the command line.++ Or, for a declared account, you can write the alias as an 'alias:'+tag on its account directive.++ OLD and NEW are case sensitive full account names. hledger will+replace any occurrence of the old account name with the new one.+Subaccounts are also affected. Eg:++alias checking = assets:bank:wells fargo:checking+; rewrites "checking" to "assets:bank:wells fargo:checking", or "checking:a" to "assets:bank:wells fargo:checking:a"+++File: hledger.info, Node: Regex aliases, Next: --alias option, Prev: Basic aliases, Up: alias directive++13.19.2 Regex aliases+---------------------++There is also a more powerful variant that uses a regular expression,+indicated by wrapping the pattern in forward slashes. (This is the only+place where hledger requires forward slashes around a regular+expression.)++ Eg:++alias /REGEX/ = REPLACEMENT++ or:++$ hledger --alias '/REGEX/=REPLACEMENT' ...++ Any part of an account name matched by REGEX will be replaced by+REPLACEMENT. REGEX is case-insensitive as usual.++ If you need to match a forward slash, escape it with a backslash, eg+'/\/=:'.++ If REGEX contains parenthesised match groups, these can be referenced+by the usual backslash and number in REPLACEMENT:++alias /^(.+):bank:([^:]+):(.*)/ = \1:\2 \3+; rewrites "assets:bank:wells fargo:checking" to "assets:wells fargo checking"++ REPLACEMENT continues to the end of line (or on command line, to end+of option argument), so it can contain trailing whitespace.+++File: hledger.info, Node: --alias option, Next: Combining aliases, Prev: Regex aliases, Up: alias directive++13.19.3 '--alias' option+------------------------++The '--alias' command line option defines an account alias, using the+same syntax as an 'alias' directive (basic or regex), without editing+your files. Eg:++$ hledger bal --alias checking=assets:bank:checking+$ hledger bal --alias '/^expenses:(food|dining)/=expenses:food'++ It can be repeated to define more aliases. These aliases affect all+entries in all files (including CSV, timeclock and timedot files),+wherever the option appears on the command line; and they are applied+after any 'alias' directives or 'alias:' tags (see Combining aliases).+They are not cleared by 'end aliases'. This makes '--alias' useful for+trying out aliases interactively, or for customising particular reports.+You can also put '--alias' options in a config file.+++File: hledger.info, Node: Combining aliases, Next: Aliases and multiple files, Prev: --alias option, Up: alias directive++13.19.4 Combining aliases+-------------------------++You can define as many aliases as you like, using journal directives+and/or command line options.++ Recursive aliases - where an account name is rewritten by one alias,+then by another alias, and so on - are allowed. Each alias sees the+effect of previously applied aliases.++ In such cases it can be important to understand which aliases will be+applied and in which order. For (each account name in) each journal+entry, we apply:++ 1. 'alias' directives preceding the journal entry, most recently+ parsed first (ie, reading upward from the journal entry, bottom to+ top)+ 2. then any parent account from 'apply account' directives is+ prepended+ 3. then '--alias' options, in the order they appeared on the command+ line (left to right).++ In other words, for (an account name in) a given journal entry:++ * the nearest alias declaration before/above the entry is applied+ first+ * the next alias before/above that will be applied next, and so on+ * aliases defined after/below the entry do not affect it.++ This gives nearby aliases precedence over distant ones, and helps+provide semantic stability - aliases will keep working the same way+independent of which files are being read and in which order.++ In case of trouble, adding '--debug=6' to the command line will show+which aliases are being applied when.+++File: hledger.info, Node: Aliases and multiple files, Next: end aliases directive, Prev: Combining aliases, Up: alias directive++13.19.5 Aliases and multiple files+----------------------------------++As explained at Directive scopes, 'alias' directives (and 'alias:' tags)+do not affect parent or sibling files. Eg in this command,++hledger -f a.aliases -f b.journal++ account aliases defined in a.aliases will not affect b.journal.+Including the aliases doesn't work either:++include a.aliases++2023-01-01 ; not affected by a.aliases+ foo 1+ bar++ This means that account aliases should usually be declared at the+start of your top-most file, like this:++alias foo=Foo+alias bar=Bar++2023-01-01 ; affected by aliases above+ foo 1+ bar++include c.journal ; also affected++ To affect all files read, whether they are included, or referenced by+'-f' or the 'import' command, use '--alias' options (which could be in a+config file). Eg here the alias affects both a.journal and b.journal:++hledger -f a.journal -f b.journal --alias foo=Foo+++File: hledger.info, Node: end aliases directive, Next: Aliases can generate bad account names, Prev: Aliases and multiple files, Up: alias directive++13.19.6 'end aliases' directive+-------------------------------++This directive clears (forgets) all account aliases from 'alias'+directives and account 'alias:' tags seen so far (but not aliases from+command line '--alias' options):++end aliases+++File: hledger.info, Node: Aliases can generate bad account names, Next: Aliases and account types, Prev: end aliases directive, Up: alias directive++13.19.7 Aliases can generate bad account names+----------------------------------------------++Be aware that account aliases can produce malformed account names, which+could cause confusing reports or invalid 'print' output. For example,+you could erase all account names:++2021-01-01+ a:aa 1+ b++$ hledger print --alias '/.*/='+2021-01-01+ 1++ The above 'print' output is not a valid journal. Or you could insert+an illegal double space, causing 'print' output that would give a+different journal when reparsed:++2021-01-01+ old 1+ other++$ hledger print --alias old="new USD" | hledger -f- print+2021-01-01+ new USD 1+ other+++File: hledger.info, Node: Aliases and account types, Prev: Aliases can generate bad account names, Up: alias directive++13.19.8 Aliases and account types+---------------------------------++If an account with a type declaration (see Declaring accounts > Account+types) is renamed by an alias, normally the account type remains in+effect.++ However, renaming in a way that reshapes the account tree (eg+renaming parent accounts but not their children, or vice versa) could+prevent child accounts from inheriting the account type of their+parents.++ Secondly, if an account's type is being inferred from its name,+renaming it by an alias could prevent or alter that.++ If you are using account aliases and the 'type:' query is not+matching accounts as you expect, try troubleshooting with the accounts+command, eg something like:++$ hledger accounts --types -1 --alias assets=bassetts+++File: hledger.info, Node: assert directive, Next: comment directive, Prev: alias directive, Up: Journal++13.20 'assert' directive+========================++In addition to the point-in-time balance assertions in transaction+entries, you can use 'assert' directives to declare more general+*journal assertions*. These are special queries asserting that certain+report results do or do not exist at specified times. Like balance+assertions, hledger checks these each time it reads the journal, unless+you use '--ignore-assertions' or '-I'. You can declare conditions or+goals that you want to be upheld, and whenever hledger reads the+journal, if any rule is broken, it will report an error. Think "guard+rails for your finances". (Note, a rule is only as good as its query,+so test your new rules.)++ The syntax is:++assert (none|some)[ PERIODEXPR][ QUERY]++ Ie, the 'assert' keyword followed by 'none' or 'some', then an+optional period expression specifying when to check the assertion, then+a two-or-more-spaces delimiter and a query specifying which postings or+report rows to look for. The query is written as on the command line,+with quotes around terms containing spaces. A ';' comment can follow.++ A rule with a report interval can be followed by indented 'skip'+lines, each naming a date or period whose checks should be skipped, with+an optional comment (useful for recording the reason). These skip+checks, not data: postings in a skipped period still count in later+balances. As usual, a range's end date is exclusive. Eg:++assert none daily type:A balance:<0 ; no asset account is ever negative+ skip 2026-03-04..2026-03-08 ; transfer delayed by the bank holiday+ skip 2026-05 ; moving house++ A check is skipped if a date in a 'skip' line is among the dates it+examines. For a rule with a 'balance:' term and no 'change:' term, that+is the period's last day (where its balance is tested); for other rules,+it's any day in the period.++ Here are some examples. (Aligning is optional; just remember to put+at least two spaces before each query.):++assert none ; no postings exist+assert some ; some postings exist++; journal maintenance+assert some desc:'opening balances' ; the journal has an opening balances entry+assert none assets:oldbank date:2025- ; nothing is posted to a closed account+assert some assets:checking date:'-7 days..' ; bank data has been imported/added recently++; income+assert some monthly to this month income:salary ; there's a salary transaction in each past month+assert none monthly to this month income:salary change:<2000 ; at least this much was earned in each past month+assert none monthly to this month income:salary change:>-2000 ; a more careful signed test, handling contrabalances & sign typos+assert some monthly to this month desc:invoice any:'receivable amt:>0' ; an invoice was sent in each past month+assert some monthly to this month desc:'payment for.*invoice' ; an invoice payment was received in each past month+assert none assets:receivable balance:>15000 ; unpaid invoices are less than this, currently++; assets+assert none daily type:A balance:<0 ; no asset account is ever negative (at end of day), in any commodity+assert none daily assets:savings balance:<+10000 ; savings never drop below this much+assert some assets:savings balance:>=+20000 ; savings hold at least this much, currently+assert some monthly to this month not:tag:clopen assets:investments depth:2 change:>300 ; at least this much was invested in each past month (ignoring closing/opening entries)++; assets and liabilities+assert some taxes type:AL depth:0 balance:>0 ; estimated tax savings exceed estimated tax due, currently++; liabilities+assert some monthly to this month liabilities:card amt:>0 any:'assets amt:<0' ; a credit card payment was made in each past month+assert none monthly liabilities:card balance:<-3000 ; no month ends with more than this much owed on the credit card+assert none liabilities:card balance:<-500 ; current credit card balance is less than this++; expenses+assert none expenses:misc amt:>+10 ; no single misc expense is larger than this (in any currency)+assert none monthly expenses:dining change:>+$300 ; no month has more than this much $ dining expense+assert none monthly expenses:dining depth:2 change:>+$300 ; the same, but include subaccounts like expenses:dining:fine++ Most query terms, like 'desc:', 'acct:', or 'amt:', select postings.+'balance:' and 'change:' terms instead test the balance or change of the+accounts those postings are in.++* Menu:++* How assert rules work::+* Tips for writing assert rules::+++File: hledger.info, Node: How assert rules work, Next: Tips for writing assert rules, Up: assert directive++13.20.1 How assert rules work+-----------------------------++Assert rules are checked whenever the journal is read: by every command,+and by hledger-ui and hledger-web when they reload (unless disabled with+'-I'/'--ignore-assertions', eg while you work on a failing rule). This+happens after the journal is fully processed (after auto postings,+transaction balancing, balance assertions and lot calculation), so rules+see generated postings and lot subaccounts, and forecast transactions+when '--forecast' is used. Rules are checked in the order they were+read, and the first rule that fails stops reading, with an error.++ Their scope is the file tree: an assert rule sees all entries in the+main file and its included files, before and after it, but not entries+read by other '-f' options. To check some extra rules without adding+them to the journal, give them to the check command as quoted arguments:+eg 'hledger check 'assert none daily type:A balance:<0''.++ Each rule is checked as if by a balance report, 'hledger bal -E+QUERY', in four steps:++ 1. *Select postings.* The query's ordinary terms select and prepare+ postings as 'balance' would: costs are ignored (amounts are summed+ in their original commodities), and 'depth:' clips account names,+ merging subaccounts into their parent. 'date:' terms don't select+ postings; they limit the report period, like '-b'/'-e'.+ 2. *Calculate report rows.* The selected postings are summed by+ account. Each row has the account's change during the period, and+ its balance at the end of the period (including all earlier+ postings, like 'bal -H'). The rows are the accounts with selected+ postings in the period, plus, when the query has a 'balance:' term,+ accounts with only earlier postings (their change is zero but their+ balance may not be).+ 3. *Filter rows.* 'change:' terms test each row's change, and+ 'balance:' terms test its end balance; a query can have both.+ Without these terms every row matches, so the rule is simply about+ whether any postings were selected.+ 4. *Test.* 'none' passes if no row matches, and 'some' passes if at+ least one does.++ These steps are done at one or more checkpoints, in date order:++ * With no period expression, there is one checkpoint, covering the+ whole journal (or the 'date:' terms' span). So 'balance:' tests+ the balances at the end of the journal, and 'change:' tests the+ total change.+ * With a period expression, each of its periods is a checkpoint, and+ the rule must pass at every one. The periods are those 'bal' would+ show with that report interval and '-b START -e END'. Eg 'daily'+ checks each day's end balances or changes; 'monthly from 2024'+ checks each month from 2024 on.+ * A period with no rows passes a 'none' rule and fails a 'some' rule.+ * Relative dates in the period expression and query are resolved from+ today's date, so a rule like 'assert some assets:checking date:'-7+ days..'' can start failing just because time passes.+ * Daily is the smallest checking interval ('assert' does not check+ after every transaction).++ So you can check "no asset account is ever negative (at end of day)"+with 'assert none daily type:A balance:<0'. Without 'daily', only the+final balances would be checked.++ When a rule fails, the error shows the rule, every period in which it+failed, and up to 10 of the rows (or postings) which matched in those+periods. Only the first failing rule is reported; others may be failing+too.++ These assertions have a cost: each rule makes reading the journal+slightly slower. Rules matching few postings cost less, and 'balance:'+rules checked daily across many accounts cost more.+++File: hledger.info, Node: Tips for writing assert rules, Prev: How assert rules work, Up: assert directive++13.20.2 Tips for writing assert rules+-------------------------------------++ * *'none' gives more useful errors.* When you have a choice, prefer+ 'none', because when it fails it shows the offending rows, whereas+ a failing 'some' rule can only say nothing matched.+ * *For more precise amount tests, add a sign and/or commodity.* A+ plain number, as in 'balance:>100', ignores sign, and matches if+ any commodity's amount does. Often that is enough, but if you want+ to handle contrabalances or sign typos, add a sign:+ 'balance:>+100'. And to limit the test to one commodity, add its+ symbol, as in 'balance:<-$5000', or add a 'cur:' term.+ * *Subaccounts are not included by default.* Each row's amount is+ the account's own exclusive change or balance (like '=' in a+ balance assertion). To include subaccount balances, limit the+ depth: eg 'expenses:dining depth:2' folds 'expenses:dining''s+ subaccounts into it. (To fold just some accounts, use+ 'depth:REGEX=N'.)+ * *'depth:0' folds all matched accounts into one row.* This lets you+ test two accounts of opposite sign against each other. Eg "savings+ always cover the credit card debt" is 'assert none daily+ acct:'^(assets:savings|liabilities:card)' depth:0 balance:<0'.+ * *'date:' terms combine with the period expression's span.* Eg+ 'assert none monthly assets date:2026- balance:<0' means the same+ as 'assert none monthly from 2026 assets balance:<0'. 'to+ thismonth' is useful for "every past month" rules, excluding the+ current incomplete month.+ * *Avoid 'not:date:' in rules with a 'balance:' term.* It does not+ skip that date's check, it removes that date's postings from all+ later balances. Use 'skip' lines instead.+ * *Account names are matched after account aliases have been+ applied*, as in reports.+++File: hledger.info, Node: comment directive, Next: commodity directive, Prev: assert directive, Up: Journal++13.21 'comment' directive+=========================++A line containing just 'comment' causes all following lines to be+ignored, until an end comment directive or file end.++* Menu:++* end comment directive::+++File: hledger.info, Node: end comment directive, Up: comment directive++13.21.1 'end comment' directive+-------------------------------++A line containing just 'end comment' ends the effect of a preceding+comment directive.+++File: hledger.info, Node: commodity directive, Next: decimal-mark directive, Prev: comment directive, Up: Journal++13.22 'commodity' directive+===========================++'commodity' directives declare commodity symbols (for error checking)+and their preferred display style (digit group marks, decimal digits,+and symbol position). Eg:++commodity $1,000.00+commodity 1000,00 EUR+commodity ₹ 1,00,00,000.00+commodity 1000. ; the no-symbol commodity++ The sample amount must include a decimal mark (even if there are no+decimal digits after it). This tells the parser which decimal mark+(period or comma) is used for this commodity in the journal file, which+can be useful in case of ambiguous digit group marks. This affects+subsequent entries in the current file, its included files, and the rest+of any parent files (see directive scopes), and it can be overridden by+a 'decimal-mark' directive.++* Menu:++* Commodity directive syntax::+* Commodity tags::+* Commodity aliases::+* Commodity error checking::+++File: hledger.info, Node: Commodity directive syntax, Next: Commodity tags, Up: commodity directive++13.22.1 Commodity directive syntax+----------------------------------++In more detail. A commodity directive is normally the word 'commodity'+followed by a sample amount (only its format is significant), and+optionally a comment. Eg:++commodity $1000.00+commodity 1.000,00 EUR+commodity 1 000 000.0000 ; the no-symbol commodity++ A commodity directive's sample amount must always include a decimal+mark (period or comma). If you don't want to show any decimal digits,+write the decimal mark at the end:++commodity 1000. AAAA ; show AAAA with no decimals++ Commodity symbols containing spaces, numbers, or punctuation must be+enclosed in double quotes, as usual:++commodity 1.0000 "AAAA 2023"++ Commodity directives normally include a sample amount, but can+declare only a symbol (ie, just function 1 above):++commodity $+commodity INR+commodity "AAAA 2023"+commodity "" ; the no-symbol commodity++ Commodity directives may also be written with an indented 'format'+subdirective, as in Ledger. The symbol is repeated and must be the same+in both places. Other subdirectives are ignored:++; display indian rupees with currency name on the left,+; thousands, lakhs and crores comma-separated,+; period as decimal point, and two decimal places.+commodity INR+ format INR 1,00,00,000.00+ other subdirective ; ignored++ A commodity can be declared more than once, eg in a main file and an+included file, or in several files read with '-f'. The later+declaration will override or add to the earlier one, as follows: its+display style (if it has one) replaces the earlier style, its tags take+precedence over the earlier tags, and its aliases are added to the+earlier aliases. ("Later" means later in the order hledger reads them:+through each file and its included files, then the next '-f' file.)+'--debug=1' shows any commodities which files read with '-f' declare+with different display styles.+++File: hledger.info, Node: Commodity tags, Next: Commodity aliases, Prev: Commodity directive syntax, Up: commodity directive++13.22.2 Commodity tags+----------------------++A commodity directive's comment may contain tags. These will be+inherited by all postings using that commodity in their main amount,+except where the posting already has a value for that tag. (A posting+tag or an account tag overrides a commodity tag.) Note, these tags will+be queryable but won't be shown in 'print' output, even with+-verbose-tags.+++File: hledger.info, Node: Commodity aliases, Next: Commodity error checking, Prev: Commodity tags, Up: commodity directive++13.22.3 Commodity aliases+-------------------------++An 'alias:' tag on a commodity directive declares another symbol/name+for that commodity. You can add several (quoting any that contain+spaces or other special characters, as usual):++commodity USD 1.00 ; alias: $, alias: US$, alias: "us dollars"++ When hledger reads the journal, amounts written with an alias are+converted to the canonical commodity. So they combine with it in+reports, and a transaction can balance across them. This helps when,+eg, your bank data, manual entries and downloaded market prices use+different symbols for the same currency. Declare the symbol you want+reports to show, and the others as its aliases.++ Some details:++ * 'print' shows amounts as they were written; 'print -x' shows them+ converted to the canonical commodity.+ * 'cur:' queries match the canonical symbol, not the aliases (with+ the above declaration, '$5' would be matched by 'cur:USD', and not+ by 'cur:'\$'').+ * An alias can't have aliases of its own, and the same alias can't be+ declared on two different commodities.++* Menu:++* Commodity units::+* Commodity aliases or market prices?::+* Commodity alias scope::+++File: hledger.info, Node: Commodity units, Next: Commodity aliases or market prices?, Up: Commodity aliases++13.22.3.1 Commodity units+.........................++A commodity alias can also specify a quantity. Amounts written with the+alias are divided by this quantity (and their unit costs and market+prices are multiplied by it). This is useful for expressing+differently-sized units of a commodity. Eg:++commodity 1.00 hrs ; alias: 60 min+commodity $1.00 ; alias: 0.001 K, alias: 0.000001 M++ (Avoid decimal commas here, which would end the tag's value; use '.',+or exponential notation, 'alias: 1E-6 M'.)++ You can report in any of these units, eg with '-X min' or '-X M'+(valuation, described later).++ Note, these units keep the symbol placement they were declared with,+but inherit the canonical commodity's number format and+display/transaction-balancing precisions. If you want them to have a+different display style, eg more decimals to make small quantities+visible, give them a 'commodity' directive too:++commodity $1.00 ; alias: 0.001 K, alias: 0.000001 M+commodity 1.000 K+commodity 1.000000 M++ When the conversion gives a repeating decimal (like 1/60 hour per+minute), it is stored internally at maximum precision (255 decimals, see+Amount arithmetic). To keep costs and balance assertions exact, a unit+cost on such an amount is replaced by the exact total cost ('10 min @+$1' becomes '0.1666... hrs @@ $10'), and balance assertions add up the+alias amounts before converting them (so three '10 min' amounts satisfy+a '= 0.5 hrs' assertion).+++File: hledger.info, Node: Commodity aliases or market prices?, Next: Commodity alias scope, Prev: Commodity units, Up: Commodity aliases++13.22.3.2 Commodity aliases or market prices?+.............................................++Both let you convert between symbols. When should you use one or the+other ?++ Use a commodity alias when the symbols mean the same thing in+different names or units ('$' and 'USD', 'min' and 'hrs'). The+conversion happens always and automatically.++ Use a 'P' directive when they are different things with an exchange+rate, even a fixed one. The conversion happens only when you ask for+it.+++File: hledger.info, Node: Commodity alias scope, Prev: Commodity aliases or market prices?, Up: Commodity aliases++13.22.3.3 Commodity alias scope+...............................++Commodity aliases (with or without a quantity) work in two ways, with+different scopes:++ * When hledger reads the journal, they convert the amounts written+ with them, in their own file tree only (before or after the+ directive). A file read with another '-f' option is a separate+ file tree, so its amounts are not converted. To share aliases+ between journals, put the 'commodity' directives in a file which+ they all 'include' (or which includes them all).+ * With '-X', they also act as fixed exchange rates in all file trees,+ as a last resort when market prices can't do the conversion (see+ Finding market price). Eg '-X USD' can convert '$' amounts in+ another file tree that didn't declare that alias.+++File: hledger.info, Node: Commodity error checking, Prev: Commodity aliases, Up: commodity directive++13.22.4 Commodity error checking+--------------------------------++In strict mode ('-s'/'--strict') (or when you run 'hledger check+commodities'), hledger will report an error if an undeclared commodity+symbol is used (aliases count as declared). There's one exception: zero+amounts are always allowed to have no commodity symbol.+++File: hledger.info, Node: decimal-mark directive, Next: include directive, Prev: commodity directive, Up: Journal++13.23 'decimal-mark' directive+==============================++You can use a 'decimal-mark' directive to declare unambiguously which+character (period or comma) represents a decimal mark, for all+subsequent amounts in the current file and its included files (see+directive scopes). This helps when parsing ambiguous numbers (like+'1.000' or '1,000' where you mean one thousand, not one). It also makes+hledger check that numbers use that decimal mark and no other, which+catches some typos and misparsed numbers. With 'decimal-mark ,', a+number like '1,000.00' is reported as an error; and with 'decimal-mark+.', a number like '1.2.34' is reported as an error, instead of being+read as '1234'.++ Eg, at the top of each journal file:++decimal-mark .++ or++decimal-mark ,++ This directive only affects parsing, and it takes precedence over+'commodity' directives. So you can declare preferred decimal marks for+display, which may be different from the decimal mark(s) used in the+data files. (The amounts in 'commodity' and 'D' directives are allowed+to use a different decimal mark.)++ Without a 'decimal-mark' directive, a 'commodity' directive's decimal+mark is used to interpret that commodity's ambiguous numbers, but it is+not enforced: numbers like '1.2.34' or '1.000,00' (when the format is+'1,000.00') are accepted. So if you want these checks, use+'decimal-mark'.+++File: hledger.info, Node: include directive, Next: P directive, Prev: decimal-mark directive, Up: Journal++13.24 'include' directive+=========================++You can pull in the content of additional files by writing an include+directive, like this:++include SOMEFILE++ This has the same effect as if SOMEFILE's content was inlined at this+point. (With any include directives in SOMEFILE processed similarly,+recursively.)++ Only journal files can include other files. They can include+journal, timeclock, timedot, CSV/SSV/TSV, or CSV rules files.++ When a CSV file is included, its rules file is 'FILE.rules' alongside+it, as usual; the '--rules' option is not used here. To use a different+rules file, or a data file located elsewhere (eg in your downloads+directory), include a rules file which has a source rule instead.+Transactions generated from included CSV data are treated like inlined+journal entries: they are placed at this point, any account aliases in+effect are applied to them, and their balance assertions are checked+along with the rest of the journal (unlike when reading a CSV file+directly, where balance assertions are ignored). Other directives which+affect journal parsing (like 'Y', 'D', 'decimal-mark', 'apply account')+do not affect CSV data. Note that if you include a CSV file in your+main journal, you should not also import it, or its transactions would+be duplicated.++ If the file path begins with a tilde, that means your home directory:+'include ~/main.journal'.++ If it begins with a slash, it is an absolute path: 'include+/home/user/main.journal'. Otherwise it is relative to the including+file's folder: 'include ../finances/main.journal'.++ Also, the path may have a file type prefix to force a specific file+format, overriding the file extension(s) (as described in Data formats):+'include timedot:notes/2023.md'.++ The path may contain glob patterns to match multiple files.+hledger's globs are similar to zsh's: '?' to match any character;+'[a-z]' to match any character in a range; '*' to match zero or more+characters that aren't a path separator (like '/'); '**' to match zero+or more subdirectories and/or zero or more characters at the start of a+file name; etc. For convenience, 'include' always excludes the current+file. So, you can do++ * 'include *.journal' to include all other journal files in the+ current directory (excluding dot files)+ * 'include **.journal' to include all other journal files in this+ directory and below (excluding dot files and top-level dot+ directories)+ * 'include timelogs/2???.timedot' to include all timedot files named+ like a year number.++ Note '*' and '**' usually won't match dot files or dot directories,+with one exception: '**' does search non-top-level dot directories. If+this causes problems, make your glob pattern more specific (eg+'**.journal' instead of '**').++ To see all the files being read, and which file includes each one,+run 'hledger files --tree'.++ If you are using many, or deeply nested, include files, and have an+error that's hard to pinpoint: a good troubleshooting command is+'hledger files --debug=6' (or 7).+++File: hledger.info, Node: P directive, Next: payee directive, Prev: include directive, Up: Journal++13.25 'P' directive+===================++The 'P' directive declares a market price, which is a conversion rate+between two commodities on a certain date. This allows value reports to+convert amounts of one commodity to their value in another, on or after+that date. These prices are often obtained from a stock exchange,+cryptocurrency exchange, or the foreign exchange market.++ The format is:++P DATE COMMODITY1SYMBOL COMMODITY2AMOUNT++ DATE is a simple date, COMMODITY1SYMBOL is the symbol of the+commodity being priced, and COMMODITY2AMOUNT is the amount (symbol and+quantity) of commodity 2 that one unit of commodity 1 is worth on this+date. Examples:++# one euro was worth $1.35 from 2009-01-01 onward:+P 2009-01-01 € $1.35++# and $1.40 from 2010-01-01 onward:+P 2010-01-01 € $1.40++ The '-V', '-X' and '--value' flags use these market prices to show+amount values in another commodity. See Value reporting.+++File: hledger.info, Node: payee directive, Next: tag directive, Prev: P directive, Up: Journal++13.26 'payee' directive+=======================++ payee PAYEE NAME++ This directive can be used to declare a limited set of payees which+may appear in transaction descriptions. The "payees" check will report+an error if any transaction refers to a payee that has not been+declared. (This is quite a strict check, and not often used.)++ Eg:++payee Whole Foods ; a comment++ To declare the empty payee name, use '""'.++payee ""++ Payees do not support tags. Any indented subdirectives are ignored.+++File: hledger.info, Node: tag directive, Next: Periodic transactions, Prev: payee directive, Up: Journal++13.27 'tag' directive+=====================++ tag TAGNAME++ This directive can be used to declare a limited set of tag names+allowed in tags. TAGNAME should be a valid tag name (no spaces). Eg:++tag item-id++ Any indented subdirectives are ignored.++ The "tags" check will report an error if any undeclared tag name is+used. It is quite easy to accidentally create a tag through normal use+of colons in comments; if you want to prevent this, you can declare and+check your tags.+++File: hledger.info, Node: Periodic transactions, Next: Auto postings, Prev: tag directive, Up: Journal++13.28 Periodic transactions+===========================++The '~' directive declares a "periodic rule" which generates temporary+extra transactions, usually recurring at some interval, when hledger is+run with the '--forecast' flag. These "forecast transactions" are+useful for forecasting future activity. They exist only at report time,+when '--forecast' is used; they are not saved in the journal file.++ Periodic rules also have a second use: with the '--budget' flag they+set budget goals for budgeting.++ Periodic rules can be a little tricky, so before you use them, read+this whole section, or at least the following tips:++ 1. Two spaces accidentally added or omitted in the rule will cause you+ trouble - see below.+ 2. For troubleshooting, show the generated transactions with 'hledger+ print --forecast tag:generated' or 'hledger register --forecast+ tag:generated'.+ 3. Forecasted transactions will begin only after the last+ non-forecasted transaction's date.+ 4. Forecasted transactions will end 6 months from today, by default.+ See below for the exact start/end rules.+ 5. Period expressions with report intervals can be tricky; note how+ they make start/end date adjustments.++* Menu:++* Periodic rule syntax::+* Periodic rules and relative dates::+* Two spaces between period expression and description!::+++File: hledger.info, Node: Periodic rule syntax, Next: Periodic rules and relative dates, Up: Periodic transactions++13.28.1 Periodic rule syntax+----------------------------++A periodic transaction rule looks like a normal journal entry, with the+date replaced by a tilde ('~') followed by a period expression+(mnemonic: '~' looks like a recurring sine wave.):++# every first of month+~ monthly+ expenses:rent $2000+ assets:bank:checking++# every 15th of month in 2023's second quarter:+~ monthly from 2023-04-15 to 2023-06-16+ expenses:utilities $400+ assets:bank:checking++ The period expression is the same syntax used for specifying+multi-period reports, just interpreted differently; there, it specifies+report periods; here it specifies recurrence dates (the periods' start+dates).+++File: hledger.info, Node: Periodic rules and relative dates, Next: Two spaces between period expression and description!, Prev: Periodic rule syntax, Up: Periodic transactions++13.28.2 Periodic rules and relative dates+-----------------------------------------++Partial or relative dates (like '12/31', '25', 'tomorrow', 'last week',+'next quarter') are usually not recommended in periodic rules, since the+results will change as time passes. If used, they will be interpreted+relative to, in order of preference:++ 1. the first day of the default year specified by a recent 'Y'+ directive+ 2. or the date specified with '--today'+ 3. or the date on which you are running the report.++ They will not be affected at all by report period or forecast period+dates.+++File: hledger.info, Node: Two spaces between period expression and description!, Prev: Periodic rules and relative dates, Up: Periodic transactions++13.28.3 Two spaces between period expression and description!+-------------------------------------------------------------++If the period expression is followed by a transaction description, these+must be separated by *two or more spaces*. This helps hledger know+where the period expression ends, so that descriptions can not+accidentally alter their meaning, as in this example:++; 2 or more spaces needed here, so the period is not understood as "every 2 months in 2023"+; ||+; vv+~ every 2 months in 2023, we will review+ assets:bank:checking $1500+ income:acme inc++ So,++ * Do write two spaces between your period expression and your+ transaction description, if any.+ * Don't accidentally write two spaces in the middle of your period+ expression.+++File: hledger.info, Node: Auto postings, Next: Other syntax, Prev: Periodic transactions, Up: Journal++13.29 Auto postings+===================++The '=' directive declares an "auto posting rule", which adds extra+postings to existing transactions. (Remember, postings are the account+name & amount lines below a transaction's date & description.)++ In the journal, an auto posting rule looks quite like a transaction,+but instead of date and description it has '=' (mnemonic: "match") and a+query, like this:++= QUERY+ ACCOUNT AMOUNT+ ...++ Queries are just like command line queries; an account name substring+is most common. Query terms containing spaces should be enclosed in+single or double quotes.++ Each '=' rule works like this: when hledger is run with the '--auto'+flag, wherever the QUERY matches a posting in the journal, the rule's+postings are added to that transaction, immediately below the matched+posting. Note these generated postings are temporary, existing only for+the duration of the report, and only when '--auto' is used; they are not+saved in the journal file by hledger.++ The postings can contain the special string '%account' which will be+expanded to the account name of the matched account.++ Generated postings' amounts can depend on the matched posting's+amount. So auto postings can be useful for, eg, adding tax postings+with a standard percentage. AMOUNT can be:++ * a number with no commodity symbol, like '2'. The matched posting's+ commodity symbol will be added to this.++ * a normal amount with a commodity symbol, like '$2'. This will be+ used as-is.++ * an asterisk followed by a number, like '*2'. This will multiply+ the matched posting's amount (and total price, if any) by the+ number.++ * an asterisk followed by an amount with commodity symbol, like+ '*$2'. This multiplies and also replaces the commodity symbol with+ this new one.++ Some examples:++; every time I buy food, schedule a dollar donation+= expenses:food+ (liabilities:charity) $-1++; when I buy a gift, also deduct that amount from a budget envelope subaccount+= expenses:gifts+ assets:checking:gifts *-1+ assets:checking *1++2017/12/1+ expenses:food $10+ assets:checking++2017/12/14+ expenses:gifts $20+ assets:checking++$ hledger print --auto+2017-12-01+ expenses:food $10+ assets:checking+ (liabilities:charity) $-1++2017-12-14+ expenses:gifts $20+ assets:checking+ assets:checking:gifts -$20+ assets:checking $20++ Note that depending fully on generated data such as this has some+drawbacks - it's less portable, less future-proof, less auditable by+others, and less robust (eg your balance assertions will depend on+whether you use or don't use '--auto'). An alternative is to use auto+postings in "one time" fashion - use them to help build a complex+journal entry, view it with 'hledger print --auto', and then copy that+output into the journal file to make it permanent.++* Menu:++* Auto postings and multiple files::+* Auto postings and dates::+* Auto postings and transaction balancing / inferred amounts / balance assertions::+* Auto posting tags::+* Auto postings on forecast transactions only::+++File: hledger.info, Node: Auto postings and multiple files, Next: Auto postings and dates, Up: Auto postings++13.29.1 Auto postings and multiple files+----------------------------------------++An auto posting rule can affect any transaction in the current file, or+in any parent file or child file. Note, currently it will not affect+sibling files (when multiple '-f'/'--file' are used - see #1212).+++File: hledger.info, Node: Auto postings and dates, Next: Auto postings and transaction balancing / inferred amounts / balance assertions, Prev: Auto postings and multiple files, Up: Auto postings++13.29.2 Auto postings and dates+-------------------------------++A posting date (or secondary date) in the matched posting, or (taking+precedence) a posting date in the auto posting rule itself, will also be+used in the generated posting.+++File: hledger.info, Node: Auto postings and transaction balancing / inferred amounts / balance assertions, Next: Auto posting tags, Prev: Auto postings and dates, Up: Auto postings++13.29.3 Auto postings and transaction balancing / inferred amounts /+--------------------------------------------------------------------++balance assertions Currently, auto postings are added:++ * after missing amounts are inferred, and transactions are checked+ for balancedness,+ * but before balance assertions are checked.++ Note this means that journal entries must be balanced both before and+after auto postings are added.++ This also means that you cannot have more than one auto-posting with+a missing amount applied to a given transaction, as it will be unable to+infer amounts.+++File: hledger.info, Node: Auto posting tags, Next: Auto postings on forecast transactions only, Prev: Auto postings and transaction balancing / inferred amounts / balance assertions, Up: Auto postings++13.29.4 Auto posting tags+-------------------------++Automated postings will have some extra tags:++ * 'generated-posting:= QUERY' - shows this was generated by an auto+ posting rule, and the query+ * '_generated-posting:= QUERY' - a hidden tag, which does not appear+ in hledger's output. This can be used to match postings generated+ "just now", rather than generated in the past and saved to the+ journal.++ Also, any transaction that has been changed by auto posting rules+will have these tags added:++ * 'modified:' - this transaction was modified+ * '_modified:' - a hidden tag not appearing in the comment; this+ transaction was modified "just now".+++File: hledger.info, Node: Auto postings on forecast transactions only, Prev: Auto posting tags, Up: Auto postings++13.29.5 Auto postings on forecast transactions only+---------------------------------------------------++Tip: you can can make auto postings that will apply to forecast+transactions but not recorded transactions, by adding+'tag:_generated-transaction' to their QUERY. This can be useful when+generating new journal entries to be saved in the journal.+++File: hledger.info, Node: Other syntax, Prev: Auto postings, Up: Journal++13.30 Other syntax+==================++hledger journal format supports quite a few other features, mainly to+make interoperating with or converting from Ledger easier. Note some of+the features below are powerful and can be useful in special cases, but+in general, features in this section are considered less important or+even not recommended for most users. Downsides are mentioned to help+you decide if you want to use them.++* Menu:++* Amount expressions::+* Balance assignments::+* Bracketed posting dates::+* D directive::+* apply account directive::+* Y directive::+* apply year directive::+* Secondary dates::+* Star comments::+* Valuation expressions::+* Virtual postings::+* Other Ledger directives::+* Ledger virtual costs::+* Ledger cost basis::+++File: hledger.info, Node: Amount expressions, Next: Balance assignments, Up: Other syntax++13.30.1 Amount expressions+--------------------------++AKA "inline math". _Since 1.99.6_++ A posting amount can also be a simple arithmetic expression, which+hledger calculates when reading the journal. This saves doing sums by+hand, and records how an amount was arrived at:++2026-03-02 groceries, two receipts+ assets:checking+ expenses:food $50.20 + $16.54 ; $66.74++2026-03-05 laptop, plus 5% sales tax+ liabilities:card+ expenses:equipment $800.00+ expenses:tax $800.00 * 0.05 ; $40.00++2026-03-07 hardware store, 3 boxes of screws less a $2 coupon+ liabilities:card+ expenses:supplies 3 * $4.99 - $2 ; $12.97++ Downsides: Complicates standard bookkeeping notation; could obscure a+posting's true amount. Makes it harder for other apps to read your+journal.++* Menu:++* Amount expression syntax::+* Amount expression rounding::+* Amount expressions are not kept::+++File: hledger.info, Node: Amount expression syntax, Next: Amount expression rounding, Up: Amount expressions++13.30.1.1 Amount expression syntax+..................................++ * You can use '+', '-', '*', '/' and parentheses. '*' and '/' are+ done before '+' and '-'; otherwise it's left to right. A minus+ sign can also go before parentheses, eg '-($1 + $2)'.+ * Spaces around the operators are optional, except that a '/' right+ after a commodity symbol needs a space before it: '10 EUR / 4'+ works, '10 EUR/4' is an error.+ * '+' and '-' need amounts in the same commodity. You can write the+ commodity just once, since a plain number takes the other side's+ commodity: '$10 + 5' is $15.+ * '*' and '/' need a plain number on at least one side, eg '$800.00 *+ 0.05', '3 * $4.99' or '$100.00 / 3'. The result is in the other+ side's commodity. So a plain number divided by an amount is in+ that amount's commodity, as in Ledger; this is handy for inverting+ an exchange rate: '1 / 1.25 EUR' is 0.80 EUR.+ * A cost, lot annotation or balance assertion can follow an+ expression, and applies to its result: '10 EUR + 5 EUR @ $1.10' is+ 15 EUR, costing $1.10 each.+ * A cost can be an expression too, eg '1 GBP @ (1 / 1.14 EUR)' or '3+ AAPL @@ $450 + $5'.+ * Expressions can be used only in posting amounts (in journal format,+ or in CSV rules) and transacted costs, not in cost basis+ annotations, balance assertions, directives, or auto posting rule+ multipliers ('*AMT').+++File: hledger.info, Node: Amount expression rounding, Next: Amount expressions are not kept, Prev: Amount expression syntax, Up: Amount expressions++13.30.1.2 Amount expression rounding+....................................++The result of '+' or '-' is exact, and shows as many decimal places as+the more precise of the two amounts.++ The result of '*' or '/' is rounded, using banker's rounding, to the+entry's decimal places for that commodity: the most decimal places+written in that commodity's amounts in the entry, including amounts+inside expressions or balance assignments, but not cost amounts, or the+plain numbers used with '*' or '/'. These are the same decimal places+hledger uses to check that the entry balances (see Transaction+balancing). So:++ * '$100/3' is $33.33 in an entry that also has '$-100.00', but $33+ when all of the entry's dollar amounts are whole numbers.+ * '$10 * 0.15' on its own is $2; write '$10.00 * 0.15' to get $1.50.+ * For more decimal places, write more: '$100.0000 / 3' is $33.3333.+ * In periodic transaction rules and auto posting rules, a result is+ rounded to its own decimal places, eg '$100/3' is $33 and+ '$100.00/3' is $33.33.+ * A result with no commodity gets the default commodity from a 'D'+ directive, if any, as usual. It is then like any other plain+ number after a 'D' directive, whose decimal places count: after 'D+ $1,000.00', '5 / 2' is $2.50.++ A cost calculated with '*' or '/' is not rounded, since a rounded+rate could be far off ('$10 / 1.14' would be $9). hledger keeps it+exact, and shows it with all its decimal places, or 8 if it's a+repeating decimal (more if written), eg '1 GBP @ $10 / 1.14' prints as+'1 GBP @ $8.77192982'.++ The rounded amount is what hledger stores (see also Where hledger+divides). So a split that doesn't divide evenly leaves the entry+unbalanced, and the error message says that such amounts are rounded.+To fix it, leave one amount blank, and hledger will give it the+remainder:++2026-03-09 dinner with Ana and Raj, split three ways+ liabilities:card $-107.00+ assets:receivable:ana ($92.00 + $15.00) / 3 ; $35.67+ assets:receivable:raj ($92.00 + $15.00) / 3 ; $35.67+ expenses:food ; $35.66+++File: hledger.info, Node: Amount expressions are not kept, Prev: Amount expression rounding, Up: Amount expressions++13.30.1.3 Amount expressions are not kept+.........................................++hledger keeps only an expression's result. 'print' (including+'--export', and all its output formats), other reports and error+messages show the result, eg '$66.74', not '$50.20 + $16.54'. If you+need to keep the parts visible, write them in a comment too.+++File: hledger.info, Node: Balance assignments, Next: Bracketed posting dates, Prev: Amount expressions, Up: Other syntax++13.30.2 Balance assignments+---------------------------++Ledger-style balance assignments are also supported. These are like+balance assertions, but with no posting amount on the left side of the+equals sign; instead it is calculated automatically so as to satisfy the+assertion. This can be a convenience during data entry, eg when setting+opening balances:++; starting a new journal, set asset account balances+2016/1/1 opening balances+ assets:checking = $409.32+ assets:savings = $735.24+ assets:cash = $42+ equity:opening balances++ or when adjusting a balance to reality:++; no cash left; update balance, record any untracked spending as a generic expense+2016/1/15+ assets:cash = $0+ expenses:misc++ The calculated amount depends on the account's balance in the+commodity at that point (which depends on the previously-dated postings+of the commodity to that account since the last balance assertion or+assignment).++ Downsides: using balance assignments makes your journal less+explicit; to know the exact amount posted, you have to run hledger or do+the calculations yourself, instead of just reading it. Also balance+assignments' forcing of balances can hide errors. These things make+your financial data less portable, less future-proof, and less+trustworthy in an audit.++* Menu:++* Balance assignments and costs::+* Balance assignments and subaccounts::+* Balance assignments and multiple files::+++File: hledger.info, Node: Balance assignments and costs, Next: Balance assignments and subaccounts, Up: Balance assignments++13.30.2.1 Balance assignments and costs+.......................................++A cost in a balance assignment will cause the calculated amount to have+that cost attached:++2019/1/1+ (a) = $1 @ €2++$ hledger print --explicit+2019-01-01+ (a) $1 @ €2 = $1 @ €2+++File: hledger.info, Node: Balance assignments and subaccounts, Next: Balance assignments and multiple files, Prev: Balance assignments and costs, Up: Balance assignments++13.30.2.2 Balance assignments and subaccounts+.............................................++Subaccount-inclusive balance assignments ('=*' or '==*') are also+supported. The calculated amount is posted to the account named, making+its balance including subaccounts equal the assigned balance; the+subaccounts' balances are not changed. '=*' sets the balance in just+the assigned commodity, while '==*' also clears any other commodities.++2026-01-01+ liabilities:card $-30+ liabilities:loan $-200+ expenses++2026-01-15 a windfall pays off all liabilities+ liabilities ==* $0+ income:windfall++$ hledger print --explicit date:2026-01-15+2026-01-15 a windfall pays off all liabilities+ liabilities $230 ==* $0+ income:windfall $-230++$ hledger bal liabilities+ $230 liabilities+ $-30 liabilities:card+ $-200 liabilities:loan+--------------------+ 0 +++File: hledger.info, Node: Balance assignments and multiple files, Prev: Balance assignments and subaccounts, Up: Balance assignments++13.30.2.3 Balance assignments and multiple files+................................................++Balance assignments handle multiple files like balance assertions. They+see balance from other files previously included from the current file,+but not from previous sibling or parent files.+++File: hledger.info, Node: Bracketed posting dates, Next: D directive, Prev: Balance assignments, Up: Other syntax++13.30.3 Bracketed posting dates+-------------------------------++For setting posting dates and secondary posting dates, Ledger's+bracketed date syntax is also supported: '[DATE]', '[DATE=DATE2]' or+'[=DATE2]' in posting comments. hledger will attempt to parse any+square-bracketed sequence of the '0123456789/-.=' characters in this+way. With this syntax, DATE infers its year from the transaction and+DATE2 infers its year from DATE.++ Downsides: another syntax to learn, redundant with hledger's+'date:'/'date2:' tags, and confusingly similar to Ledger's lot date+syntax.+++File: hledger.info, Node: D directive, Next: apply account directive, Prev: Bracketed posting dates, Up: Other syntax++13.30.4 'D' directive+---------------------++ D AMOUNT++ This directive sets a default commodity, to be used for any+subsequent commodityless amounts (ie, plain numbers) seen while parsing+the journal. This affects subsequent entries until the next 'D'+directive, or the end of the current file (including its included files;+see directive scopes).++ For compatibility/historical reasons, 'D' also acts like a+'commodity' directive (setting the commodity's decimal mark for parsing+and display style for output). So its argument is not just a commodity+symbol, but a full amount demonstrating the style. The amount must+include a decimal mark (either period or comma). Eg:++; commodity-less amounts should be treated as dollars+; (and displayed with the dollar sign on the left, thousands separators and two decimal places)+D $1,000.00++1/1+ a 5 ; <- commodity-less amount, parsed as $5 and displayed as $5.00+ b++ Interactions with other directives:++ For setting a commodity's display style, a 'commodity' directive has+highest priority, then a 'D' directive.++ For detecting a commodity's decimal mark during parsing,+'decimal-mark' has highest priority, then 'commodity', then 'D'.++ For checking commodity symbols with the check command, a 'commodity'+directive is required ('hledger check commodities' ignores 'D'+directives).++ Downsides: omitting commodity symbols makes your financial data less+explicit, less portable, and less trustworthy in an audit. It is+usually an unsustainable shortcut; sooner or later you will want to+track multiple commodities. D is overloaded with functions redundant+with 'commodity' and 'decimal-mark'. And it works differently from+Ledger's 'D'.+++File: hledger.info, Node: apply account directive, Next: Y directive, Prev: D directive, Up: Other syntax++13.30.5 'apply account' directive+---------------------------------++This directive sets a default parent account, which will be prepended to+all accounts in following entries, until an 'end apply account'+directive or end of current file. Eg:++apply account home++2010/1/1+ food $10+ cash++end apply account++ is equivalent to:++2010/01/01+ home:food $10+ home:cash $-10++ (If the parent account name ends with a colon ('apply account+home:'), it is ignored, as in Ledger.)++ 'account' directives are also affected, and so is any 'include'd+content.++ Account names entered via hledger add or hledger-web are not+affected.++ Account aliases from 'alias' directives are applied before the parent+account is prepended (as in Ledger), so they match the account names as+written. This means a file's aliases keep working when it is included+under 'apply account'. (Before hledger 2, they were applied after.)+'--alias' options are applied after the parent account is prepended, so+they match the full account names.++ Downsides: this can make your financial data less explicit, less+portable, and less trustworthy in an audit.+++File: hledger.info, Node: Y directive, Next: apply year directive, Prev: apply account directive, Up: Other syntax++13.30.6 'Y' directive+---------------------++ Y YEAR++ or (deprecated backward-compatible form):++ year YEAR++ The space is optional. This sets a default year to be used for+subsequent dates which don't specify a year. Eg:++Y2009 ; set default year to 2009++12/15 ; equivalent to 2009/12/15+ expenses 1+ assets++year 2010 ; change default year to 2010++2009/1/30 ; specifies the year, not affected+ expenses 1+ assets++1/31 ; equivalent to 2010/1/31+ expenses 1+ assets++ Downsides: omitting the year (from primary transaction dates, at+least) makes your financial data less explicit, less portable, and less+trustworthy in an audit. Such dates can get separated from their+corresponding Y directive, eg when evaluating a region of the journal in+your editor. A missing Y directive makes reports dependent on today's+date.+++File: hledger.info, Node: apply year directive, Next: Secondary dates, Prev: Y directive, Up: Other syntax++13.30.7 'apply year' directive+------------------------------++'apply year YEAR' sets a default year like 'Y', but only until a+matching 'end apply year' directive (or the end of the current file).+'end apply year' restores the default year that was in effect before the+matching 'apply year'. These blocks can be nested, as in Ledger (which+also lets a bare 'end' or 'end apply' close them; hledger requires 'end+apply year'). Eg:++Y 2009++apply year 2010+1/31 ; 2010-01-31+ expenses 1+ assets+end apply year++2/28 ; 2009-02-28+ expenses 1+ assets++ An 'end apply year' with no matching 'apply year' is an error.+(Before hledger 2, 'apply year' worked like 'Y', and 'end apply year'+was ignored.)+++File: hledger.info, Node: Secondary dates, Next: Star comments, Prev: apply year directive, Up: Other syntax++13.30.8 Secondary dates+-----------------------++A secondary date is written after the primary date, following an equals+sign: 'DATE1=DATE2'. If the year is omitted, the primary date's year is+assumed. When running reports, the primary (left side) date is used by+default, but with the '--date2' flag ('--aux-date' or'--effective' also+work, for Ledger users), the secondary (right side) date will be used+instead.++ The meaning of secondary dates is up to you. Eg it could be "primary+is the bank's clearing date, secondary is the date the transaction was+initiated, if different".++ In practice, this feature usually adds confusion:++ * You have to remember the primary and secondary dates' meaning, and+ follow that consistently.+ * It splits your bookkeeping into two modes, and you have to remember+ which mode is appropriate for a given report.+ * Usually your balance assertions will work with only one of these+ modes.+ * It makes your financial data more complicated, less portable, and+ less clear in an audit.+ * It interacts with every feature, creating an ongoing cost for+ implementors.+ * It distracts new users and supporters.+ * Posting dates are simpler and work better.++ So secondary dates are officially deprecated in hledger, remaining+only as a Ledger compatibility aid; we recommend using posting dates+instead.+++File: hledger.info, Node: Star comments, Next: Valuation expressions, Prev: Secondary dates, Up: Other syntax++13.30.9 Star comments+---------------------++Lines beginning with '*' (star/asterisk) are also comment lines, for+Ledger compatibility. Emacs users can use these as foldable org+headings. (But it's usually better to use ledger-mode, and add outshine+minor mode for org-like folding.)+++File: hledger.info, Node: Valuation expressions, Next: Virtual postings, Prev: Star comments, Up: Other syntax++13.30.10 Valuation expressions+------------------------------++Ledger allows a valuation function or value to be written in double+parentheses after an amount. hledger ignores these.+++File: hledger.info, Node: Virtual postings, Next: Other Ledger directives, Prev: Valuation expressions, Up: Other syntax++13.30.11 Virtual postings+-------------------------++A posting with parentheses around the account name, like '(some:account)+10', is called an _unbalanced virtual posting_. These postings do not+participate in transaction balancing. (And if you write them without an+amount, a zero amount is always inferred.) These can occasionally be+convenient for special circumstances, but they violate double entry+bookkeeping and make your data less portable across applications, so+many people avoid using them at all.++ A posting with brackets around the account name ('[some:account]') is+called a _balanced virtual posting_. The balanced virtual postings in a+transaction must add up to zero, just like ordinary postings, but+separately from them. These are not part of double entry bookkeeping+either, but they are at least balanced. An example:++2022-01-01 buy food with cash, update budget envelope subaccounts, & something else+ assets:cash $-10 ; <- these balance each other+ expenses:food $7 ; <-+ expenses:food $3 ; <-+ [assets:checking:budget:food] $-10 ; <- and these balance each other+ [assets:checking:available] $10 ; <-+ (something:else) $5 ; <- this is not required to balance++ Ordinary postings, whose account names are neither parenthesised nor+bracketed, are called _real postings_. You can exclude virtual postings+from reports with the '-R/--real' flag or a 'real:1' query.+++File: hledger.info, Node: Other Ledger directives, Next: Ledger virtual costs, Prev: Virtual postings, Up: Other syntax++13.30.12 Other Ledger directives+--------------------------------++These other Ledger directives are currently accepted but ignored. This+allows hledger to read more Ledger files, but be aware that hledger's+reports may differ from Ledger's if you use these.++apply fixed COMM AMT+apply tag TAG+bucket / A ACCT+capture ACCT REGEX+check EXPR+define VAR=EXPR+end apply fixed+end apply tag+end tag+eval / expr EXPR+python+ PYTHONCODE+tag NAME+value EXPR+--command-line-flags++ Ledger's 'assert EXPR' directive is not supported: 'assert' is+hledger's assert directive, which has a different syntax, so a+Ledger-style 'assert' line is an error.++ See also https://hledger.org/ledger.html for a detailed+hledger/Ledger syntax comparison.+++File: hledger.info, Node: Ledger virtual costs, Next: Ledger cost basis, Prev: Other Ledger directives, Up: Other syntax++13.30.13 Ledger virtual costs+-----------------------------++In Ledger, '(@) UNITCOST' and '(@@) TOTALCOST' are virtual costs, which+do not generate market prices. In hledger, these are equivalent to '@'+and '@@'.+++File: hledger.info, Node: Ledger cost basis, Prev: Ledger virtual costs, Up: Other syntax++13.30.14 Ledger cost basis+--------------------------++In Ledger, these annotations after an amount help specify or select a+lot's cost basis: '{LOTUNITCOST}' or '{{LOTTOTALCOST}}', '[LOTDATE]',+and/or '(LOTNOTE)'. hledger will read these, as an alternative to its+own cost basis syntax.++ We also read Ledger's fixed price syntax, '{=LOTUNITCOST}' or+'{{=LOTTOTALCOST}}', treating it as equivalent to '{LOTUNITCOST}' or+'{{LOTTOTALCOST}}'.+++File: hledger.info, Node: CSV, Next: Timeclock, Prev: Journal, Up: Top++14 CSV+******++hledger can read transactions from CSV (comma-separated values) files.+More precisely, it can read DSV (delimiter-separated values), from a+file or standard input. Comma-separated, semicolon-separated and+tab-separated are the most common variants, and hledger recognises these+three automatically from the file extension.++ (To learn about producing CSV or TSV _output_, see Output format.)++ Each CSV file must be described by a corresponding _rules file_.+This contains rules describing the CSV data (header line, fields layout,+date format etc.), how to construct hledger transactions from it, and+how to categorise transactions based on description or other attributes.++ By default, hledger expects this rules file to be named like the CSV+file, with an extra '.rules' extension added, in the same directory. Eg+when asked to read 'foo/FILE.csv', hledger looks for+'foo/FILE.csv.rules'. You can specify a different rules file with the+'--rules' option (for CSV files specified on the command line; not for+ones included by a journal file).++ At minimum, the rules file must identify the date and amount fields,+and often it also specifies the date format and how many header lines+there are. Here's a simple CSV file and a rules file for it:++Date, Description, Id, Amount+12/11/2019, Foo, 123, 10.23++# basic.csv.rules+skip 1+fields date, description, , amount+date-format %d/%m/%Y++$ hledger print -f basic.csv+2019-11-12 Foo+ expenses:unknown 10.23+ income:unknown -10.23++ Or you can read the rules file itself, if it has a 'source' rule+saying where the data is (eg 'source ./basic.csv'): 'hledger print -f+basic.csv.rules'. This is the usual setup for regular importing; see+Finding the data.++ There's an introductory Tutorial: Import CSV data on hledger.org, and+more CSV rules examples below, and a larger collection at+https://github.com/hledgerorg/hledger/tree/main/examples/csv.++* Menu:++* CSV rules cheatsheet::+* Finding the data::+* Reading the data::+* CSV fields and hledger fields::+* fields::+* Field assignment::+* hledger fields::+* balance-type::+* if::+* Matchers::+* ifs::+* end::+* merge::+* include::+* Working with CSV::+* How CSV rules are evaluated::+++File: hledger.info, Node: CSV rules cheatsheet, Next: Finding the data, Up: CSV++14.1 CSV rules cheatsheet+=========================++The following kinds of rule can appear in the rules file, in any order.+(Blank lines and lines beginning with '#' or ';' are ignored.)++*'source'* optionally declare which file to read data+ from+*'archive'* optionally enable an archive of imported+ files+*'separator'* declare the field separator, instead of+ relying on file extension+*'encoding'* optionally declare which text encoding the+ data has+*'skip'* skip header line(s) at start of file, or+ (inside an if rule) the current record(s)+*'date-format'* declare how to parse CSV dates/date-times+*'timezone'* declare the time zone of ambiguous CSV+ date-times+*'decimal-mark'* declare the decimal mark used in CSV amounts,+ when ambiguous+*'newest-first'* improve txn order when: there are multiple+ records, newest first, all with the same date+*'intra-day-reversed'* improve txn order when: same-day txns are in+ opposite order to the overall file+*'fields'* name CSV fields for easy reference, and+ optionally assign their values to hledger+ fields+*Field assignment* assign a CSV value or interpolated text value+ to a hledger field+*'balance-type'* select which type of balance+ assertions/assignments to generate+*'if'* conditionally assign values to hledger+ fields, or skip one or more records+*'ifs'* declare multiple if rules in a compact table+ format+*'end'* (inside an if rule) skip the current and all+ remaining records+*'merge'* combine this record with the next one(s), to+ be converted to a single transaction+*'include'* inline another CSV rules file++ Working with CSV tips and How CSV rules are evaluated can be found+below.+++File: hledger.info, Node: Finding the data, Next: Reading the data, Prev: CSV rules cheatsheet, Up: CSV++14.2 Finding the data+=====================++You can name a CSV file on the command line, as in 'hledger -f foo.csv+CMD', and hledger will use the rules file named like it+('foo.csv.rules').++ Or you can name the rules file, as in 'hledger -f foo.csv.rules CMD'.+The rules file must then have a 'source' rule (described below), saying+which data file to read (perhaps in your web browser's download+directory), or which command to run to get the data.++ The second way is more powerful. This and the archive rule below,+and the default behaviour of the get and import commands, help remove+the busywork of managing CSV downloads. Ideally, you can periodically++ 1. Download new CSVs from your banks (perhaps by just running 'hledger+ get').+ 2. Import new transactions from all the CSVs specified by rules files+ in 'rules/', by just running 'hledger import'.++ Or, do both with one command: 'hledger import -g'++ After import, you can discard the CSV immediately, or leave it where+it is for a while, or archive it automatically (to 'data/archive/') with+the archive rule.++ It's also possible to include a CSV file or rules file in your+journal, in which case there's no import step at all; instead, the whole+CSV is reconverted on each run.++* Menu:++* source::+* archive::+* File Extension::+* Reading CSV from standard input::+* Reading multiple CSV files::+++File: hledger.info, Node: source, Next: archive, Up: Finding the data++14.2.1 'source'+---------------++When hledger reads a rules file ('-f foo.csv.rules'), the 'source' rule+says which data file to read (it is ignored if you name the data file+instead, as in '-f foo.csv'):++source ./Checking1.csv++ If the file does not exist, it is just considered empty, without+raising an error.++ A rules file (and any included rules file) can have only one 'source'+rule. To read several data files, use a rules file for each; they can+include their common rules.++ The file path is resolved this way:++ * Absolute paths and '~'-prefixed paths are used as-is.+ * A path beginning with './' or '../' ('source ./Checking1.csv') is+ anchored relative to the rules file's directory (as in hledger 1).+ * Any other relative path ('source bank/Checking1.csv'), or a bare+ file name ('source Checking1.csv'), is searched for first in a+ 'data/' directory next to the main journal file (also used by the+ 'archive' rule and the 'get' command), then in your '~/Downloads'+ folder.++ You can use a glob pattern, to avoid specifying the file name+exactly:++source Checking1*.csv++ A glob pattern has another benefit: if it matches multiple files,+hledger reads just one of them: the newest, so stale copies are ignored;+or when importing with 'archive', the oldest, which is then archived, so+that successive imports process the copies in order.++* Menu:++* Data cleaning / data generating commands::+++File: hledger.info, Node: Data cleaning / data generating commands, Up: source++14.2.1.1 Data cleaning / data generating commands+.................................................++After 'source''s file pattern, you can write '|' (pipe) and a data+cleaning command (or command pipeline) (since hledger 1.50). If+hledger's CSV rules aren't enough, you can pre-process the downloaded+data here with a shell command or script, to make it more suitable for+conversion. The command will be executed by your default shell, in the+directory of the rules file, will receive the data file's content as+standard input, and should output zero or more lines of+character-separated-values, suitable for conversion by the CSV rules.++ Examples:++source ./paypal.json | paypalcsv+source data/simplefin.json | simplefincsv - 'chase.*card'+source OfxDownload*.csv | grep -vE '^(([^,]*,){6}[^,]*|)$' | sort -t, -n +2+source History_for_Account_Z20144832*.csv # | grep -E '^([^,]*,){12}[^,]*$' | sed -E -e 's/^ //' -e 's/\.([0-9]),/.\10,/g' -e 's/,([0-9]+),/,\1.00,/g'++ Or, after 'source' you can write '|' and a data generating command+(with no file pattern before the '|'). This command receives no input,+and should output zero or more lines of character-separated values,+suitable for conversion by the CSV rules.++ Examples:++source | paypaljson | paypalcsv+source | paypalcsv data/paypal.json +source | simplefinjson >data/simplefin.json && simplefincsv data/simplefin.json 'chase.*card'+source | simplefincsv data/simplefin.json 'unify.*checking'++ ('paypal*' and 'simplefin*' scripts are in bin/)++ Whenever hledger runs one of these commands, it will echo the command+on stderr, prefixed by the rules file's name. If the command produces+error output, but exits successfully, hledger will show the error output+as a warning. If a data cleaning command fails, hledger will fail and+show the error output in the error message. If a data generating+command fails, hledger will show the error as a warning and continue,+treating this as if no data was found.++ These commands run in an 'import --dry-run' too, since their output+is needed to preview the data. So they should be safe to run+repeatedly: a data cleaning command should be a pure filter, and a data+generating command should not consume or change anything that the real+import will need. A fetch that isn't safe to repeat belongs in the get+command's 'getdata' script instead (which 'get --dry-run' and 'import+--dry-run -g' don't run), with a file pattern to read its output.+++File: hledger.info, Node: archive, Next: File Extension, Prev: source, Up: Finding the data++14.2.2 'archive'+----------------++With 'archive' added to a rules file, the 'import' command will archive+each successfully processed data file or data command output in an+'archive/' subdirectory of the 'data/' directory next to the main+journal file. The archive file name will be based on the rules file and+the data file's modification date and extension (or for a+data-generating command, the current date and the ".csv" extension).+The original data file, once archived, will be removed.++ Also, in this mode 'import' will prefer the oldest file matched by+the 'source' rule's glob pattern, not the newest. (So if there are+multiple downloads, they will be imported and archived oldest first.)++ Archiving is optional, but it can be useful for troubleshooting your+CSV rules, regenerating entries with improved rules, checking for+variations in your bank's CSV, etc.+++File: hledger.info, Node: File Extension, Next: Reading CSV from standard input, Prev: archive, Up: Finding the data++14.2.3 File Extension+---------------------++To help hledger choose the CSV file reader and show the right error+messages (and choose the right field separator character by default),+it's best if CSV/SSV/TSV files are named with a '.csv', '.ssv' or '.tsv'+filename extension. (More about this at Data formats.)++ When reading files with the "wrong" extension, you can ensure the CSV+reader (and the default field separator) by prefixing the file path with+'csv:', 'ssv:' or 'tsv:': Eg:++$ hledger -f ssv:foo.dat print++ You can also override the default field separator with a separator+rule if needed.+++File: hledger.info, Node: Reading CSV from standard input, Next: Reading multiple CSV files, Prev: File Extension, Up: Finding the data++14.2.4 Reading CSV from standard input+--------------------------------------++You'll need the file format prefix when reading CSV from stdin also,+since hledger assumes journal format by default. Eg:++$ cat foo.dat | hledger -f ssv:- print+++File: hledger.info, Node: Reading multiple CSV files, Prev: Reading CSV from standard input, Up: Finding the data++14.2.5 Reading multiple CSV files+---------------------------------++If you use multiple '-f' options to read multiple CSV files at once,+hledger will look for a correspondingly-named rules file for each CSV+file. But if you specify a rules file with '--rules', that rules file+will be used for all the CSV files.++ Alternatively, a journal file can include CSV files (or rules files).+In this case each CSV file always uses its correspondingly-named rules+file; '--rules' has no effect.+++File: hledger.info, Node: Reading the data, Next: CSV fields and hledger fields, Prev: Finding the data, Up: CSV++14.3 Reading the data+=====================++These tips and rules help hledger read the CSV data correctly: check+that it's valid, choose its separator, decode its text, skip any header+lines, parse its dates and numbers, and put its records in the right+order.++* Menu:++* Valid CSV::+* separator::+* encoding::+* skip::+* date-format::+* timezone::+* decimal-mark::+* newest-first::+* intra-day-reversed::+++File: hledger.info, Node: Valid CSV, Next: separator, Up: Reading the data++14.3.1 Valid CSV+----------------++Note that hledger will only accept valid CSV conforming to RFC 4180, and+equivalent SSV and TSV formats (like RFC 4180 but with semicolon or tab+as separators). This means, eg:++ * Values may be enclosed in double quotes, or not. Enclosing in+ single quotes is not allowed. (Eg ''A','B'' is rejected.)+ * When values are enclosed in double quotes, spaces outside the+ quotes are not allowed. (Eg '"A", "B"' is rejected.)+ * When values are not enclosed in quotes, they may not contain double+ quotes. (Eg 'A"A, B' is rejected.)++ If your CSV/SSV/TSV is not valid in this sense, you'll need to+transform it before reading with hledger. Try using sed, or a more+permissive CSV parser like python's csv lib.+++File: hledger.info, Node: separator, Next: encoding, Prev: Valid CSV, Up: Reading the data++14.3.2 'separator'+------------------++You can use the 'separator' rule to read other kinds of+character-separated data. The argument is any single separator+character, or the words 'tab' or 'space' (case insensitive). Eg, for+comma-separated values (CSV):++separator ,++ or for semicolon-separated values (SSV):++separator ;++ or for tab-separated values (TSV):++separator TAB++ If the input file has a '.csv', '.ssv' or '.tsv' file extension (or a+'csv:', 'ssv:', 'tsv:' prefix), the appropriate separator will be+inferred automatically, and you won't need this rule.+++File: hledger.info, Node: encoding, Next: skip, Prev: separator, Up: Reading the data++14.3.3 'encoding'+-----------------++encoding ENCODING++ hledger normally expects non-ascii text to be using the system+locale's text encoding. If you need to read CSV files which have some+other encoding, you can do it by adding 'encoding ENCODING' to your CSV+rules. Eg: 'encoding iso-8859-1'.++ The supported encodings are: 'ascii', 'utf-8', 'utf-16', 'utf-32',+'iso-8859-1' to 'iso-8859-11' and 'iso-8859-13' to 'iso-8859-16',+'cp1250' to 'cp1258', 'koi8-r', 'koi8-u', 'gb18030', 'macintosh',+'jis-x-0201', 'jis-x-0208', 'iso-2022-jp', 'shift-jis', 'cp437',+'cp737', 'cp775', 'cp850', 'cp852', 'cp855', 'cp857', 'cp860' to+'cp866', 'cp869', 'cp874', and 'cp932'.+++File: hledger.info, Node: skip, Next: date-format, Prev: encoding, Up: Reading the data++14.3.4 'skip'+-------------++skip N++ The word 'skip' followed by a number (or no number, meaning 1) tells+hledger to ignore this many non-empty lines at the start of the input+data. You'll need this whenever your CSV data contains header lines.+Note, empty and blank lines are skipped automatically, so you don't need+to count those.++ 'skip' has a second meaning: it can be used inside an 'if' rule+(described below), to skip one or more records whenever the condition is+true. Records skipped in this way are ignored, except they are still+required to be valid CSV.+++File: hledger.info, Node: date-format, Next: timezone, Prev: skip, Up: Reading the data++14.3.5 'date-format'+--------------------++date-format DATEFMT++ This is a helper for the 'date' (and 'date2') fields. If your CSV+dates are not formatted like 'YYYY-MM-DD', 'YYYY/MM/DD' or 'YYYY.MM.DD',+you'll need to add a date-format rule describing them with a+strptime-style date parsing pattern - see+https://hackage.haskell.org/package/time/docs/Data-Time-Format.html#v:formatTime.+The pattern must parse the CSV date value completely. Some examples:++# MM/DD/YY+date-format %m/%d/%y++# D/M/YYYY+# The - makes leading zeros optional.+date-format %-d/%-m/%Y++# YYYY-Mmm-DD+date-format %Y-%h-%d++# M/D/YYYY HH:MM AM some other junk+# Note the time and junk must be fully parsed, though only the date is used.+date-format %-m/%-d/%Y %l:%M %p some other junk++ Note currently there is no locale awareness for things like '%b', and+setting LC_TIME won't help.+++File: hledger.info, Node: timezone, Next: decimal-mark, Prev: date-format, Up: Reading the data++14.3.6 'timezone'+-----------------++timezone TIMEZONE++ When CSV contains date-times that are implicitly in some time zone+other than yours, but containing no explicit time zone information, you+can use this rule to declare the CSV's native time zone, which helps+prevent off-by-one dates.++ When the CSV date-times do contain time zone information, you don't+need this rule; instead, use '%Z' in 'date-format' (or '%z', '%EZ',+'%Ez'; see the formatTime link above).++ In either of these cases, hledger will do a time-zone-aware+conversion, localising the CSV date-times to your current system time+zone. If you prefer to localise to some other time zone, eg for+reproducibility, you can (on unix at least) set the output timezone with+the TZ environment variable, eg:++$ TZ=-1000 hledger print -f foo.csv # or TZ=-1000 hledger import foo.csv++ 'timezone' currently does not understand timezone names, except+"UTC", "GMT", "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", or "PDT".+For others, use numeric format: +HHMM or -HHMM.+++File: hledger.info, Node: decimal-mark, Next: newest-first, Prev: timezone, Up: Reading the data++14.3.7 'decimal-mark'+---------------------++decimal-mark .++ or:++decimal-mark ,++ hledger automatically accepts either period or comma as a decimal+mark when parsing numbers (cf Amounts). However if any numbers in the+CSV contain digit group marks, such as thousand-separating commas, you+should declare the decimal mark explicitly with this rule, to avoid+misparsed numbers. Like the 'decimal-mark' directive, this also makes+hledger report numbers using a different decimal mark, or repeating the+declared one (like '1.2.34'), as errors. This applies to amounts from+the CSV fields and to amounts written in the rules.+++File: hledger.info, Node: newest-first, Next: intra-day-reversed, Prev: decimal-mark, Up: Reading the data++14.3.8 'newest-first'+---------------------++hledger tries to ensure that the generated transactions will be ordered+chronologically, including same-day transactions. Usually it can+auto-detect how the CSV records are ordered. But if it encounters CSV+where all records are on the same date, it assumes that the records are+oldest first. If in fact the CSV's records are normally newest first,+like:++2022-10-01, txn 3...+2022-10-01, txn 2...+2022-10-01, txn 1...++ you can add the 'newest-first' rule to help hledger generate the+transactions in correct order.++# same-day CSV records are newest first+newest-first+++File: hledger.info, Node: intra-day-reversed, Prev: newest-first, Up: Reading the data++14.3.9 'intra-day-reversed'+---------------------------++If CSV records within a single day are ordered opposite to the overall+record order, you can add the 'intra-day-reversed' rule to improve the+order of journal entries. Eg, here the overall record order is newest+first, but same-day records are oldest first:++2022-10-02, txn 3...+2022-10-02, txn 4...+2022-10-01, txn 1...+2022-10-01, txn 2...++# transactions within each day are reversed with respect to the overall date order+intra-day-reversed+++File: hledger.info, Node: CSV fields and hledger fields, Next: fields, Prev: Reading the data, Up: CSV++14.4 CSV fields and hledger fields+==================================++The main task of CSV rules is to convert *CSV fields* to *hledger+fields*. It's important to know which is which, when you are creating+rules:++ 1. CSV fields+ * are the parts of the records (lines) in your CSV data+ * are referenced by their position or assigned name, with a '%'+ prefix (eg '%1' or '%date')+ * are read-only.++ 2. hledger fields+ * are the parts of a hledger journal entry (see hledger fields)+ (eg 'date', 'description', 'account1', 'amount1')+ * are assigned to by rules, to construct a journal entry+ * can be referenced by their name, without a '%' prefix, inside+ a '%{...}' expression (eg '%{description}'; see Referencing+ other fields).++ CSV rules can't make new fields; you can't define your own variables+in a rules file. (But you could add new CSV fields to the data before+running rules, with a preprocessing script.)++ It's ok for a CSV field and a hledger field to have the same name; in+a 'fields' list, this causes the CSV field's value to be assigned to the+hledger field ("field name punning"). hledger knows which kind of field+is meant from the context: in field values and matchers, '%NAME' is a+CSV field, and a bare 'HLEDGERFIELDNAME' inside '%{...}' is a hledger+field. Some examples:++# set the journal entry's date to the value of CSV field 1+date %1++# name the CSV fields, and use the first as the entry's date+fields date, bankamt++# test the value of the CSV date field+if %date 2026+ ...++# add a tag to the hledger comment field, keeping any comment assigned before+comment %{join(", ", comment, "imported:")}+++File: hledger.info, Node: fields, Next: Field assignment, Prev: CSV fields and hledger fields, Up: CSV++14.5 'fields'+=============++fields FIELDNAME1, FIELDNAME2, ...++ A 'fields' list (the word 'fields' followed by comma-separated field+names) is optional, but convenient. It does two things:++ 1. It names the CSV field in each column. This can be convenient if+ you are referencing them in other rules, so you can say+ '%SomeField' instead of remembering '%13'.++ 2. Whenever you use one of the special hledger field names (described+ below), it assigns the CSV value in this position to that hledger+ field. This is the quickest way to populate hledger's fields and+ build a transaction.++ Here's an example that says "use the 1st, 2nd and 4th fields as the+transaction's date, description and amount; name the last two fields for+later reference; and ignore the others":++fields date, description, , amount, , , somefield, anotherfield++ In 'fields', the names are always separated by commas; this is+unrelated to the CSV file's separator. Also:++ * There must be least two items in the list (at least one comma).+ * Field names may not contain spaces. Spaces before/after field+ names are optional.+ * Field names may contain '_' (underscore) or '-' (hyphen).+ * Fields you don't care about can be given a dummy name or an empty+ name.++ If the CSV contains column headings, it's convenient to use these for+your field names, suitably modified (eg lower-cased with spaces replaced+by underscores).++ Sometimes you may want to alter a CSV field name to avoid assigning+to a hledger field with the same name. Eg you could call the CSV's+"balance" field 'balance_' to avoid directly setting hledger's 'balance'+field (and generating a balance assertion).+++File: hledger.info, Node: Field assignment, Next: hledger fields, Prev: fields, Up: CSV++14.6 Field assignment+=====================++HLEDGERFIELD FIELDVALUE++ Field assignments are the more flexible way to assign CSV values to+hledger fields. They can be used instead of or in addition to a+'fields' list (see above).++ To assign a value to a hledger field, write the field name (any of+the standard hledger field/pseudo-field names, defined below), a space,+followed by a text value on the same line. This text value may+interpolate CSV fields, referenced either by their 1-based position in+the CSV record ('%N') or by the name they were given by 'fields'+('%CSVFIELD'), and regular expression match groups ('\N'), and can+transform them with functions ('%{upper(%CSVFIELD)}') or use other+hledger fields' values ('%{description}'; see Referencing other fields).+You can also write '%(CSVFIELD)' to delimit the field name from adjacent+text (eg '%(field)suffix'). When CSV records have been combined by a+'merge' rule, a '_ROWNUM' suffix (eg '%amt_2', '%4_2') references the+later rows' fields. Interpolation strips outer whitespace (so a CSV+value like '" 1 "' becomes '1' when interpolated) (#1051).++ Some examples:++# set the amount to the 4th CSV field, with " USD" appended+amount %4 USD++# combine three fields to make a comment, containing note: and date: tags+comment note: %somefield - %anotherfield, date: %1++# use parenthesised form when the field name would run into adjacent text+account1 assets:%(type)checking++* Menu:++* Functions::+* Referencing other fields::+++File: hledger.info, Node: Functions, Next: Referencing other fields, Up: Field assignment++14.6.1 Functions+----------------++_Since 1.99.6; experimental_++ To transform a value while interpolating it, write a '%{...}'+expression calling one of the built-in functions below. Eg:++# upper-case the description+description %{upper(%desc)}++# use the category in lower case, or "misc" if it's empty+account2 expenses:%{lower(default(%category, "misc"))}++# remove a reference number from the description+description %{replace(%desc, " *ref#[0-9]+", "")}++# put the date's year and month in a tag+comment month:%{substr(%date, 1, 7)}++# show the last four digits of the card number+comment card:%{substr(%card, -4)}++ Function arguments can be CSV field references ('%summary' or '%3'),+hledger field names ('comment'), match group references ('\1'),+double-quoted text ('"misc"'), numbers, or other function calls. Use+'\"' for a double quote inside double-quoted text. Each expression's+result has outer whitespace removed, like other interpolated values.++function result+--------------------------------------------------------------------------+'upper(TEXT)' TEXT in upper case+'lower(TEXT)' TEXT in lower case+'capitalize(TEXT)' TEXT with each word's first letter in upper case+ and the rest in lower case ('capitalise' also+ works)+'trim(TEXT)' TEXT without outer whitespace+'negate(AMOUNT)' AMOUNT with its sign flipped, eg '5' -> '-5', '-5'+ or '(5)' -> '5'+'abs(AMOUNT)' AMOUNT without a minus sign, eg '-5' or '(5)' ->+ '5'+'concat(TEXT, all the arguments joined together+...)'+'join(SEP, TEXT, the TEXTs that aren't empty, joined with SEP+...)' between them+'default(TEXT, the first argument that's not empty+...)'+'replace(TEXT, TEXT with each match of REGEX replaced by REPL+REGEX, REPL)'+'substr(TEXT, LENGTH characters of TEXT, starting at position+START, LENGTH)' START (1 is the first, -1 the last); LENGTH is+ optional++ For 'replace', REGEX must be double-quoted text, and is a+case-insensitive regular expression. REPL can use '\1', '\2' etc. to+insert REGEX's match groups. (Unquoted '\1' etc. outside double quotes+refer to the match groups of an enclosing 'if' rule instead.) For+'substr', START and LENGTH must be numbers. A negative START counts+from the end, so eg 'substr(%card, -4)' gives the last four characters.+Positions before the start or after the end of TEXT are treated as the+start or end.++ For 'negate' and 'abs', AMOUNT is a number, optionally with a+commodity symbol before or after it, and optionally with a sign: '-' or+'+' before it, or parentheses meaning negative around it. The sign can+be before or after a commodity symbol written in front of the number.+Eg these are all negative amounts: '-5', '(5)', '-$5', '$-5', '$(5)',+'USD -5', '-5 USD', '(5 USD)'. The number itself isn't parsed, so its+decimal mark and digit group marks don't matter. 'negate' converts '5'+to '-5' and '$-1,000.50' to '$1,000.50', and 'abs' converts any of the+above to the unsigned form. A sign after the number ('5-'), or+parentheses around just the number when the symbol comes after it ('(5)+USD'), are not supported.++ 'join' is useful for combining parts which may be empty, without+stray separators. Eg 'comment %{join(", ", %note, %ref)}'.++ Mistakes in an expression, like an unknown function or the wrong+number of arguments, are reported when the rules file is read. Text+beginning with '%{' is always taken as an expression.+++File: hledger.info, Node: Referencing other fields, Prev: Functions, Up: Field assignment++14.6.2 Referencing other fields+-------------------------------++To use a hledger field's value, write its name (without '%') inside a+'%{...}' expression. '%NAME' always means a CSV field, even when a+hledger field has the same name:++# name the third CSV field "amount1"+fields date, description, amount1+# set hledger's amount1 to the CSV amount1 field, followed by USD+amount1 %amount1 USD+# the CSV amount1 field, eg "5"+comment %amount1+# hledger's amount1 field, eg "5 USD"+comment1 %{amount1}++ When there are multiple field assignments to the same hledger field,+only the last one takes effect (though it can include the earlier value,+see below). Here, comment's value will be B, or C if "something" is+matched, but never A:++comment A+comment B+if something+ comment C++ In an assignment to the same field, a hledger field's name gives the+field's value from its previous assignment, so you can add to it. This+is handy for appending to a comment:++fields date, description, comment, amount+if refund+ # add a refund tag+ comment %{comment}, refund:+ # or, avoiding a redundant separator when comment is empty:+ #comment %{join(", ", comment, "refund:")}++ "Previous assignment" here means the one before this one, in this+order: top-level assignments (including those made by 'fields'), then+assignments in matched 'if' rules, each in the order written. (So a+top-level assignment comes before any 'if' rule's, even if written after+it.)++ In an assignment to a different field, a hledger field's name gives+that field's final value, wherever it is assigned. Eg here, comment is+set to the final value of the hledger description:++comment %{description}++ When interpolating a hledger field, the value is the text assigned to+the field by these rules, before further processing by hledger. Eg+'%{amount1}' is the amount text before any sign simplification, and+'%{account2}' is empty if account2 isn't assigned (not+'expenses:unknown').+++File: hledger.info, Node: hledger fields, Next: balance-type, Prev: Field assignment, Up: CSV++14.7 hledger fields+===================++Here are all the hledger fields you can assign to. They correspond to+parts of a journal entry, or in some cases they are pseudo-fields which+have a special effect. You can also interpolate their values in+'%{...}' expressions, except for the '-in'/'-out' amount fields.++* Menu:++* date field::+* date2 field::+* status field::+* code field::+* description field::+* comment field::+* account field::+* amount field::+* currency field::+* balance field::+++File: hledger.info, Node: date field, Next: date2 field, Up: hledger fields++14.7.1 date field+-----------------++Assigning to 'date' sets the transaction date. This is required. If+the CSV dates aren't like 'YYYY-MM-DD', see 'date-format' (and+'timezone').+++File: hledger.info, Node: date2 field, Next: status field, Prev: date field, Up: hledger fields++14.7.2 date2 field+------------------++'date2' sets the transaction's secondary date, if any.+++File: hledger.info, Node: status field, Next: code field, Prev: date2 field, Up: hledger fields++14.7.3 status field+-------------------++'status' sets the transaction's status, if any.+++File: hledger.info, Node: code field, Next: description field, Prev: status field, Up: hledger fields++14.7.4 code field+-----------------++'code' sets the transaction's code, if any.++ Journal format can't represent a right parenthesis in a code (when+reparsed, it would end the code early). So any right parentheses here+will be replaced with ']', with a warning.+++File: hledger.info, Node: description field, Next: comment field, Prev: code field, Up: hledger fields++14.7.5 description field+------------------------++'description' sets the transaction's description, if any.++ Journal format can't represent a semicolon in a description (when+reparsed, it would start a comment, truncating the description). So any+semicolons here will be replaced with '.,' (a semicolon on its side),+and a warning is printed.+++File: hledger.info, Node: comment field, Next: account field, Prev: description field, Up: hledger fields++14.7.6 comment field+--------------------++'comment' sets the transaction's comment, if any.++ 'commentN', where N is a number, sets the Nth posting's comment.++ You can assign multi-line comments by writing literal '\n' in the+code. A comment starting with '\n' will begin on a new line.++ Comments can contain tags, as usual.++ Posting comments can also contain a posting date. A secondary date,+or a year-less date, will be ignored.+++File: hledger.info, Node: account field, Next: amount field, Prev: comment field, Up: hledger fields++14.7.7 account field+--------------------++Assigning to 'accountN', where N is 1 to 99, sets the account name of+the Nth posting, and causes that posting to be generated.++ Most often there are two postings, so you'll want to set 'account1'+and 'account2'. Typically 'account1' is associated with the CSV file,+and is set once with a top-level assignment, while 'account2' is set+based on each transaction's description, in 'if' rules.++ If a posting's account name is left unset but its amount is set, the+account name will be set to 'expenses:unknown' or 'income:unknown'+(depending on the amount's sign).+++File: hledger.info, Node: amount field, Next: currency field, Prev: account field, Up: hledger fields++14.7.8 amount field+-------------------++There are several ways to set posting amounts from CSV, useful in+different situations.++ 1. *'amount'* is the oldest and simplest. Assigning to this sets the+ amount of the first and second postings. In the second posting,+ the amount will be negated; also, if it has a cost attached, it+ will be converted to cost.++ 2. *'amount-in'* and *'amount-out'* work exactly like the above, but+ should be used when the CSV has two amount fields (such as "Debit"+ and "Credit", or "Inflow" and "Outflow"). Whichever field has a+ non-zero value will be used as the amount of the first and second+ postings. Here are some tips to avoid confusion:++ * It's not "amount-in for posting 1 and amount-out for posting+ 2", it is "extract a single amount from the amount-in or+ amount-out field, and use that for posting 1 and (negated) for+ posting 2".+ * Don't use both 'amount' and 'amount-in'/'amount-out' in the+ same rules file; choose based on whether the amount is in a+ single CSV field or spread across two fields.+ * In each record, at most one of the two CSV fields should+ contain a non-zero amount; the other field must contain a zero+ or nothing.+ * hledger assumes both CSV fields contain unsigned numbers, and+ it automatically negates the amount-out values.+ * If the data doesn't fit these requirements, you'll probably+ need an if rule (see Setting amounts).++ 3. *'amountN'* (where N is a number from 1 to 99) sets the amount of+ only a single posting: the Nth posting in the transaction. You'll+ usually need at least two such assignments to make a balanced+ transaction. You can also generate more than two postings, to+ represent more complex transactions. The posting numbers don't+ have to be consecutive; with if rules, higher posting numbers can+ be useful to ensure a certain order of postings.++ 4. *'amountN-in'* and *'amountN-out'* work exactly like the above, but+ should be used when the CSV has two amount fields. This is+ analogous to 'amount-in' and 'amount-out', and those tips also+ apply here.++ 5. Remember that 'fields' can also do assignments. So if you name a+ CSV field "amount" in 'fields', that counts as assigning to+ 'amount'. (If you don't want that, call it something else there,+ like "amount_".)++ 6. The above don't handle every situation; if you need more+ flexibility, use an 'if' rule to set amounts conditionally. See+ Setting amounts below for more on this and on amount-setting+ generally.++ If the CSV numbers have digit group marks (like '1,000.00'), see+'decimal-mark'.++ An amount value can be an amount expression, eg 'amount1 %price ++%fee' (see Amount signs for how this interacts with sign handling).++* Menu:++* Setting amounts::+* Amount signs::+* Amount decimal places::+++File: hledger.info, Node: Setting amounts, Next: Amount signs, Up: amount field++14.7.8.1 Setting amounts+........................++Which amount fields to use depends on how the CSV shows amounts:++ 1. *If the amount is in a single CSV field:*++ a. *If its sign indicates direction of flow:*+ Assign it to 'amountN', to set the Nth posting's amount. N is+ usually 1 or 2 but can go up to 99.++ b. *If another field indicates direction of flow:*+ Use one or more 'if' rules to set the appropriate amount sign.+ Eg:++ # assume a withdrawal unless Type contains "deposit":+ amount1 -%Amount+ if %Type deposit+ amount1 %Amount++ 2. *If the amount is in two CSV fields (such as Debit and Credit, or+ In and Out):*++ a. *If both fields are unsigned:*+ Assign one field to 'amountN-in' and the other to+ 'amountN-out'. hledger will automatically negate the "out"+ field, and will use whichever field value is non-zero as+ posting N's amount.++ b. *If either field is signed:*+ You will probably need to override hledger's sign for one or+ the other field, as in the following example:++ # Negate the -out value, but only if it is not empty:+ fields date, description, amount1-in, amount1-out+ if %amount1-out [1-9]+ amount1-out -%amount1-out++ c. *If both fields can contain a non-zero value (or both can be+ empty):*+ The -in/-out rules normally choose the value which is+ non-zero/non-empty. Some value pairs can be ambiguous, such as '1'+ and 'none'. For such cases, use 'if' rules to help select the+ amount. Eg, to handle the above you could select the value+ containing non-zero digits: 'rules fields date, description, in,+ out if %in [1-9] amount1 %in if %out [1-9] amount1 %out'++ 3. *If you want posting 2's amount converted to cost:*+ Use the unnumbered 'amount' (or 'amount-in' and 'amount-out')+ syntax.++ 4. *If the CSV has only balance amounts, not transaction amounts:*+ Assign to 'balanceN', to set a balance assignment on the Nth+ posting, causing the posting's amount to be calculated+ automatically. 'balance' with no number is equivalent to+ 'balance1'. In this situation hledger is more likely to guess the+ wrong default account name, so you may need to set that explicitly.+++File: hledger.info, Node: Amount signs, Next: Amount decimal places, Prev: Setting amounts, Up: amount field++14.7.8.2 Amount signs+.....................++There is some special handling making it easier to parse and to reverse+amount signs. (This only works for whole amounts, not for cost amounts+such as COST in 'amount1 AMT @ COST'):++ * *If an amount value begins with a plus sign:*+ that will be removed: '+AMT' becomes 'AMT'++ * *If an amount value is parenthesised:*+ it will be de-parenthesised and sign-flipped: '(AMT)' becomes+ '-AMT'++ * *If an amount value has two minus signs (or two sets of+ parentheses, or a minus sign and parentheses):*+ they cancel out and will be removed: '--AMT' or '-(AMT)' becomes+ 'AMT'++ * *If an amount value contains just a sign (or just a set of+ parentheses):*+ that is removed, making it an empty value. '"+"' or '"-"' or+ '"()"' becomes '""'.++ These rules don't apply to a value containing an arithmetic operator+('*', '/', or a '+' or '-' which is not a leading sign or an exponent+sign as in '1e-5'), which is read as an amount expression instead. In+an expression, parentheses group rather than negate: '-(%price + %fee)'+is minus the sum.++ To set an amount to its absolute value, ie discard its sign, use the+'abs' function, eg 'amount1 %{abs(%amt)}'.+++File: hledger.info, Node: Amount decimal places, Prev: Amount signs, Up: amount field++14.7.8.3 Amount decimal places+..............................++When you are reading CSV data, eg with a command like 'hledger -f+foo.csv print', hledger will infer each commodity's decimal precision+(and other commodity display styles) from the amounts - much as when+reading a journal file without 'commodity' directives (see the link).++ Note, the commodity styles are not inferred from the numbers in the+original CSV data; rather, they are inferred from the amounts generated+by the CSV rules.++ When you are importing CSV data with the 'import' command, eg+'hledger import foo.csv', there's another step: 'import' tries to make+the new entries conform to the journal's existing styles. So for each+commodity - let's say it's EUR - 'import' will choose:++ 1. the style declared for EUR by a 'commodity' directive in the+ journal+ 2. otherwise, the style inferred from EUR amounts in the journal+ 3. otherwise, the style inferred from EUR amounts generated by the CSV+ rules.++ TLDR: if 'import' is not generating the precisions or styles you+want, add a 'commodity' directive to specify them.+++File: hledger.info, Node: currency field, Next: balance field, Prev: amount field, Up: hledger fields++14.7.9 currency field+---------------------++'currency' sets a default commodity symbol, to be used for any posting+(or balance) amounts which don't have one. You can use this if the CSV+amounts do not have a currency symbol, eg if it is in a separate column.+(You can also set the symbol within an amount assignment, like 'amount+%amt USD', but sometimes it's more convenient to set it this way.) The+value can be:++ * a commodity symbol, like 'USD' or '$' or '"Some Fund"'; this is+ placed on the left of the number, with no space ('USD5').+ * or a dummy amount with that symbol, like '1 USD' or 'USD 1' or+ '1USD', showing the symbol's position and spacing to use. (The+ amount's number style, if any, like '1.000,00 EUR', is also used as+ a default display style for that commodity.)++ Note the symbol's placement and display style don't matter much when+using 'import', since that command applies the journal's existing+commodity styles to the new entries (see Amount decimal places).++ 'currencyN' does the same for just the Nth posting's amount.++* Menu:++* Setting currency/commodity::+++File: hledger.info, Node: Setting currency/commodity, Up: currency field++14.7.9.1 Setting currency/commodity+...................................++If the currency/commodity symbol is included in the CSV's amount+field(s):++2023-01-01,foo,$123.00++ you don't have to do anything special for the commodity symbol, it+will be assigned as part of the amount. Eg:++fields date,description,amount++2023-01-01 foo+ expenses:unknown $123.00+ income:unknown $-123.00++ If the currency is provided as a separate CSV field:++2023-01-01,foo,USD,123.00++ You can name that field 'currency'; this is a special rule, which+sets the commodity of every amount in the transaction which doesn't have+one (placing the symbol on the left, with no separating space):++fields date,description,currency,amount++2023-01-01 foo+ expenses:unknown USD123.00+ income:unknown USD-123.00++ To put the symbol on the right, separated by a space, give the+'currency' rule a dummy amount showing that:++fields date,description,cur,amt+currency 1 %cur+amount %amt++2023-01-01 foo+ expenses:unknown 123.00 USD+ income:unknown -123.00 USD++ Or, you can use a field assignment to construct the amount yourself:+'amount %amt %cur'.+++File: hledger.info, Node: balance field, Prev: currency field, Up: hledger fields++14.7.10 balance field+---------------------++'balanceN' sets a balance assertion amount (or if the posting amount is+left empty, a balance assignment) on posting N.++ 'balance' is a compatibility spelling for hledger <1.17; it is+equivalent to 'balance1'.++ You can adjust the type of assertion/assignment with the+'balance-type' rule (see below). If the CSV has only balances, not+transaction amounts, see Setting amounts.+++File: hledger.info, Node: balance-type, Next: if, Prev: hledger fields, Up: CSV++14.8 'balance-type'+===================++Balance assertions generated by assigning to balanceN are of the simple+'=' type by default, which is a single-commodity, subaccount-excluding+assertion. You may find the subaccount-including variants more useful,+eg if you have created some virtual subaccounts of checking to help with+budgeting. You can select a different type of assertion with the+'balance-type' rule:++# balance assertions will consider all commodities and all subaccounts+balance-type ==*++ Here are the balance assertion types for quick reference:++= single commodity, exclude subaccounts+=* single commodity, include subaccounts+== multi commodity, exclude subaccounts+==* multi commodity, include subaccounts+++File: hledger.info, Node: if, Next: Matchers, Prev: balance-type, Up: CSV++14.9 'if'+=========++Rules can be applied conditionally, depending on patterns in the CSV+data. This is how you can categorise transactions, selecting an+appropriate account based on their description (eg).++ An 'if' rule is the word 'if', followed by one or more "matcher"+expressions starting on the same line or the next line, followed by one+or more indented rules. Eg,++if MATCHER+ RULE++ or++if+MATCHER+MATCHER+MATCHER+ RULE+ RULE++ Comment lines can appear anywhere within an 'if' rule, and blank+lines can also appear among the indented rules; these do not end the+rule. (One exception: a matcher on the same line as 'if' can begin with+a comment character (eg 'if #groceries' matches records containing+"#groceries"); but on the lines below 'if', such a line would be read as+a comment. There, escape the comment character with a backslash, eg+'\#groceries'.)++ If any of the matchers succeeds, all of the indented rules will be+applied. The rules are usually field assignments, but the following+special rules may also be used within an 'if' rule:++ * 'skip' - skips the matched CSV record (generating no transaction+ from it) (described above).+ * 'end' - skips the rest of the current CSV file (described below).+ * 'merge' - combines the matched CSV record and the next record(s)+ into one record (described below).++ Some examples:++# if the record contains "groceries", set account2 to "expenses:groceries"+if groceries+ account2 expenses:groceries++# if the record contains any of these phrases, set account2 and a transaction comment as shown+if+monthly service fee+atm transaction fee+banking thru software+ account2 expenses:business:banking+ comment XXX deductible ? check it+++File: hledger.info, Node: Matchers, Next: ifs, Prev: if, Up: CSV++14.10 Matchers+==============++There are two kinds of matcher:++ 1. A whole record matcher is simplest: it is just a word, single-line+ text fragment, or other regular expression, which hledger will try+ to match case-insensitively anywhere within the CSV record.+ Eg: 'whole foods'.++ 2. A field matcher has a percent-prefixed CSV field number or name+ before the pattern.+ Eg: '%3 whole foods' or '%description whole foods'.+ hledger will try to match the pattern just within the named CSV+ field. (In records combined by a 'merge' rule, a '_ROWNUM' suffix+ selects a later row's field, eg '%description_2'.)++ When using these, there's two things to be aware of:++ 1. Whole record matchers don't see the exact original record; they see+ a reconstruction of it, in which values are comma-separated, and+ quotes enclosing values and whitespace outside those quotes are+ removed.+ Eg when reading an SSV record like: '2023-01-01 ; "Acme, Inc. " ;+ 1,000'+ the whole record matcher sees instead: '2023-01-01,Acme, Inc.+ ,1,000'++ 2. Field matchers expect either a CSV field number, or a CSV field+ name declared with 'fields'. Anything else will cause it to match+ against the empty string, and probably fail silently (this makes it+ easier to reuse common rules with different CSV files). Don't use+ a hledger field name here (see CSV fields and hledger fields).++ You can also prefix a matcher line with '!' to negate it (at the+start of the line; you can't negate individual terms within the line).+Eg '! whole foods', '! %3 whole foods', '!%description whole foods' will+match if "whole foods" is NOT present.++ The pattern is, as usual in hledger, a POSIX extended regular+expression that also supports GNU word boundaries ('\b', '\B', '\<',+'\>') and nothing else. For more details and tips, see Regular+expressions in CSV rules below.++* Menu:++* Multiple matchers::+* Match groups::+* Regular expressions in CSV rules::+++File: hledger.info, Node: Multiple matchers, Next: Match groups, Up: Matchers++14.10.1 Multiple matchers+-------------------------++When an 'if' rule has multiple matchers, each on its own line,++ * By default they are OR'd (any of them can match).+ * Matcher lines beginning with '&' (or '&&') are AND'ed with the+ matcher above (all in the AND'ed group must match).+ * Matcher lines beginning with '& !' (or '&& !') are first negated+ and then AND'ed with the matcher above.++ You can also combine multiple matchers on the same line separated by+'&&' (AND) or '&& !' (AND NOT). Eg '%description amazon && %date+2025-01-01' will match only when the description field contains "amazon"+and the date field contains "2025-01-01".+++File: hledger.info, Node: Match groups, Next: Regular expressions in CSV rules, Prev: Multiple matchers, Up: Matchers++14.10.2 Match groups+--------------------++Matchers can define match groups: parenthesised portions of the regular+expression which are available for reference in field assignments.+Groups are enclosed in regular parentheses ('(' and ')') and can be+nested. Each group is available in field assignments using the token+'\N', where N is an index into the match groups for this 'if' rule (e.g.+'\1', '\2', etc.).++ Example: Warp credit card payment postings to the beginning of the+billing period (Month start), to match how they are presented in+statements, using posting dates:++if %date (....-..)-..+ comment2 date:\1-01++ Another example: Read the expense account from the CSV field, but+throw away a prefix:++if %account1 liabilities:family:(expenses:.*)+ account1 \1+++File: hledger.info, Node: Regular expressions in CSV rules, Prev: Match groups, Up: Matchers++14.10.3 Regular expressions in CSV rules+----------------------------------------++Regular expressions in 'if' conditions (AKA matchers) are POSIX extended+regular expressions, that also support GNU word boundaries ('\b', '\B',+'\<', '\>'), and nothing else. (For more detail, see Regular+expressions.)++ Here are some examples that might be useful in CSV rules:++ * Is field "foo" truly empty ? 'if %foo ^$'+ * Is it empty or containing only whitespace ? 'if %foo ^ *$'+ * Is it non-empty ? 'if %foo .'+ * Does it contain non-whitespace ? 'if %foo [^ ]'++ Testing the value of numeric fields is a little harder. You can't+use hledger queries like 'amt:0' or 'amt:>10' in CSV rules. But you can+often achieve the same thing with a regular expression.++ Note the content and layout of number fields in CSV varies, and can+change over time (eg if you switch data providers). So numeric regexps+are always somewhat specific to your particular CSV data; and it's a+good idea to make them defensive and robust if you can.++ Here are some examples:++ * Does foo contain a non-zero number ? 'if %foo [1-9]'+ * Is it negative ? 'if %foo -'+ * Is it non-negative ? 'if ! %foo -'+ * Is it >= 10 ? 'if %foo [1-9][0-9]+\.' (assuming a decimal period+ and no leading zeros)+ * Is it >= 10 and < 20 ? 'if %foo \b1[0-9]\.'+++File: hledger.info, Node: ifs, Next: end, Prev: Matchers, Up: CSV++14.11 'ifs'+===========++An "ifs table" is a more compact way to write many if rules.++ * The first line begins with 'ifs', then one or more hledger field+ names, all separated by a delimiter character (any punctuation+ character, your choice) plus optional whitespace. (An older form+ is also supported for backward compatibility: 'if' followed by the+ delimiter with no space between them.)+ * The following lines begin with a matcher, then values to assign to+ each of those hledger fields.+ * Comment lines, beginning with ';' or '#' (optionally indented), are+ also allowed.+ * A blank line (or the end of the file) ends the table.++ Eg:++ifs | HLEDGERFIELD1 | HLEDGERFIELD2 | ...+MATCHER | VALUE | VALUE | ...+MATCHER | VALUE | VALUE | ...+MATCHER | VALUE | VALUE | ...+<empty line>++ This means: for each line in turn, if the matcher matches the current+CSV record, assign all of the non-blank values on that line, without+their surrounding whitespace, to the corresponding hledger fields. All+of the lines are processed, so later lines may override earlier ones.+Except for the blank/whitespace handling, it's equivalent to writing+these if rules:++if MATCHER+ HLEDGERFIELD1 VALUE+ HLEDGERFIELD2 VALUE+ ...++if MATCHER+ HLEDGERFIELD1 VALUE+ HLEDGERFIELD2 VALUE+ ...++if MATCHER+ HLEDGERFIELD1 VALUE+ HLEDGERFIELD2 VALUE+ ...++ Because every matching row is applied in order, the last one that+matches wins. To supply a default, set the field before the table (or+put a catch-all matcher such as '.*' as the first row); later,+more-specific rows will override it when they match.++account2 expenses:unknown++ifs | account2+WHOLE FOODS | expenses:food+WHOLE FOODS.*organic | expenses:food:organic++ In this example a transaction whose description contains "WHOLE FOODS+organic" matches both WHOLE FOODS rows; the last assignment is the one+that remains.++ The 'skip', 'end' and 'merge' actions can also be table columns.+Write a number in the cell on lines where the action should happen, and+leave it blank on other lines. For 'skip' and 'merge' the number is how+many records to skip or merge (1 or more); for 'end', write 1 (any+non-blank value will end). Eg:++ifs | account2 | skip+atm withdrawal fee | expenses:banking |+transfer to savings | | 1++ The delimiter must appear the same number of times in each line of+the table, and it must not appear in the field names, matchers, or+values used in the table (though inside '%{...}' expressions is ok).+You cannot escape it with a backslash.++ Note, the delimiter in an ifs table is unrelated to the one used in+the data file (consider avoiding ',' or ';', because they look+confusing).++ In fact, it's hard to find a delimiter character that never clashes+with anything, so the flexibility can be useful. Some examples:++# | as delimiter; can use a leading !, can't use regex | operator+ifs | account2 | comment+! %amount [0-9][0-9]+\. | expenses:misc |+%desc amazon | expenses:shopping |+%desc amzn | expenses:shopping |+%amount [0-9]{4,} | | TODO: large amount, check it++# ! as delimiter; can't use leading !, can use regex |+ifs ! account2+%desc amazon|amzn ! expenses:shopping++# ` as delimiter; can use both leading ! and regex |+ifs ` account2+! %amount [0-9][0-9]+\. ` expenses:misc+%desc amazon|amzn ` expenses:shopping+++File: hledger.info, Node: end, Next: merge, Prev: ifs, Up: CSV++14.12 'end'+===========++The word 'end', used inside an 'if' or 'ifs' rule, tells hledger to skip+the current record and remaining records in the current CSV file,+whenever the condition is true. Eg:++# if an empty record is seen (assuming five fields), ignore the rest of the CSV file+if ,,,,+ end+++File: hledger.info, Node: merge, Next: include, Prev: end, Up: CSV++14.13 'merge'+=============++if MATCHER+ merge N++ Some banks and brokers export a single transaction as multiple CSV+records - eg a currency conversion or stock trade, with each side of the+trade on its own row. The 'merge' rule combines such related records,+so that they can generate a single journal transaction.++ When a record matches an 'if' rule containing 'merge N' (the word+'merge' followed by a number, or no number, meaning 1), the next N+records are joined onto the matched record, forming a group of rows.+Conversion then proceeds as usual, with the whole group generating one+transaction.++ Fields of the later rows are referenced by adding a '_ROWNUM' suffix+(row number 2 or greater) to the usual field name or number: '%amt_2' or+'%4_2' is row 2's 'amt'/fourth field. Unsuffixed references ('%amt',+'%4') always mean the first row, so the same 'fields' list describes+every row. A reference to a row that isn't there (eg in an unmerged+record) just has an empty value. And if you have declared a field name+that looks like 'NAME_ROWNUM', it keeps its declared meaning; the suffix+interpretation is only a fallback.++ For example, to convert this two-row currency conversion:++2026-09-01,PAYMENT,coffee,-3.50,USD+2026-09-02,CONVERT,converted USD to EUR,-100.00,USD+2026-09-02,CONVERT,converted USD to EUR,90.00,EUR++fields date, type, desc, amt, cur+description %desc+account1 assets:bank:%cur+amount1 %amt %cur++# a conversion's second row holds the amount received; make it posting 2+if %type CONVERT+ merge+ account2 assets:bank:%cur_2+ amount2 %amt_2 %cur_2++if %type PAYMENT+ account2 expenses:unknown++$ hledger print -f conversion.csv+2026-09-01 coffee+ assets:bank:USD -3.50 USD+ expenses:unknown++2026-09-02 converted USD to EUR+ assets:bank:USD -100.00 USD+ assets:bank:EUR 90.00 EUR++ Things to note:++ * 'merge' can also be used as a top-level rule (unconditionally),+ useful for files where every transaction is exactly N+1 rows.+ * 'skip' and 'end' rules are applied before row merging - skipped+ records don't count toward a merge group.+ * The rows of a group must be consecutive in the file (ignoring+ skipped records), and the merging record must be the first of them.+ * Matchers which (if successful) will trigger a 'merge' rule, can+ only usefully reference the first row's fields - the other row+ fields will be empty at this stage.+ * But once a 'merge' rule has been evaluated, later 'if' rules can+ see the whole group; eg a whole-record matcher will see all of its+ rows combined as one, and field matchers can use '%FIELD_ROWNUM'+ references.+ * If fewer than N records remain in the file, just those are merged.+++File: hledger.info, Node: include, Next: Working with CSV, Prev: merge, Up: CSV++14.14 'include'+===============++include RULESFILE++ This includes the contents of another CSV rules file at this point.+'RULESFILE' is an absolute file path or a path relative to the current+file's directory. This can be useful for sharing common rules between+several rules files, eg:++# someaccount.csv.rules++## someaccount-specific rules+fields date,description,amount+account1 assets:someaccount+account2 expenses:misc++## common rules+include categorisation.rules++ Since included rules are effectively inlined, and since for most+rules the last declaration wins, you can override an included file's+rules by writing rules after the 'include' line.+++File: hledger.info, Node: Working with CSV, Next: How CSV rules are evaluated, Prev: include, Up: CSV++14.15 Working with CSV+======================++Some tips for creating rules and importing CSV data regularly:++* Menu:++* CSV rules examples::+* Rapid feedback::+* Well factored rules::+* Deduplicating importing::+* Valid transactions::+++File: hledger.info, Node: CSV rules examples, Next: Rapid feedback, Up: Working with CSV++14.15.1 CSV rules examples+--------------------------++For real-world rules files for many banks, brokers, exchanges and apps,+see the hledger CSV rules library in the hledger repo. These aren't+necessarily maintained, and may need adapting, but they are a good+source of ideas and examples.+++File: hledger.info, Node: Rapid feedback, Next: Well factored rules, Prev: CSV rules examples, Up: Working with CSV++14.15.2 Rapid feedback+----------------------++It's a good idea to get rapid feedback while creating/troubleshooting+CSV rules. Here's a good way, using entr from eradman.com/entrproject:++$ ls foo.csv* | entr bash -c 'echo ----; hledger -f foo.csv print desc:SOMEDESC'++ A desc: query (eg) is used to select just one, or a few, transactions+of interest. "bash -c" is used to run multiple commands, so we can echo+a separator each time the command re-runs, making it easier to read the+output.+++File: hledger.info, Node: Well factored rules, Next: Deduplicating importing, Prev: Rapid feedback, Up: Working with CSV++14.15.3 Well factored rules+---------------------------++Some things that can help reduce duplication and complexity in rules+files:++ * Extracting common rules usable with multiple CSV files into a+ 'common.rules', and adding 'include common.rules' to each CSV's+ rules file.++ * Splitting 'if' rules into smaller 'if' rules, extracting the+ frequently used parts.+++File: hledger.info, Node: Deduplicating importing, Next: Valid transactions, Prev: Well factored rules, Up: Working with CSV++14.15.4 Deduplicating, importing+--------------------------------++When you download a CSV file periodically, eg to get your latest bank+transactions, the new file may overlap with the old one, containing some+of the same records.++ The import command will (a) detect the new transactions, and (b)+append just those transactions to your main journal. It is idempotent,+so you don't have to remember how many times you ran it or with which+version of the CSV. (It keeps state in a hidden '.latest.FILE.csv'+file.) This is the easiest way to import CSV data. Eg:++# download the latest CSV files, then run this command.+# Note, no -f flags needed here.+$ hledger import *.csv [--dry]++ This method works for most CSV files. (Where records have a stable+chronological order, and new records appear only at the new end.)++ A number of other tools and workflows, hledger-specific and+otherwise, exist for converting, deduplicating, classifying and managing+CSV data. See:++ * https://hledger.org/workflows.html#comparing-csv-workflows+ * https://hledger.org/doc.html#setups-and-workflows+ * https://plaintextaccounting.org -> data import/conversion+++File: hledger.info, Node: Valid transactions, Prev: Deduplicating importing, Up: Working with CSV++14.15.5 Valid transactions+--------------------------++After reading a CSV file, hledger post-processes and validates the+generated journal entries as it would for a journal file - balancing+them, applying balance assignments, and canonicalising amount styles.+Any errors at this stage will be reported in the usual way, displaying+the problem entry.++ There is one exception: balance assertions, if you have generated+them, will not be checked, since normally these will work only when the+CSV data is part of the main journal. If you do need to check balance+assertions generated from CSV right away, pipe into another hledger:++$ hledger -f file.csv print | hledger -f- print+++File: hledger.info, Node: How CSV rules are evaluated, Prev: Working with CSV, Up: CSV++14.16 How CSV rules are evaluated+=================================++Here's how to think of CSV rules being evaluated. If you get a+confusing error while reading a CSV file, it may help to try to+understand which of these steps is failing:++ 1. Any included rules files are inlined, from top to bottom, depth+ first (scanning each included file for further includes,+ recursively, before proceeding).++ 2. Top level rules ('date-format', 'fields', 'newest-first', 'skip'+ etc) are read, top to bottom. "Top level rules" means+ non-conditional rules. If a rule occurs more than once, the last+ one wins; except for the 'skip' rule, where the first one wins, and+ the 'source' rule, which may occur only once. A rule written after+ an 'include' would override the same rule in the included file.++ 3. The CSV file is read as text. Any non-ascii characters will be+ decoded using the text encoding specified by the 'encoding' rule,+ otherwise the system locale's text encoding.++ 4. Any top-level skip or end rule is applied. 'skip [N]' immediately+ skips the current or next N CSV records; 'end' immediately skips+ all remaining CSV records (not normally used at top level).++ 5. Now any remaining CSV records are processed. For each CSV record,+ in file order:++ * Is there a conditional skip/end rule that applies for this+ record ? Search the 'if' rules, from top to bottom, for a+ succeeding one containing a 'skip' or 'end' rule. If found,+ skip the specified number of CSV records, then continue at 5.+ Otherwise...++ * Is there a 'merge' rule that applies for this record (top+ level or conditional) ? If so, join the next N CSV records+ onto this record, making one combined record.++ * Do some basic validation on this CSV record (eg, check that it+ has at least two fields).++ * For each hledger field ('date', 'description', 'account1',+ etc.):++ 1. Get the field's assigned value, first searching top level+ assignments, made directly or by the 'fields' rule, then+ assignments made inside succeeding 'if' rules. If there+ are more than one, the last one wins (though it can+ include the previous one's value with '%{FIELDNAME}').++ 2. Compute the field's actual value (as text), by+ interpolating any %CSVFIELD references and %{...}+ expressions within the assigned value (which may use+ other hledger fields' values, computing them first); or+ by choosing a default value if there was no assignment.++ * Generate a hledger transaction from the hledger field values,+ parsing them if needed (eg from text to an amount).++ This is all done by the CSV reader, one of several readers hledger+can use to read transactions from an input file. When all input files+have been read successfully, their transactions are passed to whichever+hledger command the user specified.+++File: hledger.info, Node: Timeclock, Next: Timedot, Prev: CSV, Up: Top++15 Timeclock+************++hledger can read time logs in the timeclock time logging format of+timeclock.el. As with Ledger, hledger's timeclock format is a+subset/variant of timeclock.el's.++ hledger's timeclock format was updated in hledger 1.43 and 1.50. If+your old time logs are rejected, you should adapt them to modern+hledger; for now, you can restore the pre-1.43 behaviour with the+'--old-timeclock' flag.++ Here is the timeclock format (in hledger 1.50+):++# Comment lines like these, and blank lines, are ignored:+# comment line+; comment line+* comment line++# Lines beginning with b, h, or capital O are also ignored, for compatibility:+b SIMPLEDATE HH:MM[:SS][+-ZZZZ][ TEXT]+h SIMPLEDATE HH:MM[:SS][+-ZZZZ][ TEXT]+O SIMPLEDATE HH:MM[:SS][+-ZZZZ][ TEXT]++# Lines beginning with i or o are are clock-in / clock-out entries:+i SIMPLEDATE HH:MM[:SS][+-ZZZZ] ACCOUNT[ DESCRIPTION][;COMMENT]]+o SIMPLEDATE HH:MM[:SS][+-ZZZZ][ ACCOUNT][;COMMENT]++ The date is a hledger simple date (YYYY-MM-DD or similar). The time+parts must use two digits. The seconds are optional. A + or -+four-digit time zone is accepted for compatibility, but currently+ignored; times are always interpreted as a local time.++ In clock-in entries ('i'), the account name is required. A+transaction description, separated from the account name by 2+ spaces,+is optional. A transaction comment, beginning with ';', is also+optional. (Indented following comment lines are also allowed, as in+journal format.)++ Clock-out entries ('o') have no description, but can have a comment+if you wish. A clock-in and clock-out pair form a "transaction" posting+some number of hours to an account - also known as a session. Eg:++i 2015/03/30 09:00:00 session1+o 2015/03/30 10:00:00++$ hledger -f a.timeclock print+2015-03-30 * 09:00-10:00+ (session1) 1.00h++ Clock-ins and clock-outs are matched by their account/session name.+If a clock-out does not specify a name, the most recent unclosed+clock-in is closed. You can have multiple sessions active+simultaneously. Entries are processed in the order they are parsed.+Sessions spanning more than one day are automatically split at day+boundaries.++ Eg, the following time log:++i 2015/03/30 09:00:00 some account optional description after 2 spaces ; optional comment, tags:+o 2015/03/30 09:20:00+i 2015/03/31 22:21:45 another:account+o 2015/04/01 02:00:34+i 2015/04/02 12:00:00 another:account ; this demonstrates multiple sessions being clocked in+i 2015/04/02 13:00:00 some account+o 2015/04/02 14:00:00+o 2015/04/02 15:00:00 another:account++ generates these transactions:++$ hledger -f t.timeclock print+2015-03-30 * optional description after 2 spaces ; optional comment, tags:+ (some account) 0.33333333h++2015-03-31 * 22:21-23:59+ (another:account) 1.6375h++2015-04-01 * 00:00-02:00+ (another:account) 2.00944444h++2015-04-02 * 12:00-15:00 ; this demonstrates multiple sessions being clocked in+ (another:account) 3.00h++2015-04-02 * 13:00-14:00+ (some account) 1.00h++ Here is a sample.timeclock to download and some queries to try:++$ hledger -f sample.timeclock balance # current time balances+$ hledger -f sample.timeclock register -p 2009/3 # sessions in march 2009+$ hledger -f sample.timeclock register -p weekly --depth 1 --empty # time summary by week++ To generate time logs, ie to clock in and clock out, you could:++ * use these shell aliases at the command line:++ alias ti='echo i `date "+%Y-%m-%d %H:%M:%S"` $* >>$TIMELOG'+ alias to='echo o `date "+%Y-%m-%d %H:%M:%S"` >>$TIMELOG'++ * or Emacs's built-in timeclock.el, or the extended timeclock-x.el,+ and perhaps the extras in ledgerutils.el++ * or use the old 'ti' and 'to' scripts in the ledger 2.x repository.+ These rely on a "timeclock" executable which I think is just the+ ledger 2 executable renamed.+++File: hledger.info, Node: Timedot, Next: PART 4 CONCEPTS, Prev: Timeclock, Up: Top++16 Timedot+**********++'timedot' format is hledger's human-friendly time logging format.+Compared to 'timeclock' format, it is more convenient for quick,+approximate, and retroactive time logging, and more human-readable (you+can see at a glance where time was spent). A quick example:++2023-05-01+hom:errands .... .... ; two hours; the space is ignored+fos:hledger:timedot .. ; half an hour+per:admin:finance ; no time spent yet++ hledger reads this as a transaction on this day with three+(unbalanced) postings, where each dot represents 0.25 (of an hour, we+usually assume).++$ hledger -f a.timedot print # .timedot file extension (or timedot: prefix) is required+2023-05-01 *+ (hom:errands) 2.00 ; two hours; the space is ignored+ (fos:hledger:timedot) 0.50 ; half an hour+ (per:admin:finance) 0.00 ; no time spent yet++ A timedot file specifies a series of transactions, usually one per+day. (Unlike in a journal file, these "transactions" don't need to+balance; time logs use "single entry accounting".)++ Each transaction begins with a *date line*: a line whose first word+looks like a simple date, ie three groups of digits separated by '-',+'/', or '.' (if these cannot be parsed as a valid date, an error is+raised). After the date, on the same line, there can optionally be a+transaction description, and after ';', a transaction comment (possibly+containing tags).++ After the date line are zero or more *posting lines*. A timedot+posting line begins with a hledger-style account name, optionally+indented. After the account name there are *two or more spaces* and+then a *timedot amount*. (Or nothing, which is equivalent to a zero+amount.)++ Timedot amounts can be written in several ways:++ * One or more *dots* ('.')+ Each dot represents a quarter hour. (There's no commodity symbol,+ but usually we assume hours.) Spaces can optionally be used for+ aligning or grouping dots, eg '.... .... ..' is easy to read as 2.5+ hours.++ * A *bare number* (integer or decimal)+ This can be more precise or more convenient, eg for large+ durations.++ * A *number followed by a time unit* ('s', 'm', 'h', 'd', 'w', 'mo',+ or 'y')+ representing seconds, minutes, hours, days, weeks, months or years,+ which will be converted to hours using these ratios: 60s = 1m, 60m+ = 1h, 24h = 1d, 7d = 1w, 30d = 1mo, 365d = 1y. This allows use of+ more convenient time units.++ * One or more *timedot letters*+ These work like dots, except they also generate a posting tag 't:'+ (short for "type") with the letter as its value, and a separate+ posting for each of the letter values. This adds a second+ dimension of categorisation - in addition to account name, you'll+ have the 't' tag's value, which can be shown in reports with+ '--pivot t', '--pivot acct:t', etc.++ Posting lines can end with a hledger-style posting comment (text+after ';'), optionally containing tags.++ Lines beginning with '#' or ';' are *comment lines*, and ignored.+Blank lines are also ignored.++ There is some additional support for users of Emacs org mode:++ * Before the first date line, lines beginning with '*' are also+ treated as comments, and ignored. This allows top-level org+ headings in a timedot file.++ * From the first date line onward, org heading prefixes (one or more+ '*''s followed by a space) are ignored, with the rest of the line+ being parsed normally. This allows timedot date or posting lines+ to also be org headings.++ Timedot files don't support directives like journal files. So a+common pattern is to have a main journal file that contains any needed+directives, and then includes the timedot file ('include time.timedot').++* Menu:++* Timedot examples::+++File: hledger.info, Node: Timedot examples, Up: Timedot++16.1 Timedot examples+=====================++Numbers:++2016/2/3+inc:client1 4+fos:hledger 3h+biz:research 60m++ Dots:++# on this day, 6h was spent on client work, 1.5h on haskell FOSS work, etc.+2016/2/1+inc:client1 .... .... .... .... .... ....+fos:haskell .... ..+biz:research .++2016/2/2+inc:client1 .... ....+biz:research .++$ hledger -f a.timedot print date:2016/2/2+2016-02-02 *+ (inc:client1) 2.00+ (biz:research) 0.25++$ hledger -f a.timedot bal --daily+Balance changes in 2016-02-01..2016-02-02:++ || 2016-02-01 2016-02-02 +==============++========================+ biz:research || 0.25 0.25 + fos:haskell || 1.50 0 + inc:client1 || 6.00 2.00 +--------------++------------------------+ || 7.75 2.25 ++ Letters:++# Activity types:+# c cleanup/catchup/repair+# e enhancement+# s support+# l learning/research++2023-11-01+work:adm ccecces++$ hledger -f a.timedot print+2023-11-01 *+ (work:adm) 1.00 ; t:c+ (work:adm) 0.50 ; t:e+ (work:adm) 0.25 ; t:s++$ hledger -f a.timedot bal+ 1.75 work:adm+--------------------+ 1.75 ++$ hledger -f a.timedot bal --pivot t+ 1.00 c+ 0.50 e+ 0.25 s+--------------------+ 1.75 ++ Org:++* 2023 Work Diary+** Q1+*** 2023-02-28+**** DONE+yoga ....+**** BEGUN+hom:chores+ cleaning ...+ water plants+ outdoor - one full watering can+ indoor - light watering+**** TODO+adm:planning:trip+*** LATER++ Using '.' as account name separator:++2016/2/4+fos.hledger.timedot 4h+fos.ledger ..++$ hledger -f a.timedot --alias '/\./=:' bal -t+ 4.50 fos+ 4.00 hledger:timedot+ 0.50 ledger+--------------------+ 4.50 +++File: hledger.info, Node: PART 4 CONCEPTS, Next: Time periods, Prev: Timedot, Up: Top++17 PART 4: CONCEPTS+*******************+++File: hledger.info, Node: Time periods, Next: Queries, Prev: PART 4 CONCEPTS, Up: Top++18 Time periods+***************++* Menu:++* Report start & end date::+* Smart dates::+* Report intervals::+* Date adjustments::+* Period expressions::+++File: hledger.info, Node: Report start & end date, Next: Smart dates, Up: Time periods++18.1 Report start & end date+============================++Most hledger reports will by default show the full time period+represented by the journal. The report start date will be the earliest+transaction or posting date, and the report end date will be the latest+transaction, posting, or market price date.++ Often you will want to see a shorter period, such as the current+month. You can specify a start and/or end date with the '-b/--begin',+'-e/--end', or '-p/--period' options, or a 'date:' query argument,+described below. All of these accept the smart date syntax, also+described below.++ End dates are exclusive; specify the day after the last day you want+to see in the report.++ When dates are specified by multiple options, the last (right-most)+option wins. And when 'date:' queries and date options are combined,+the report period will be their intersection.++ Examples:++'-b 2016/3/17'++ beginning on St. Patrick's day 2016+'-e 12/1'++ ending at the start of December 1st in the current year+'-p 'this month''++ during the current month+'-p thismonth'++ same as above, spaces are optional+'-b 2023'++ beginning on the first day of 2023+'date:2023..' or 'date:2023-'++ same as above++ '-b 2024 -e 2025 -p '2000 to 2030' date:2020-01 date:2020' :+during January 2020 (the smallest common period, with the -p overriding+-b and -e)+++File: hledger.info, Node: Smart dates, Next: Report intervals, Prev: Report start & end date, Up: Time periods++18.2 Smart dates+================++In hledger's user interfaces (though not in the journal file), you can+optionally use "smart date" syntax. Smart dates can be written with+english words, can be relative, and can have parts omitted. Missing+parts are inferred as 1, when needed. Smart dates can be interpreted as+dates or periods depending on the context.++ Examples:++ '2004-01-01', '2004/10/1', '2004.9.1', '20240504', '2024Q1' :+Exact dates. The year must have at least four digits, the month must be+1-12, the day must be 1-31, the separator can be '-' or '/' or '.' or+nothing. The q can be upper or lower case and the quarter number must+be 1-4.++'2004-10'++ start of month+'2004q3'++ start of third quarter of 2004+'q3'++ start of third quarter of current year+'2004'++ start of year+'10/1' or 'oct' or 'october'++ October 1st in current year+'21'++ 21st day in current month+'yesterday, today, tomorrow'++ -1, 0, 1 days from today+'last/this/next day/week/month/quarter/year'++ -1, 0, 1 periods from the current period+'last/this/next tuesday'++ the previous occurrence of the named day, or the next occurrence+ after today+'last/this/next february'++ the previous occurrence of 1st of the named month, or the next+ occurrence after the current month+'in n days/weeks/months/quarters/years'++ n periods from the current period+'n days/weeks/months/quarters/years ahead'++ n periods from the current period+'n days/weeks/months/quarters/years ago'++ -n periods from the current period+'20181201'++ 8 digit YYYYMMDD with valid year month and day+'201812'++ 6 digit YYYYMM with valid year and month++ Dates with no separators are allowed but might give surprising+results if mistyped:++ * '20181301' (YYYYMMDD with an invalid month) is parsed as an+ eight-digit year+ * '20181232' (YYYYMMDD with an invalid day) gives a parse error+ * '201801012' (a valid YYYYMMDD followed by additional digits) gives+ a parse error++ The meaning of relative dates depends on today's date. If you need+to test or reproduce old reports, you can use the '--today' option to+override that. (Except for periodic transaction rules, which are not+affected by '--today'.)+++File: hledger.info, Node: Report intervals, Next: Date adjustments, Prev: Smart dates, Up: Time periods++18.3 Report intervals+=====================++A report interval can be specified so that reports like register,+balance or activity become multi-period, showing each subperiod as a+separate row or column.++ The following standard intervals can be enabled with command-line+flags:++ * '-D/--daily'+ * '-W/--weekly'+ * '-M/--monthly'+ * '-Q/--quarterly'+ * '-Y/--yearly'++ More complex intervals can be specified using '-p/--period',+described below.+++File: hledger.info, Node: Date adjustments, Next: Period expressions, Prev: Report intervals, Up: Time periods++18.4 Date adjustments+=====================++* Menu:++* Start date adjustment::+* End date adjustment::+++File: hledger.info, Node: Start date adjustment, Next: End date adjustment, Up: Date adjustments++18.4.1 Start date adjustment+----------------------------++If you let hledger infer a report's start date, it will adjust the date+to the previous natural boundary of the report interval, for convenient+periodic reports. (If you don't want that, specify a start date.)++ For example, if the journal's first transaction is on january 10th,++ * 'hledger register' (no report interval) will start the report on+ january 10th.+ * 'hledger register --monthly' will start the report on the previous+ month boundary, january 1st.+ * 'hledger register --monthly --begin 1/5' will start the report on+ january 5th [1].++ The start date of transactions generated by periodic transaction+rules is chosen separately; see Forecast period, in detail.+++File: hledger.info, Node: End date adjustment, Prev: Start date adjustment, Up: Date adjustments++18.4.2 End date adjustment+--------------------------++A report's end date is always adjusted to include a whole number of+intervals, so that the last subperiod has the same length as the others.++ For example, if the journal's last transaction is on february 20th,++ * 'hledger register' will end the report on february 20th.+ * 'hledger register --monthly' will end the report at the end of+ february.+ * 'hledger register --monthly --end 2/14' also will end the report at+ the end of february (overriding the requested end date).+ * 'hledger register --monthly --begin 1/5 --end 2/14' will end the+ report on march 4th.+++File: hledger.info, Node: Period expressions, Prev: Date adjustments, Up: Time periods++18.5 Period expressions+=======================++The '-p/--period' option specifies a period expression, which is a+compact way of expressing a start date, end date, and/or report+interval.++ Here's a period expression with a start and end date (specifying the+first quarter of 2009):++'-p "from 2009/1/1 to 2009/4/1"'++ Several keywords like "from" and "to" are supported for readability;+these are optional. "to" can also be written as ".." or "-". (Except+that a lone day number, directly after a "-" with no spaces, is not+accepted; eg '2026-13' is more likely a mistyped date than "2026 to the+13th of this month", so it's an error. To mean the latter, write+'2026..13'.) The spaces are also optional, as long as you don't run two+dates together. So the following are equivalent to the above:++'-p "2009/1/1 2009/4/1"'+'-p2009/1/1to2009/4/1'+'-p2009/1/1..2009/4/1'++ Dates are smart dates, so if the current year is 2009, these are also+equivalent to the above:++'-p "1/1 4/1"'+'-p "jan-apr"'+'-p "this year to 4/1"'++ If you specify only one date, the missing start or end date will be+the earliest or latest transaction date in the journal:++'-p "from 2009/1/1"' everything after january 1, 2009+'-p "since 2009/1"' the same, since is a synonym+'-p "from 2009"' the same+'-p "to 2009"' everything before january 1, 2009++ You can also specify a period by writing a single partial or full+date:++'-p "2009"' the year 2009; equivalent to “2009/1/1 to 2010/1/1”+'-p "2009/1"' the month of january 2009; equivalent to “2009/1/1 to+ 2009/2/1”+'-p the first day of 2009; equivalent to “2009/1/1 to+"2009/1/1"' 2009/1/2”++ or by using the "Q" quarter-year syntax (case insensitive):++'-p "2009Q1"' first quarter of 2009, equivalent to “2009/1/1 to+ 2009/4/1”+'-p "q4"' fourth quarter of the current year++* Menu:++* Period expressions with a report interval::+* More complex report intervals::+* Multiple weekday intervals::+++File: hledger.info, Node: Period expressions with a report interval, Next: More complex report intervals, Up: Period expressions++18.5.1 Period expressions with a report interval+------------------------------------------------++A period expression can also begin with a report interval, separated+from the start/end dates (if any) by a space or the word 'in':++'-p "weekly from 2009/1/1 to 2009/4/1"'+'-p "monthly in 2008"'+'-p "quarterly"'+++File: hledger.info, Node: More complex report intervals, Next: Multiple weekday intervals, Prev: Period expressions with a report interval, Up: Period expressions++18.5.2 More complex report intervals+------------------------------------++Some more complex intervals can be specified within period expressions,+such as:++ * 'biweekly' (every two weeks)+ * 'fortnightly'+ * 'bimonthly' (every two months)+ * 'every day|week|month|quarter|year'+ * 'every N days|weeks|months|quarters|years'++ Weekly on a custom day:++ * 'every Nth day of week' ('th', 'nd', 'rd', or 'st' are all accepted+ after the number)+ * 'every WEEKDAYNAME' (full or three-letter english weekday name,+ case insensitive)++ Monthly on a custom day:++ * 'every Nth day [of month]' ('31st day' will be adjusted to each+ month's last day)+ * 'every Nth WEEKDAYNAME [of month]'++ Yearly on a custom month and day:++ * 'every MM/DD [of year]' (month number and day of month number)+ * 'every MONTHNAME DDth [of year]' (full or three-letter english+ month name, case insensitive, and day of month number)+ * 'every DDth MONTHNAME [of year]' (equivalent to the above)++ Examples:++'-p "bimonthly from+2008"'+'-p "every 2 weeks"'+'-p "every 5 months from+2009/03"'+'-p "every 2nd day of periods will go from Tue to Tue+week"'+'-p "every Tue"' same+'-p "every 15th day"' period boundaries will be on 15th of each+ month+'-p "every 2nd Monday"' period boundaries will be on second Monday+ of each month+'-p "every 11/05"' yearly periods with boundaries on 5th of+ November+'-p "every 5th November"' same+'-p "every Nov 5th"' same++ Show historical balances at end of the 15th day of each month (N is+an end date, exclusive as always):++$ hledger balance -H -p "every 16th day"++ Group postings from the start of wednesday to end of the following+tuesday (N is both (inclusive) start date and (exclusive) end date):++$ hledger register checking -p "every 3rd day of week"+++File: hledger.info, Node: Multiple weekday intervals, Prev: More complex report intervals, Up: Period expressions++18.5.3 Multiple weekday intervals+---------------------------------++This special form is also supported:++ * 'every WEEKDAYNAME,WEEKDAYNAME,...' (full or three-letter english+ weekday names, case insensitive)++ Also, 'weekday' and 'weekendday' are shorthand for+'mon,tue,wed,thu,fri' and 'sat,sun'.++ This is mainly intended for use with '--forecast', to generate+periodic transactions on arbitrary days of the week. It may be less+useful with '-p', since it divides each week into subperiods of unequal+length, which is unusual. (Related: #1632)++ Examples:++'-p "every dates will be Mon, Wed, Fri; periods will be+mon,wed,fri"' Mon-Tue, Wed-Thu, Fri-Sun+'-p "every dates will be Mon, Tue, Wed, Thu, Fri; periods will+weekday"' be Mon, Tue, Wed, Thu, Fri-Sun+'-p "every dates will be Sat, Sun; periods will be Sat, Sun-Fri+weekendday"'+++File: hledger.info, Node: Queries, Next: Depth, Prev: Time periods, Up: Top++19 Queries+**********++Many hledger commands accept query arguments, which restrict their scope+and let you report on a precise subset of your data. Here's a quick+overview of hledger's queries:++ * By default, a query argument is treated as a case-insensitive+ substring pattern for matching account names. Eg:++ dining groceries+ car:fuel++ * Patterns containing spaces or other special characters must be+ enclosed in single or double quotes:++ 'personal care'++ * Patterns are actually regular expressions, so you can add regexp+ metacharacters for more precision (or you may need to+ backslash-escape certain characters; see "Regular expressions"+ above):++ '^expenses\b'+ 'food$'+ 'fuel|repair'+ 'accounts (payable|receivable)'++ * To match something other than the account name, you can add a query+ type prefix, such as:++ 'date:202312-'+ 'status:'+ 'desc:amazon'+ 'cur:USD'+ 'cur:\\$'+ 'amt:'>0''+ 'change:'>100'', 'balance:'<0'' (match report rows or entries by+ their change or balance, see below)+ 'acct:groceries' (but 'acct:' is the default, so we usually don't+ bother writing it)++ * To match in any field, or by date, use the 'find:' query type, or+ '::' for short:++ '::amazon'+ '::2024'+ '::amazon ::2024' (both must match)++ * To negate a query, add a 'not:' prefix:++ not:status:'*'+ not:desc:'opening|closing'+ not:cur:USD++ * Multiple query terms can be combined, as space-separated queries+ Eg: 'hledger print date:2022 desc:amazon desc:amzn' (show+ transactions dated in 2022 whose description contains "amazon" or+ "amzn").++ * Or more flexibly as boolean queries. Eg: 'hledger print+ expr:'date:2022 and (desc:amazon or desc:amzn) and not+ date:202210''++ All hledger commands use the same query language, but different+commands may interpret the query in different ways. Here's the gist of+it (see PART 2: COMMANDS above for the commands):++ * Transaction-oriented commands ('print', 'aregister', 'close',+ 'import', 'descriptions'..) try to match transactions (including+ the transaction's postings).++ * Posting-oriented commands ('register', 'balance', 'balancesheet',+ 'incomestatement', 'accounts'..) try to match postings. Postings+ inherit their transaction's attributes for querying purposes, so+ transaction fields like date or description can still be referenced+ in a posting query.++ * A few commands match in more specific ways. (Eg 'aregister', which+ has a special first argument.)++* Menu:++* Query types::+* Negative queries::+* Space-separated queries::+* Boolean queries::+* Queries and command options::+* Queries and account aliases::+* Queries and valuation::+++File: hledger.info, Node: Query types, Next: Negative queries, Up: Queries++19.1 Query types+================++Here are the query types available.++ In the ones which take a regular expression, an empty one (eg 'desc:'+or '::') matches anything. (Except in 'cur:', which must match the+whole symbol, so an empty 'cur:' matches amounts with no commodity+symbol.)++* Menu:++* acct query::+* amt query::+* balance and change queries::+* code query::+* cur query::+* desc query::+* date query::+* date2 query::+* depth query::+* find query::+* note query::+* payee query::+* real query::+* status query::+* type query::+* tag query::+++File: hledger.info, Node: acct query, Next: amt query, Up: Query types++19.1.1 acct: query+------------------++*'acct:REGEX'*, or just *'REGEX'*+Match account names containing this case insensitive regular expression.+This is the default query type, so we usually don't bother writing the+"acct:" prefix.+++File: hledger.info, Node: amt query, Next: balance and change queries, Prev: acct query, Up: Query types++19.1.2 amt: query+-----------------++*'amt:N, amt:'<N', amt:'<=N', amt:'>N', amt:'>=N''*, optionally with a+commodity symbol, eg 'amt:'>$100'' or 'amt:'>100 EUR''+Match postings with an amount equal to, less than, or greater than N.+'amt:' needs quotes to hide the less than/greater than sign from the+command line shell.++ The comparison has two modes: if N is preceded by a + or - sign (or+is 0), the two signed numbers are compared. Otherwise, the absolute+magnitudes are compared, ignoring sign.++ If N has a commodity symbol (before or after the number, quoted with+'"' if needed), only amounts in that commodity are compared; a posting+with none doesn't match. Otherwise, amounts in any commodity are+compared. A posting whose amount has several commodities matches if any+one of them does.++ Keep in mind that 'amt:' matches posting amounts, not account+balances. To match accounts, or periods, by their change or balance,+use 'change:' or 'balance:'.+++File: hledger.info, Node: balance and change queries, Next: code query, Prev: amt query, Up: Query types++19.1.3 balance: and change: queries+-----------------------------------++*'change:N, change:'<N', change:'<=N', change:'>N', change:'>=N''*,+*'balance:N, balance:'<N', balance:'<=N', balance:'>N', balance:'>=N''*,+optionally with a commodity symbol, eg 'change:'>$100'' or 'balance:'<0+EUR''+Match report rows (or entries) by their summed amounts: 'change:' by the+row's change, the sum of its postings; 'balance:' by the row's balance,+the sum of all its postings up to the end of its period. Unlike 'amt:',+which tests each posting before postings are added up, these test the+amounts a report shows after adding them up. Eg:++$ hledger bal expenses change:'>100' # expense accounts which changed by more than 100+$ hledger bal assets balance:'<0' # asset accounts with a negative balance+$ hledger reg gifts -M change:'>100' # months with more than 100 in gift expenses+$ hledger areg checking balance:'<0' # the transactions after which checking was overdrawn+$ hledger print not:change:0 # entries with a tolerated imbalance or unbalanced virtual postings++ The comparison works as with 'amt:': signed if N has a + or - sign+(or is 0), otherwise by absolute magnitude. Like 'amt:', these test+amounts' real signs, not the signs they are displayed with (after+'--invert', or the sign normalisation in 'balancesheet',+'incomestatement' etc.); so 'incomestatement change:'<-1000'' finds the+large revenues. If N has a commodity symbol, only that commodity's part+of the amount is compared, and an amount with none of it doesn't match.+An amount with several commodities matches if any one of them does.++ 'balance:' always means the actual balance, from the start of the+journal (or of the postings matched by the other query terms), whether+or not the report is a historical ('-H') one. So the amounts a report+shows are not always the ones tested; '-H' shows balances. A date span+('date:2026', '-p', '-b'/'-e') sets the report period and does not limit+the balance, as with '-H'. But query terms which exclude postings also+exclude them from the balance; this includes 'not:date:' and date terms+combined with OR.++ What is tested depends on the kind of item being matched:++ * In balance reports ('balance', 'balancesheet', 'incomestatement',+ etc.), each account's own change over the report period, or its own+ balance at the end of the report period, as shown in list mode+ (without or with '-H'). In a multi-period report, the change is+ the row's Total column, and the balance is the last column's (with+ '-H'). Accounts which don't match are left out, as if excluded by+ an account query. So in tree mode, a parent account is shown if it+ has matching subaccounts, with a balance including just those; and+ the report's totals and percentages include just the matching+ accounts. To test parent accounts' subaccount-inclusive amounts+ instead, limit the depth, eg 'bal -1 change:'>100''. An account+ matched by 'balance:' is shown even if it had no postings in the+ report period.++ * In budget reports ('balance --budget'), rows are hidden if their+ actual change or balance (including subaccounts) doesn't match.+ The other rows, and the totals, are unchanged, since budget goals+ are often set on parent accounts.++ * In 'register', 'change:' tests each posting's amount, or with a+ report interval, each period's amount; 'balance:' tests the running+ total after it (the actual balance, even without '-H').++ * In 'aregister', 'change:' tests each transaction's change to the+ account; 'balance:' tests the account's balance after it.++ * In 'print' (and 'descriptions', 'notes' and 'codes'), both test+ each entry's sum of postings (an entry has no balance), converted+ to cost as in transaction balancing, including any unbalanced+ virtual postings. Since an entry's real postings must balance,+ this will be zero, or a small tolerated imbalance, plus the amount+ of any unbalanced virtual postings. (To find large transactions,+ use 'amt:' instead, eg 'print amt:'>1000''.)++ * In 'holdings', each line (one commodity in one account) has two+ amounts, its units and its market value. 'balance:' tests the+ units, or with a commodity symbol, whichever of them is in that+ commodity (so 'balance:'>$1000'' tests the value). 'change:'+ likewise tests the change in units during the report period, or its+ value. Unlike in other reports, '-V'/'-X' don't change which+ amount is tested; to test the value, write its commodity symbol.+ With '-B', the cost is tested instead of the value (eg 'holdings -B+ balance:'>$1000''). The totals cover just the lines shown, but+ Weight is still relative to all the holdings.++ * Other commands ignore these terms.++ In registers, hidden rows still count in the running total or+balance, which is the account's real one. (Unlike 'amt:', which+excludes the postings themselves, so they don't count.)++ 'change:' and 'balance:' can be combined with other query terms only+by AND, and negated with 'not:'. They can't be used inside OR, a+negated group, 'any:' or 'all:'. As with other query terms which aren't+OR'd, multiple terms must all match, so 'change:'>100' change:'<500''+selects a range, and 'change:'>100' balance:'<0'' requires both.+++File: hledger.info, Node: code query, Next: cur query, Prev: balance and change queries, Up: Query types++19.1.4 code: query+------------------++*'code:REGEX'*+Match by transaction code (eg check number).+++File: hledger.info, Node: cur query, Next: desc query, Prev: code query, Up: Query types++19.1.5 cur: query+-----------------++*'cur:FULLREGEX'*+Match postings or transactions including any amounts whose+currency/commodity symbol is fully matched by REGEX. (Contrary to+hledger's usual infix matching. To do infix matching, write+'.*REGEX.*'.)++ To match special characters which are regex-significant, escape them+with '\'. And at the command line, characters which are+shell-significant need one more level of escaping - eg to match the+dollar sign, write 'cur:\\$' or 'cur:'\$''.++ Amounts written with a commodity alias have been converted to the+commodity, so 'cur:' matches them by the commodity's symbol, not the+alias.+++File: hledger.info, Node: desc query, Next: date query, Prev: cur query, Up: Query types++19.1.6 desc: query+------------------++*'desc:REGEX'*+Match transaction descriptions.+++File: hledger.info, Node: date query, Next: date2 query, Prev: desc query, Up: Query types++19.1.7 date: query+------------------++*'date:PERIODEXPR'*+Match dates (or with the '--date2' flag, secondary dates) within the+specified period. PERIODEXPR is a period expression. Examples:+'date:2016', 'date:thismonth', 'date:2/1-2/15',+'date:2021-07-27..nextquarter'.++ PERIODEXPR may include a report interval (since 1.52). On the+command line, this is equivalent to specifying a report interval with a+command line option. In other contexts (hledger-ui, hledger-web), the+report interval may be ignored.+++File: hledger.info, Node: date2 query, Next: depth query, Prev: date query, Up: Query types++19.1.8 date2: query+-------------------++*'date2:PERIODEXPR'*+If you use secondary dates: this matches secondary dates within the+specified period. It is not affected by the '--date2' flag. A report+interval in PERIODEXPR will be ignored.+++File: hledger.info, Node: depth query, Next: find query, Prev: date2 query, Up: Query types++19.1.9 depth: query+-------------------++*'depth:[REGEXP=]N'*+Match (or display, depending on command) accounts at or above this+depth, optionally only for accounts matching a provided regular+expression. See Depth for detailed rules.+++File: hledger.info, Node: find query, Next: note query, Prev: depth query, Up: Query types++19.1.10 find: query+-------------------++*'find:REGEX'*, or *'::REGEX'*+Match if any text field contains this case insensitive regular+expression: the account name, the amount (as it would be displayed), the+comment, the transaction's description, code and comment, or the name or+value of any tag. Tags include hidden tags and tags inherited from+account and commodity declarations, so a match may come from a tag not+shown in 'print' output. Eg '::dispose' finds lot disposals, which have+a hidden 'ptype: dispose' tag. To see why something matched, 'print+--verbose-tags' shows the hidden tags; for inherited tags, check the+account or commodity directive. Or, if REGEX is also a valid period+expression, match if the date is within that period. So '::amazon'+finds "amazon" anywhere, and '::2024' finds "2024" in any field or a+date in 2024. Unlike 'date:', this does not set the report period.++ Multiple 'find:' terms must all match, like the words of a search.+Eg '::amazon ::2024' shows things matching both. (In a+transaction-oriented command like 'print', the terms may be matched by+different postings.) To match alternatives, use a regular expression:+'::'amazon|amzn''.+++File: hledger.info, Node: note query, Next: payee query, Prev: find query, Up: Query types++19.1.11 note: query+-------------------++*'note:REGEX'*+Match transaction notes (the part of the description right of '|', or+the whole description if there's no '|').+++File: hledger.info, Node: payee query, Next: real query, Prev: note query, Up: Query types++19.1.12 payee: query+--------------------++*'payee:REGEX'*+Match transaction payee/payer names (the part of the description left of+'|', or the whole description if there's no '|').+++File: hledger.info, Node: real query, Next: status query, Prev: payee query, Up: Query types++19.1.13 real: query+-------------------++*'real:, real:0'*+Match real or virtual postings respectively.+++File: hledger.info, Node: status query, Next: type query, Prev: real query, Up: Query types++19.1.14 status: query+---------------------++*'status:, status:!, status:*'*+Match unmarked, pending, or cleared transactions respectively.+++File: hledger.info, Node: type query, Next: tag query, Prev: status query, Up: Query types++19.1.15 type: query+-------------------++*'type:TYPECODES'*+Match by account type (see Declaring accounts > Account types).+'TYPECODES' is one or more of the single-letter account type codes+'ALERXCVGUM', case insensitive. Note 'type:A', 'type:E', and 'type:R'+will also match their respective subtypes 'C' (Cash), 'V' (Conversion),+'U' (UnrealisedGain) and 'M' (Imbalance), and 'G' (Gain). Certain kinds+of account alias can disrupt account types, see Rewriting accounts >+Aliases and account types.+++File: hledger.info, Node: tag query, Prev: type query, Up: Query types++19.1.16 tag: query+------------------++*'tag:NAMEREGEX[=VALREGEX]'*+Match by tag name, and optionally also by tag value. Note:++ * Both regular expressions do infix matching. If you need a complete+ match, use '^' and '$'.+ Eg: 'tag:'^fullname$'', 'tag:'^fullname$=^fullvalue$'+ * To match values, ignoring names, do 'tag:=VALREGEX'+ * With an empty NAMEREGEX, 'tag:' matches anything which has a tag,+ and 'not:tag:' matches anything which has none.+ * With an empty VALREGEX, 'tag:NAMEREGEX=' matches that tag with any+ value.+ * Accounts also inherit the tags of their parent accounts.+ * Postings also inherit the tags of their account and their+ transaction .+ * Transactions also acquire the tags of their postings.+++File: hledger.info, Node: Negative queries, Next: Space-separated queries, Prev: Query types, Up: Queries++19.2 Negative queries+=====================++* Menu:++* not query::+++File: hledger.info, Node: not query, Up: Negative queries++19.2.1 not: query+-----------------++*'not:QUERY'*+You can prepend *'not:'* to a query to negate the match.+Eg: 'not:equity', 'not:desc:apple'+(Also, a trick: 'not:not:...' can sometimes solve query problems+conveniently.)+++File: hledger.info, Node: Space-separated queries, Next: Boolean queries, Prev: Negative queries, Up: Queries++19.3 Space-separated queries+============================++When given multiple space-separated query terms, most commands select+things which match:++ * any of the description terms AND+ * any of the account terms AND+ * any of the status terms AND+ * all the other terms.++ The print command is a little different, showing transactions which:++ * match any of the description terms AND+ * have any postings matching any of the positive account terms AND+ * have no postings matching any of the negative account terms AND+ * match all the other terms.+++File: hledger.info, Node: Boolean queries, Next: Queries and command options, Prev: Space-separated queries, Up: Queries++19.4 Boolean queries+====================++For more complex needs, you can combine query terms with 'NOT', 'AND',+'OR' operators (case insensitive) and parentheses, writing the whole+expression in quotes with one of three prefixes: 'expr:', 'any:' or+'all:'. Eg, to show transactions involving both cash and expense+accounts:++hledger print expr:'cash AND expenses'++ The prefix and the quotes are required. Two more things to know:++ * 'date:' queries may not be used inside an OR expression (it could+ produce a report with disjoint or unclear report periods).+ * Space-separated terms can also appear inside a boolean query,+ combining as described in space-separated queries; but it's+ probably clearer to avoid mixing the two styles.++* Menu:++* expr query::+* any query::+* all query::+++File: hledger.info, Node: expr query, Next: any query, Up: Boolean queries++19.4.1 expr: query+------------------++*'expr:'QUERYEXPR''*+The general purpose boolean query. It can match transactions, postings,+accounts, etc. depending on context. Eg, 'expr:'date:lastmonth AND NOT+(food OR rent)'' matches things dated in the last month, without food or+rent in the account name.++ With transaction-oriented commands like 'print', posting-oriented+terms like 'acct:' and 'amt:' match a transaction if they match any of+its postings. So, 'hledger print expr:'cash AND amt:>0'' shows+transactions which have at least one cash posting and at least one+positive-amount posting (these are not necessarily the same posting).+++File: hledger.info, Node: any query, Next: all query, Prev: expr query, Up: Boolean queries++19.4.2 any: query+-----------------++*'any:'QUERYEXPR''*+Matches a transaction, if at least one of its postings is matched by+QUERYEXPR. So, 'hledger print any:'cash AND amt:>0'' shows transactions+which have at least one posting that both involves a cash account and+has a positive amount.++ Unlike 'expr:', 'any:' always considers whole transactions. So,+'hledger balance expenses any:cash' shows expenses from transactions+involving cash, and 'hledger balance expenses not:any:cash' shows+expenses from transactions not involving cash.++ A query containing only 'any:' (or 'all:') terms selects entire+transactions, so its balance report will be zero-balanced, showing where+the money in those transactions came from and went to. For the same+reason, such a query combined with 'register''s '--related' flag shows+nothing: every posting is matched, so there are no unmatched related+postings left to show.+++File: hledger.info, Node: all query, Prev: any query, Up: Boolean queries++19.4.3 all: query+-----------------++*'all:'QUERYEXPR''*+Matches a transaction, if it has at least one posting and all of its+postings are matched by QUERYEXPR. So, 'hledger print all:'cash OR+checking'' shows transactions touching only cash and/or checking+accounts.++ Like 'any:', 'all:' always considers whole transactions. So,+'hledger register all:'cash OR checking'' shows the postings of+transactions touching only cash and/or checking accounts - eg, transfers+between those two. By contrast, 'hledger register expr:'cash OR+checking'' tests each posting on its own, so it could also show, say,+the cash posting of a grocery purchase.+++File: hledger.info, Node: Queries and command options, Next: Queries and account aliases, Prev: Boolean queries, Up: Queries++19.5 Queries and command options+================================++Some queries can also be expressed as command-line options: 'depth:2' is+equivalent to '--depth 2', 'date:2023' is equivalent to '-p 2023', etc.+When you mix command options and query arguments, generally the+resulting query is their intersection.+++File: hledger.info, Node: Queries and account aliases, Next: Queries and valuation, Prev: Queries and command options, Up: Queries++19.6 Queries and account aliases+================================++When account names are rewritten by account aliases, queries see only+the new account names. Eg with 'alias checking = assets:bank:checking',+'acct:bank' matches the rewritten postings, but 'acct:^checking' does+not.+++File: hledger.info, Node: Queries and valuation, Prev: Queries and account aliases, Up: Queries++19.7 Queries and valuation+==========================++When amounts are converted to other commodities in cost or value+reports, 'cur:' and 'amt:' match the old commodity symbol and the old+amount quantity, not the new ones. 'change:' and 'balance:' match the+converted amounts, except in 'print' (see balance: and change: queries).+(With '-B' and no '--lots', a sale from several lots may be left out by+'cur:' or 'amt:', since it is matched as converted to cost; add '--lots'+to match it as written.)+++File: hledger.info, Node: Depth, Next: Pivoting, Prev: Queries, Up: Top++20 Depth+********++With the '--depth NUM' option (short form, usually preferred: '-NUM'),+reports will show accounts only to the specified depth, hiding deeper+subaccounts. Use this when you want a summary with less detail. This+flag has the same effect as a 'depth:' query argument. So all of these+are equivalent: 'depth:2', '--depth=2', '-2'.++ You can also provide custom depths for specific accounts, by+providing a 'REGEX=NUM' argument instead of just 'NUM'. For example,+'--depth assets=2' (or 'depth:assets=2') will collapse accounts matching+the regular expression "assets" to depth 2. So 'assets:bank:savings'+would be collapsed to 'assets:bank', but 'liabilities:bank:credit card'+would not be affected.++ If REGEX contains spaces or other special characters, enclose it in+quotes in the usual way. Eg: '--depth 'credit card=2''++* Menu:++* Combining depth options::+++File: hledger.info, Node: Combining depth options, Up: Depth++20.1 Combining depth options+============================++If a command line contains multiple general depth options, the last one+wins. (Useful for overriding a depth specified by scripts.)++ Or a command may contain a combination of general and custom depth+options. In this case, the most specifically (deepest) matching option+wins. Some examples:++ * '--depth assets=3 --depth expenses=2 --depth 1' would collapse+ accounts containing "assets" to depth 3, accounts containing+ "expenses" to depth 2, and all other accounts to depth 1.++ * '--depth assets=1 --depth savings=2' would collapse+ 'assets:bank:savings' to depth 2 (not depth 1; because "savings"+ matches a deeper part of the account name than "assets").++ Note currently, to override a custom depth option '--depth REGEX=NUM'+with a later option, the later option must use the same REGEX.+++File: hledger.info, Node: Pivoting, Next: Report titles, Prev: Depth, Up: Top++21 Pivoting+***********++Normally, hledger groups amounts and displays their totals by account+(name). With '--pivot PIVOTEXPR', some other field's (or multiple+fields') value is used as a synthetic account name, causing different+grouping and display. PIVOTEXPR can be++ * any of these standard transaction or posting fields (their value is+ substituted): 'status', 'code', 'desc'/'description', 'payee',+ 'note', 'acct'/'account', 'comm'/'cur', 'amt', 'cost'+ * or a tag name+ * or any combination of these, colon-separated.++ Some special cases:++ * Colons appearing in PIVOTEXPR or in a pivoted tag value will+ generate account hierarchy.+ * When pivoting a posting that has multiple values for a tag, the+ tag's first value will be used as the pivoted value.+ * When a posting has multiple commodities, the pivoted value of+ "comm"/"cur" will be "". Also when an unrecognised tag name or+ field is provided, its pivoted value will be "". (If this causes+ confusing output, consider excluding those postings from the+ report.)++ Examples:++2016/02/16 Yearly Dues Payment+ assets:bank account 2 EUR+ income:dues -2 EUR ; member: John Doe, kind: Lifetime++ Normal balance report showing account names:++$ hledger balance+ 2 EUR assets:bank account+ -2 EUR income:dues+--------------------+ 0++ Pivoted balance report, using member: tag values instead:++$ hledger balance --pivot member+ 2 EUR+ -2 EUR John Doe+--------------------+ 0++ One way to show only amounts with a member: value (using a query):++$ hledger balance --pivot member tag:member=.+ -2 EUR John Doe+--------------------+ -2 EUR++ Another way (the acct: query matches against the pivoted "account+name"):++$ hledger balance --pivot member acct:.+ -2 EUR John Doe+--------------------+ -2 EUR++ Hierarchical reports can be generated with multiple pivot values:++$ hledger balance Income:Dues --pivot kind:member+ -2 EUR Lifetime:John Doe+--------------------+ -2 EUR+++File: hledger.info, Node: Report titles, Next: Languages, Prev: Pivoting, Up: Top++22 Report titles+****************++Some reports ('aregister', 'balance' (multi-period), 'balancesheet',+'balancesheetequity', 'cashflow', 'holdings', 'incomestatement') are+displayed with a title by default, and others are not. For most reports+you can set a title with '--title='Some Text'', or suppress the title+with '--title='. Titles are shown in text and HTML output (and in some+commands' CSV/TSV output). In HTML output the title is an '<h3+class="report-title">' element, which you can style with a 'hledger.css'+file.++ Compound reports, like those just mentioned, also have subreport+headings, like Assets and Liabilities in the balance sheet. You can+customise these with '--subreport-titles=HEADING1|HEADING2..', or+suppress them with '--subreport-titles='.++ In both '--title' and '--subreport-titles', you can use '\n' to+generate a newline.++ In multi-period reports each period has a heading describing its date+range or end date. When date ranges correspond to natural period+boundaries, they are described compactly by default. Eg: '2026', 'Q1',+'Jan', 'W02'. (Month names follow the '--lang' option.) You can+disable these compact descriptions by using '--period-titles=dates';+then periods will always be described as 'STARTDATE..ENDDATE'.+++File: hledger.info, Node: Languages, Next: Amount arithmetic, Prev: Report titles, Up: Top++23 Languages+************++hledger's output is in English by default. Report titles, section+headings, column headings, month names and similar structural text can+be shown in another language with the '--lang' option (which can also be+set in a config file), when a translation catalog for that language is+available. (This is hledger's localization support; it covers the+language of hledger's own text, not number or date formats, which come+from the journal, as described below.)++ * '--lang=LANG' selects a language by its tag, like 'de' or 'pt-BR'.+ An unavailable language is an error.+ * '--lang=auto' selects the language from the environment (the+ LANGUAGE, LC_ALL, LC_MESSAGES and LANG variables, see Environment),+ falling back to English.+ * '--lang=en', or no '--lang' option, selects English.++ To always get German output, for example, put it in your config+file's general options:++# ~/.config/hledger/hledger.conf+--lang de++ Currently Brazilian Portuguese ('pt-BR'), French ('fr'), German+('de'), Hawaiian ('haw'), Irish ('ga'), Italian ('it'), Japanese ('ja'),+Russian ('ru'), Simplified Chinese ('zh', also selected by 'zh_CN' or+'zh-Hans'), Spanish ('es') and Ukrainian ('uk') catalogs are built in.+Catalogs are gettext PO files, which the usual translation tools can+edit. hledger also looks for catalogs in the 'locale' subdirectory of+its config directory ('~/.config/hledger/locale/LANG.po' on unix,+'%APPDATA%\hledger\locale\LANG.po' on windows), and merges a catalog+found there over the built-in catalog for the same language, if any. So+a translator can work on a new language with a released hledger, and a+user can adjust terminology to taste. 'hledger --write-lang=LANG' puts+a catalog there to start from: a copy of the built-in catalog for that+language, or for a new language, an untranslated one. (It won't+overwrite a catalog that is already there.) Contributed catalogs are+welcome, and no programming is needed: see Translating hledger in the+developer docs.++ Only hledger's own structural text is translated. Your data (account+names, descriptions, amounts) is never changed; dates keep their ISO+format, and numbers keep the display styles declared for each commodity.+Error messages, journal-format output, and the column headings of CSV,+TSV and JSON output stay in English, since they are commonly read by+other programs. Report titles, however, are translated wherever they+appear, as they would be with '--title'; and an explicit '--title' or+'--subreport-titles' is always used as given, untranslated.+++File: hledger.info, Node: Amount arithmetic, Next: Transaction balancing, Prev: Languages, Up: Top++24 Amount arithmetic+********************++hledger uses decimal (Decimal) numbers for accounting arithmetic:+amounts, balances, costs, prices, valuation and gains. Floating point+(Double) numbers are used for inherently approximate statistics like+'stats' txns/s, 'prices --summary' coverage, 'roi' and 'holdings' rates+of return, and debug timings, where they are a better fit.++ Unlike the usual floating point numbers, which are binary and+fixed-size, and so frequently rounded, decimal numbers are base ten, so+amounts like 0.1 are stored exactly, and they can have up to 255 decimal+places (and any number of digits in the integer part). Addition,+subtraction and multiplication are exact (as long as the result needs no+more than 255 decimal places). Division can produce a non-terminating+decimal (like 1/3 = 0.333...); hledger rounds these to 255 decimal+places. The error is less than 10^-250, too small to affect transaction+balancing or reports at normal display precisions. When hledger shows+such a rounded amount in full, eg in 'print' output, it shows 8 decimal+places.++* Menu:++* Where hledger divides::+++File: hledger.info, Node: Where hledger divides, Up: Amount arithmetic++24.1 Where hledger divides+==========================++Non-terminating decimals can arise only where hledger divides. (Journal+amounts are written as finite decimals, and amount expressions round+their results, except in costs.) Here's when that happens:++When What is Visible effect+ divided+---------------------------------------------------------------------------+Dividing in an amount amount / None: the result is rounded to+expression ('$100.00 / number the entry's decimal places for+3') that commodity when the+ journal is read, so it is+ exactly what 'print' shows. A+ split that doesn't divide+ evenly makes the transaction+ unbalanced, unless one amount+ is left blank.+Dividing in a cost amount / None in calculations: the cost+expression ('@ 1 / 1.14 number, or is kept exact. 'print' shows+EUR') number / a repeating decimal with 8+ amount decimal places (more if+ written), so text copied from+ it is slightly rounded.+Converting a lot's total total cost None in calculations: gains+cost ('@@') or total cost / quantity use the unrounded unit cost.+basis ('{{ }}') to a unit Lot names and 'print' show it+cost with up to 8 decimal places+ (more if the cost commodity's+ display style has more), so+ text copied from them is+ slightly rounded; see Cost+ basis precision.+Inferring market prices total cost None+from costs, with / quantity+'--infer-market-prices'+Using a reverse market 1 / price None+price+Averaging lot costs, with total cost None+the AVERAGE cost basis / total+methods or in holdings quantity+Inferring costs from one amount None+equity conversion / the other+postings+Inferring a unit cost for total / None in calculations. 'print+several postings in one quantity -x' shows it with 8 decimal+commodity, in an implicit places (more if the+conversion commodities' decimal places+ add up to more), so text+ copied from it is slightly+ rounded.+Converting amounts amount / None in calculations: unit+written with a commodity alias costs are replaced by exact+alias that has a quantity quantity total costs, and balance+ assertions convert the alias+ amounts' total (so three '10+ min' amounts satisfy a '= 0.5+ h' assertion). 'print -x'+ shows converted amounts with+ all their decimal places (8+ for a repeating decimal).+Calculating averages (eg total / None: these are displayed+'-A') and percentages (eg count, part rounded+'-%') in reports / total+Converting times to hours time / hour Negligible: each is rounded at+in timeclock entries, and length the 255th decimal place, so eg+timedot durations written three '10m' timedot entries+in minutes or seconds total 0.50 hours, as+('10m') displayed. But that total+ isn't exactly 0.5, so a+ balance assertion of '0.5'+ hours on it would fail.+ Reports show durations with 2+ decimal places; 'print' shows+ a repeating decimal with 8+ ('0.16666667').+Calculating rates of various Rates are approximate+return: roi's IRR and (calculated with floating+TWR, and holdings' XIRR point numbers; IRR and XIRR by+column iteration)+++File: hledger.info, Node: Transaction balancing, Next: Amount formatting, Prev: Amount arithmetic, Up: Top++25 Transaction balancing+************************++A transaction's postings must add up to zero. When they are all in one+commodity, this is simple: the sum must be exactly zero. But when a+transaction converts between commodities using a cost, the cost is often+rounded (by you, or by your bank or broker), and requiring an exact zero+would reject many correct-looking entries. So, like Ledger and+Beancount, hledger allows a small tolerance.++* Menu:++* How balancing is checked::+* Where imbalances come from::+* Accumulated imbalances::+* Showing imbalances::+* Avoiding imbalances::+* Transaction balancing before 150::+++File: hledger.info, Node: How balancing is checked, Next: Where imbalances come from, Up: Transaction balancing++25.1 How balancing is checked+=============================++For each commodity in a journal entry, hledger:++ 1. adds up the posting amounts in that commodity, after converting any+ amounts that have a cost to the cost's commodity (exactly; see+ Amount arithmetic)+ 2. finds the entry's _balancing precision_ for that commodity: the+ most decimal places used by that commodity's amounts in the entry,+ not counting cost amounts+ 3. considers the entry balanced if the sum rounds to zero at that+ precision. In other words, the imbalance can be at most half a+ unit in the last decimal place: 0.005 for amounts with 2 decimal+ places, 0.5 for amounts with no decimal places.++ Eg:++2024-01-30 currency exchange+ assets:usd -19110.17 USD @ 0.869050 CHF+ assets:chf 16607.69 CHF++ The first posting converts to -16607.6932385 CHF, so the sum in CHF+is -0.0032385 CHF. The balancing precision for CHF is 2 (from 16607.69+CHF; the cost amount 0.869050 CHF doesn't count). -0.0032385 rounded to+2 decimal places is zero, so this entry is accepted.++ To make hledger check an entry more strictly, write its amounts with+more decimal places. Eg if the second amount above is written as+16607.690 CHF, the balancing precision becomes 3 and the entry is+rejected.+++File: hledger.info, Node: Where imbalances come from, Next: Accumulated imbalances, Prev: How balancing is checked, Up: Transaction balancing++25.2 Where imbalances come from+===============================++ * Rounded unit costs ('@'). The exact rate may have infinitely many+ decimal places (above, the exact rate is 16607.69 / 19110.17 =+ 0.86904983053...), or just more than your bank or broker shows you.+ This is the most common cause.++ * Total costs ('@@') that don't quite match the other amounts. Eg+ this entry is accepted, because the balancing precision for $ is 0+ (because $100 was written with no decimals):++ 2026-01-01+ assets:stock -3 AAPL @@ $100.40+ assets:cash $100+++File: hledger.info, Node: Accumulated imbalances, Next: Showing imbalances, Prev: Where imbalances come from, Up: Transaction balancing++25.3 Accumulated imbalances+===========================++Accepted imbalances are not corrected; they stay in the data, and add+up. So reports which convert amounts at cost, like 'balance -B' or+'balancesheetequity -B', may show a small non-zero total where you would+expect zero. Eg after three of the currency exchange entries above,+'hledger bal -B' shows a total of -0.01 CHF. Typically this is a few+cents, but each entry can contribute up to half a unit in its last+decimal place.++ (Without cost conversion, these imbalances aren't directly visible.+And with '--infer-equity', each commodity balances exactly, and the+imbalances become part of the conversion rates.)++ To see an accumulated imbalance more precisely, increase the display+precision with '-c'. Eg:++$ hledger bal -B -c 'CHF 1.000000000'++ And to see which entries contribute to it, use a register report:+'hledger reg -B -c 'CHF 1.000000000''. Or, show the imbalances+explicitly, as described next.+++File: hledger.info, Node: Showing imbalances, Next: Avoiding imbalances, Prev: Accumulated imbalances, Up: Transaction balancing++25.4 Showing imbalances+=======================++With the '--infer-imbalance' flag, hledger shows entry imbalances+explicitly, by generating postings to an imbalance account+('equity:imbalance' by default) which make the entry balance exactly (as+if you had added an amountless posting to that account). Eg:++$ hledger print --infer-imbalance+2024-01-30 currency exchange+ assets:usd -19110.17 USD @ 0.869050 CHF+ assets:chf 16607.69 CHF+ equity:imbalance 0.0032385 CHF++ This doesn't change which entries are accepted. But totals at cost+are now exactly zero, and the accumulated imbalance appears as the+balance of 'equity:imbalance'. Eg after three of the currency exchange+entries:++$ hledger bal -B --infer-imbalance+ 49823.07 CHF assets:chf+ -49823.08 CHF assets:usd+ 0.01 CHF equity:imbalance+--------------------+ 0++ The imbalance postings' amounts are usually smaller than the display+precision, so to see them individually, increase the display precision.+Eg:++$ hledger areg equity:imbalance --infer-imbalance -c 'CHF 1.0000000'+Transactions in equity:imbalance and subaccounts:+2024-01-30 currency exchange as:usd, as:chf CHF 0.0032385 CHF 0.0032385+2024-01-30 currency exchange as:usd, as:chf CHF 0.0032385 CHF 0.0064770+2024-01-30 currency exchange as:usd, as:chf CHF 0.0032385 CHF 0.0097155++ Some notes:++ * The imbalance postings have a hidden '_imbalance-posting' tag+ (shown by '--verbose-tags'), so they can also be matched with+ 'tag:imbalance-posting'.+ * To use a different account, declare it with the 'M'/'Imbalance'+ account type (the first one declared is used, if there are+ several). Imbalance accounts, including 'equity:imbalance', can be+ matched with 'type:M'.+ * With '--infer-equity' as well, the generated equity conversion+ postings use the exact cost amounts, so every commodity balances+ exactly.+ * No imbalance posting is generated if its amount would display as+ zero (at 8 decimal places, for a repeating decimal). This ignores+ the tiny leftovers of hledger's own division (see Amount+ arithmetic).+ * The imbalance account need not be declared, even in strict mode.+ * To list the entries with an imbalance, without generating postings,+ you can use 'hledger print not:change:0' (see change: query).+ (This also lists entries with unbalanced virtual postings;+ 'not:change:0 change:'<1'' would list only the small imbalances.)+ * If you use this flag with 'import', the imbalance postings will be+ added to your journal too.+++File: hledger.info, Node: Avoiding imbalances, Next: Transaction balancing before 150, Prev: Showing imbalances, Up: Transaction balancing++25.5 Avoiding imbalances+========================++You can avoid imbalances by writing exact entries. Any of these will+do:++ * Use a total cost ('@@') instead of a unit cost ('@') when the unit+ cost would be rounded. Total costs are converted exactly. Eg+ '-19110.17 USD @@ 16607.69 CHF'.+ * Write the unit cost with enough decimal places to be exact, when+ possible.+ * Add a posting to absorb the imbalance, eg to an 'expenses:rounding'+ account. If you leave its amount blank, hledger will calculate it+ exactly.+++File: hledger.info, Node: Transaction balancing before 150, Prev: Avoiding imbalances, Up: Transaction balancing++25.6 Transaction balancing before 1.50+======================================++hledger versions before 1.50 used the commodity's display precision as+the balancing precision, instead of the precision in the entry. This+masked larger imbalances, and made balancing depend on display settings+(see issue #2402). So some journal entries (or CSV rules) that worked+with hledger <1.50 are now rejected with an "unbalanced transaction"+error. If you hit this, you can:++ * restore the old behaviour, by adding '--txn-tolerance=display'+ (formerly '--txn-balancing=old') to the command or to your+ '~/.hledger.conf' file. This lets you keep using old journals+ unchanged.++ * or fix the problem entries (recommended), in one of these ways:++ 1. make cost amounts more precise (add more or better decimal+ digits)+ 2. or make non-cost amounts less precise (remove unnecessary+ decimal digits that are raising the precision)+ 3. or add a posting to absorb the imbalance, as described above.+++File: hledger.info, Node: Amount formatting, Next: Cost reporting, Prev: Transaction balancing, Up: Top++26 Amount formatting+********************++* Menu:++* Commodity display style::+* Commodity style override::+* Display rounding::+* Trailing decimal marks::+* Amount parseability::+++File: hledger.info, Node: Commodity display style, Next: Commodity style override, Up: Amount formatting++26.1 Commodity display style+============================++For the amounts in each commodity, hledger chooses a consistent display+style (symbol placement, decimal mark and digit group marks, number of+decimal digits) to use in most reports. This is inferred as follows:++ First, if there's a 'D' directive declaring a default commodity, that+commodity symbol and amount format is applied to all no-symbol amounts+in the journal.++ Then each commodity's display style is determined from its+'commodity' directive. We recommend always declaring commodities with+'commodity' directives, since they help ensure consistent display styles+and precisions, and bring other benefits such as error checking for+commodity symbols. Here's an example:++# Set display styles (and decimal marks, for parsing, if there is no decimal-mark directive)+# for the $, EUR, INR and no-symbol commodities:+commodity $1,000.00+commodity EUR 1.000,00+commodity INR 9,99,99,999.00+commodity 1 000 000.9455++ But for convenience, if a 'commodity' directive is not present,+hledger infers a commodity's display styles from its amounts as they are+written in the journal (excluding cost amounts and amounts in periodic+transaction rules or auto posting rules). It uses++ * the symbol placement and decimal mark of the first amount seen+ * the digit group marks of the first amount with digit group marks+ * and the maximum number of decimal digits seen across all amounts.++ And as fallback if no applicable amounts are found, it would use a+default style, like '$1000.00' (symbol on the left with no space, period+as decimal mark, and two decimal digits).++ Finally, commodity styles can be overridden by the+'-c/--commodity-style' command line option, described next.+++File: hledger.info, Node: Commodity style override, Next: Display rounding, Prev: Commodity display style, Up: Amount formatting++26.2 Commodity style override+=============================++The '-c/--commodity-style' option overrides a commodity's declared or+inferred display style, for the current command. Its argument is a+sample amount, as in the commodity directive. Eg, to show dollar+amounts with period digit group marks, comma decimal mark, and one+decimal digit:++$ hledger print -c '$1.000,0'++ Some things to note:++ * The option can be repeated, to set the display style of several+ commodities.+ * Omitting the commodity symbol sets the style of just the no-symbol+ commodity, not of all commodities.+ * For cost amounts, and amounts displayed by the 'print' command, it+ affects only the symbol placement and digit group/decimal marks;+ those amounts are always displayed with all of their decimal+ digits.+ * In some cases hledger will adjust number formatting to improve+ parseability, eg by adding trailing decimal marks when needed.+++File: hledger.info, Node: Display rounding, Next: Trailing decimal marks, Prev: Commodity style override, Up: Amount formatting++26.3 Display rounding+=====================++Amounts are stored internally as decimal numbers with up to 255 decimal+places (see Amount arithmetic). They are displayed with their original+journal precisions by print and print-like reports, and rounded to their+display precision (the number of decimal digits specified by the+commodity display style) by other reports. When rounding, hledger uses+banker's rounding (it rounds to the nearest even digit). So eg 0.5+displayed with zero decimal digits appears as "0".+++File: hledger.info, Node: Trailing decimal marks, Next: Amount parseability, Prev: Display rounding, Up: Amount formatting++26.4 Trailing decimal marks+===========================++If you're wondering why your 'print' report sometimes shows trailing+decimal marks, with no decimal digits; it does this when showing amounts+that have digit group marks but no decimal digits, to disambiguate them+and allow them to be re-parsed reliably (see Decimal marks). Eg:++commodity $1,000.00++2023-01-02+ (a) $1000++$ hledger print+2023-01-02+ (a) $1,000.++ You can avoid this by disabling digit group marks, eg temporarily+with -c/-commodity:++$ hledger print -c '$1000.00'+2023-01-02+ (a) $1000++ or by forcing print to show some decimal digits, with -round:++$ hledger print -c '$1,000.00' --round=soft+2023-01-02+ (a) $1,000.00+++File: hledger.info, Node: Amount parseability, Prev: Trailing decimal marks, Up: Amount formatting++26.5 Amount parseability+========================++More generally, hledger output falls into three rough categories, which+format amounts a little bit differently to suit different consumers:++ *1. "hledger-readable output" - should be readable by hledger (and+by humans)*++ * This is produced by reports that show full journal entries:+ 'print', 'import', 'close', 'rewrite' etc.+ * It shows amounts with their original journal precisions, which may+ not be consistent from one amount to the next.+ * It adds a trailing decimal mark when needed to avoid showing+ ambiguous amounts.+ * It can be parsed reliably (by hledger and ledger2beancount at+ least, but perhaps not by Ledger..)++ *2. "human-readable output" - usually for humans*++ * This is produced by all other reports.+ * It shows amounts with standard display precisions, which will be+ consistent within each commodity.+ * It shows ambiguous amounts unmodified.+ * It can be parsed reliably in the context of a known report (when+ you know decimals are consistently not being shown, you can assume+ a single mark is a digit group mark).++ *3. "machine-readable output" - usually for other software*++ * This is produced by all reports when an output format like 'csv',+ 'tsv', 'json', or 'sql' is selected.+ * It shows amounts as 1 or 2 do, but without digit group marks.+ * It can be parsed reliably (if needed, the decimal mark can be+ changed with -c/-commodity-style).+++File: hledger.info, Node: Cost reporting, Next: Value reporting, Prev: Amount formatting, Up: Top++27 Cost reporting+*****************++In some transactions - for example a currency conversion, or a purchase+or sale of stock - one commodity is exchanged for another. In these+transactions there is a conversion rate, also called the cost (when+buying) or selling price (when selling). (In hledger docs we just say+"cost" generically for convenience.) With the '-B/--cost' flag, hledger+can show amounts "at cost", converted to the cost's commodity.++* Menu:++* Recording costs::+* Reporting at cost::+* Equity conversion postings::+* Inferring equity conversion postings::+* Combining costs and equity conversion postings::+* Requirements for detecting equity conversion postings::+++File: hledger.info, Node: Recording costs, Next: Reporting at cost, Up: Cost reporting++27.1 Recording costs+====================++We'll explore several ways of recording transactions involving costs.+These are also compared at Currency conversion > Four ways to record a+conversion, compared.++ Costs can be recorded explicitly in the journal, using the '@+UNITCOST' or '@@ TOTALCOST' notation described in Journal > Costs:++ *Variant 1*++2022-01-01+ assets:dollars $-135+ assets:euros €100 @ $1.35 ; $1.35 per euro (unit cost)++ *Variant 2*++2022-01-01+ assets:dollars $-135+ assets:euros €100 @@ $135 ; $135 total cost++ Typically, writing the unit cost (variant 1) is preferable; it can be+more effort, requiring more attention to decimal digits; but it reveals+the per-unit cost basis, and makes stock sales easier.++ Costs can also be left implicit, and hledger will infer the cost that+is consistent with a balanced transaction:++ *Variant 3*++2022-01-01+ assets:dollars $-135+ assets:euros €100++ Here, hledger will attach a '@@ €100' cost to the first amount (you+can see it with 'hledger print -x'). This form looks convenient, but+there are downsides:++ * It sacrifices some error checking. For example, if you+ accidentally wrote €10 instead of €100, hledger would not be able+ to detect the mistake.++ * It is sensitive to the order of postings - if they were reversed, a+ different entry would be inferred and reports would be different.++ * The per-unit cost basis is not easy to read.++ So generally this kind of entry is not recommended. You can make+sure you have none of these by using '-s' (strict mode), or by running+'hledger check balanced'.+++File: hledger.info, Node: Reporting at cost, Next: Equity conversion postings, Prev: Recording costs, Up: Cost reporting++27.2 Reporting at cost+======================++Now when you add the '-B'/'--cost' flag to reports ("B" is from Ledger's+-B/-basis/-cost flag), any amounts which have been annotated with costs+will be converted to their cost's commodity (in the report output). Ie+they will be displayed "at cost" or "at sale price".++ For lot postings, which carry a cost basis, '-B' converts to the cost+basis instead: a disposal shows what the disposed units cost, not what+they sold for, consistent with how such entries balance, so eg a lot+account's cost balance is the cost of the units still held (and zero+once they are all sold), and 'bse -B' balances. To see transacted+amounts (proceeds) instead, use '--value=transacted'.++ Some things to note:++ * Costs are attached to specific posting amounts in specific+ transactions, and once recorded they do not change. This contrasts+ with market prices, which are ambient and fluctuating.++ * Conversion to cost is performed before conversion to market value+ (described below).++ * A total at cost can be slightly off zero where you might expect+ zero (eg a few cents in 'bse -B'), because hledger accepts entries+ whose costs were rounded; see Accumulated imbalances.+++File: hledger.info, Node: Equity conversion postings, Next: Inferring equity conversion postings, Prev: Reporting at cost, Up: Cost reporting++27.3 Equity conversion postings+===============================++There is a problem with the entries above - they are not conventional+Double Entry Bookkeeping (DEB) notation, and because of the "magical"+transformation of one commodity into another, they cause an imbalance in+the Accounting Equation. This shows up as a non-zero grand total in+balance reports like 'hledger bse'.++ Most hledger users use cost notation and don't use equity postings;+for them this imbalance doesn't matter in practice and can safely be+ignored. But if you'd like to learn more, keep reading.++ Conventional DEB uses an extra pair of equity postings to balance the+transaction. Of course you can do this in hledger as well:++ *Variant 4*++2022-01-01+ assets:dollars $-135+ assets:euros €100+ equity:conversion $135+ equity:conversion €-100++ Now the transaction is perfectly balanced according to standard DEB,+and 'hledger bse''s total will not be disrupted. It also translates+easily to any other double entry accounting system.++ And, hledger can still infer the cost for cost reporting, but it's+not done by default - you must add the '--infer-costs' flag like so:++$ hledger print --infer-costs+2022-01-01 one hundred euros purchased at $1.35 each+ assets:dollars $-135 @@ €100+ assets:euros €100+ equity:conversion $135+ equity:conversion €-100++$ hledger bal --infer-costs -B+ €-100 assets:dollars + €100 assets:euros +-------------------- + 0 ++ Here are some downsides of this kind of entry:++ * The per-unit cost basis is not easy to read.++ * Instead of '-B' you must remember to type '-B --infer-costs'.++ * '--infer-costs' works only where hledger can identify the two+ equity:conversion postings and match them up with the two+ non-equity postings. So writing the journal entry in a particular+ format becomes more important. More on this below.+++File: hledger.info, Node: Inferring equity conversion postings, Next: Combining costs and equity conversion postings, Prev: Equity conversion postings, Up: Cost reporting++27.4 Inferring equity conversion postings+=========================================++Can we go in the other direction ? Yes, if you have transactions+written with the @/@@ cost notation, hledger can infer the missing+equity postings, if you add the '--infer-equity' flag. Eg:++2022-01-01+ assets:dollars -$135+ assets:euros €100 @ $1.35++$ hledger print --infer-equity+2022-01-01+ assets:dollars $-135+ assets:euros €100 @ $1.35+ equity:conversion:$-€:€ €-100+ equity:conversion:$-€:$ $135.00++ The equity account names will be "equity:conversion:A-B:A" and+"equity:conversion:A-B:B" where A is the alphabetically first commodity+symbol. You can customise the "equity:conversion" part by declaring an+account with the 'V'/'Conversion' account type (the first-declared one,+if there are several; or if none is declared, the alphabetically first+account whose type is inferred as V, such as 'equity:trading', is used).++ For a lot disposal, the conversion postings record the units sold at+their cost basis, not at the sale price, so that the entry (and your+balance sheet) still sums to zero; the difference between the two is the+gain posting. Eg:++commodity AAPL ; lots:++2026-01-02 buy+ assets:stock 10 AAPL @@ $1000+ assets:cash++2026-01-03 sell+ assets:stock -4 AAPL @@ $600+ assets:cash $600++$ hledger print --infer-equity desc:sell+2026-01-03 sell+ assets:stock -4 AAPL {2026-01-02, $100} @@ $600+ equity:conversion:$-AAPL:AAPL 4 AAPL+ equity:conversion:$-AAPL:$ $-400+ assets:cash $600+ revenues:gain $-200++ If you write such an entry yourself, write the conversion postings at+cost basis like this, and keep the transacted cost ('@'/'@@') on the+disposal posting, since the gain is calculated from it.++ The generated equity conversion accounts need not be declared, even+in strict mode. (And unlike normal postings, generated equity postings+do not inherit tags from account declarations.)+++File: hledger.info, Node: Combining costs and equity conversion postings, Next: Requirements for detecting equity conversion postings, Prev: Inferring equity conversion postings, Up: Cost reporting++27.5 Combining costs and equity conversion postings+===================================================++Finally, you can use both the @/@@ cost notation and equity postings at+the same time. This in theory gives the best of all worlds - preserving+the accounting equation, revealing the per-unit cost basis, and+providing more flexibility in how you write the entry:++ *Variant 5*++2022-01-01 one hundred euros purchased at $1.35 each+ assets:dollars $-135+ equity:conversion $135+ equity:conversion €-100+ assets:euros €100 @ $1.35++ All the other variants above can (usually) be rewritten to this final+form with:++$ hledger print -x --infer-costs --infer-equity++ Or you can enable both flags always, eg in your config file, and your+reports will have the advantages of both.++ Downsides:++ * The precise format of the journal entry becomes more important. If+ hledger can't detect and match up the cost and equity postings, it+ will give a transaction balancing error.++ * The add command does not yet accept this kind of entry (#2056).++ * This is the most verbose form.+++File: hledger.info, Node: Requirements for detecting equity conversion postings, Prev: Combining costs and equity conversion postings, Up: Cost reporting++27.6 Requirements for detecting equity conversion postings+==========================================================++'--infer-costs' has certain requirements (unlike '--infer-equity', which+always works). It will infer costs only in transactions with:++ * Two non-equity postings, in different commodities. If one of them+ is lotful, the cost will be added to that one; otherwise it will be+ added to the first (top) one.++ * Two postings to equity conversion accounts, next to one another,+ which balance the two non-equity postings. This balancing is+ checked to the same precision (number of decimal places) used in+ the conversion posting's amount. Equity conversion accounts are:++ * any accounts declared with account type 'V'/'Conversion', or+ their subaccounts+ * otherwise, accounts named 'equity:conversion', 'equity:trade',+ or 'equity:trading', or their subaccounts.++ And multiple such four-posting groups can coexist within a single+transaction. When '--infer-costs' fails, it does not infer a cost in+that transaction, and does not raise an error (ie, it infers costs where+it can).++ Reading variant 5 journal entries, combining cost notation and equity+postings, has all the same requirements. When reading such an entry+fails, hledger raises an "unbalanced transaction" error. For a lot+disposal, the conversion postings may balance the disposal's cost basis+instead of its transacted cost, as described above.+++File: hledger.info, Node: Value reporting, Next: Lots and capital gains, Prev: Cost reporting, Up: Top++28 Value reporting+******************++hledger can also show amounts "at market value", converted to some other+commodity using the market price or conversion rate on a certain date.++ This is controlled by the '--value=TYPE[,COMMODITY]' option. We also+provide simpler '-V' and '-X COMMODITY' aliases for this, which are+often sufficient. The market prices are declared with a special 'P'+directive, and/or they can be inferred from the costs recorded in+transactions, by using the '--infer-market-prices' flag.++* Menu:++* -X Value in specified commodity::+* -V Value in default commoditys::+* Valuation date::+* Finding market price::+* --infer-market-prices market prices from transactions::+* Valuation commodity::+* --value Flexible valuation::+* Valuation examples::+* Interaction of valuation and queries::+* Effect of valuation on reports::+++File: hledger.info, Node: -X Value in specified commodity, Next: -V Value in default commoditys, Up: Value reporting++28.1 -X: Value in specified commodity+=====================================++The '-X COMM' (or '--exchange=COMM') option converts amounts to their+market value in the specified commodity, using the market prices in+effect on the _valuation date(s)_, if any. (More on these in a minute.)++ Use this when you want to (eg) show everything in your base currency+as far as possible. (Commodities for which no conversion rate can be+found, will not be converted.)++ COMM should be the commodity symbol exactly as written in the+journal's amounts or market prices (eg '$', not 'USD', if the journal+uses '$'); ISO currency codes are not matched to symbols. If no+conversion price to COMM can be found, a warning is printed, suggesting+an equivalent journal commodity if one exists. Remember to quote+special shell characters, if needed. Some examples:++ * '-X€'+ * '-X$' (nothing after $, no quoting needed)+ * '-X CNY' (the space after -X is optional)+ * '-X 'red apples''+ * '-X 'r&r''+++File: hledger.info, Node: -V Value in default commoditys, Next: Valuation date, Prev: -X Value in specified commodity, Up: Value reporting++28.2 -V: Value in default commodity(s)+======================================++The '-V/--market' flag is a variant of '-X' where you don't have to+specify COMM. Instead it tries to guess a _default valuation commodity_+for each original commodity, based on the market prices in effect on the+valuation date(s).++ '-V' can often be a convenient shortcut for '-X MYCURRENCY', but not+always; depending on your data it could guess multiple valuation+commodities. Usually you want to convert to a single commodity, so it's+better to use '-X', unless you're sure '-V' is doing what you want.+++File: hledger.info, Node: Valuation date, Next: Finding market price, Prev: -V Value in default commoditys, Up: Value reporting++28.3 Valuation date+===================++Market prices can change from day to day. hledger will use the prices+on a particular valuation date (or on more than one date). By default+hledger uses "end" dates for valuation. More specifically:++ * For single period reports (including normal print and register+ reports):+ * If an explicit report end date is specified, that is used.+ * Otherwise the latest transaction date or non-future P+ directive date is used.++ * For multiperiod reports, each period is valued on its last day.++ This can be customised with the -value option described below, which+can select either "then", "end", "now", or "custom" dates.+++File: hledger.info, Node: Finding market price, Next: --infer-market-prices market prices from transactions, Prev: Valuation date, Up: Value reporting++28.4 Finding market price+=========================++To convert a commodity A to its market value in another commodity B,+hledger looks for a suitable market price (exchange rate) as follows, in+this order of preference:++ 1. A _declared market price_ or _inferred market price_: A's latest+ market price in B on or before the valuation date as declared by a+ P directive, or (with the '--infer-market-prices' flag) inferred+ from costs.++ 2. A _reverse market price_: the inverse of a declared or inferred+ market price from B to A.++ 3. A _forward chain of market prices_: a synthetic price formed by+ combining the shortest chain of "forward" (only 1 above) market+ prices, leading from A to B.++ 4. _Any chain of market prices_: a chain of any market prices,+ including both forward and reverse prices (1 and 2 above), leading+ from A to B.++ 5. _Commodity alias rates_: if none of the above is found, the same+ search is repeated, also using commodity aliases as fixed exchange+ rates (between a commodity and its alias, when there are no market+ prices between them). This lets you value amounts in an alias+ declared by another file, or show amounts in an alias with '-X',+ but aliases never change a conversion that market prices can+ provide. To see these rates and where their aliases were declared,+ use 'prices --show-aliases --locations'; '--debug=2' output shows+ when they are tried.++ There is a limit to the length of these price chains; if hledger+reaches that length without finding a complete chain or exhausting all+possibilities, it will give up (with a "gave up" message visible in+'--debug=2' output). That limit is currently 1000.++ Amounts for which no suitable market price can be found, are not+converted.++ Commodity alias rates are used only for converting, never as a+default valuation commodity for '-V'.+++File: hledger.info, Node: --infer-market-prices market prices from transactions, Next: Valuation commodity, Prev: Finding market price, Up: Value reporting++28.5 -infer-market-prices: market prices from transactions+==========================================================++Normally, market value in hledger is fully controlled by, and requires,+P directives in your journal. Since adding and updating those can be a+chore, and since transactions usually take place at close to market+value, why not use the recorded costs as additional market prices (as+Ledger does) ? Adding the '--infer-market-prices' flag to '-V', '-X' or+'--value' enables this.++ So for example, 'hledger bs -V --infer-market-prices' will get market+prices both from P directives and from transactions. If both occur on+the same day, the P directive takes precedence.++ There is a downside: value reports can sometimes be affected in+confusing/undesired ways by your journal entries. If this happens to+you, read all of this Value reporting section carefully, and try adding+'--debug' or '--debug=2' to troubleshoot.++ '--infer-market-prices' can infer market prices from:++ * multicommodity transactions with explicit prices ('@'/'@@')++ * multicommodity transactions with implicit prices (no '@', two+ commodities, unbalanced). (With these, the order of postings+ matters. 'hledger print -x' can be useful for troubleshooting.)++ * multicommodity transactions with equity postings, if cost is+ inferred with '--infer-costs'.++ There is a limitation (bug) currently: when a valuation commodity is+not specified, prices inferred with '--infer-market-prices' do not help+select a default valuation commodity, as 'P' prices would. So+conversion might not happen because no valuation commodity was detected+('--debug=2' will show this). To be safe, specify the valuation+commmodity, eg:++ * '-X EUR --infer-market-prices', not '-V --infer-market-prices'+ * '--value=then,EUR --infer-market-prices', not '--value=then+ --infer-market-prices'++ Signed costs and market prices can be confusing. For reference, here+is the current behaviour. (If you think it should work differently, see+#1870.)++2022-01-01 Positive Unit prices+ a A 1+ b B -1 @ A 1++2022-01-01 Positive Total prices+ a A 1+ b B -1 @@ A 1+++2022-01-02 Negative unit prices+ a A 1+ b B 1 @ A -1++2022-01-02 Negative total prices+ a A 1+ b B 1 @@ A -1+++2022-01-03 Double Negative unit prices+ a A -1+ b B -1 @ A -1++2022-01-03 Double Negative total prices+ a A -1+ b B -1 @@ A -1++ All of the transactions above are considered balanced (and on each+day, the two transactions are considered equivalent). Here are the+market prices inferred for B:++$ hledger -f- --infer-market-prices prices+P 2022-01-01 B A 1+P 2022-01-01 B A 1.0+P 2022-01-02 B A -1+P 2022-01-02 B A -1.0+P 2022-01-03 B A -1+P 2022-01-03 B A -1.0+++File: hledger.info, Node: Valuation commodity, Next: --value Flexible valuation, Prev: --infer-market-prices market prices from transactions, Up: Value reporting++28.6 Valuation commodity+========================++*When you specify a valuation commodity ('-X COMM' or '--value+TYPE,COMM'):*+hledger will convert all amounts to COMM, wherever it can find a+suitable market price (including by reversing or chaining prices).++ *When you leave the valuation commodity unspecified ('-V' or '--value+TYPE'):*+For each commodity A, hledger picks a default valuation commodity as+follows, in this order of preference:++ 1. The price commodity from the latest P-declared market price for A+ on or before valuation date.++ 2. The price commodity from the latest P-declared market price for A+ on any date. (Allows conversion to proceed when there are inferred+ prices before the valuation date.)++ 3. If there are no P directives at all (any commodity or date) and the+ '--infer-market-prices' flag is used: the price commodity from the+ latest transaction-inferred price for A on or before valuation+ date.++ This means:++ * If you have P directives, they determine which commodities '-V'+ will convert, and to what.++ * If you have no P directives, and use the '--infer-market-prices'+ flag, costs determine it.++ Amounts for which no valuation commodity can be found are not+converted.+++File: hledger.info, Node: --value Flexible valuation, Next: Valuation examples, Prev: Valuation commodity, Up: Value reporting++28.7 -value: Flexible valuation+===============================++'-V' and '-X' are special cases of the more general '--value' option:++ --value=TYPE[,COMM] TYPE is then, end, now, YYYY-MM-DD, cost or transacted.+ COMM is an optional commodity symbol.+ Shows amounts converted to:+ - default valuation commodity (or COMM) using market prices at posting dates+ - default valuation commodity (or COMM) using market prices at period end(s)+ - default valuation commodity (or COMM) using current market prices+ - default valuation commodity (or COMM) using market prices at some date+ - cost basis, or else transacted cost (like -B)+ - transacted cost only++ The TYPE part selects cost or value and valuation date:++'--value=then'++ Convert amounts to their value in the default valuation commodity,+ using market prices on each posting's date.+'--value=end'++ Convert amounts to their value in the default valuation commodity,+ using market prices on the last day of the report period (or if+ unspecified, the journal's end date); or in multiperiod reports,+ market prices on the last day of each subperiod.+'--value=now'++ Convert amounts to their value in the default valuation commodity+ using current market prices (as of when report is generated).+'--value=YYYY-MM-DD'++ Convert amounts to their value in the default valuation commodity+ using market prices on this date.+'--value=cost'++ Convert amounts to their cost basis where they have one (lot+ postings), otherwise to their transacted cost. Same as+ '-B'/'--cost'; see Reporting at cost.+'--value=transacted'++ Convert amounts to their transacted cost or sale amount ('@'/'@@'),+ ignoring any cost basis. This is '-B''s behaviour for non-lot+ postings, and shows proceeds rather than cost for lot disposals.++ To select a different valuation commodity, add the optional ',COMM'+part: a comma, then the target commodity's symbol. Eg:+*'--value=now,EUR'*. hledger will do its best to convert amounts to+this commodity, deducing market prices as described above.++ The symbol may be written in double quotes, as in a journal. To+select the no-symbol commodity, write it as '""', or leave the symbol+empty: *'--value=now,'""''*, *'--value=now,'*, *'-X '""''* and *'-X '''*+all work.+++File: hledger.info, Node: Valuation examples, Next: Interaction of valuation and queries, Prev: --value Flexible valuation, Up: Value reporting++28.8 Valuation examples+=======================++Here are some quick examples of '-V':++; one euro is worth this many dollars from nov 1+P 2016/11/01 € $1.10++; purchase some euros on nov 3+2016/11/3+ assets:euros €100+ assets:checking++; the euro is worth fewer dollars by dec 21+P 2016/12/21 € $1.03++ How many euros do I have ?++$ hledger -f t.j bal -N euros+ €100 assets:euros++ What are they worth at end of nov 3 ?++$ hledger -f t.j bal -N euros -V -e 2016/11/4+ $110.00 assets:euros++ What are they worth after 2016/12/21 ? (no report end date+specified, defaults to today)++$ hledger -f t.j bal -N euros -V+ $103.00 assets:euros++ Here are some examples showing the effect of '--value', as seen with+'print':++P 2000-01-01 A 1 B+P 2000-02-01 A 2 B+P 2000-03-01 A 3 B+P 2000-04-01 A 4 B++2000-01-01+ (a) 1 A @ 5 B++2000-02-01+ (a) 1 A @ 6 B++2000-03-01+ (a) 1 A @ 7 B++ Show the cost of each posting:++$ hledger -f- print --cost+2000-01-01+ (a) 5 B++2000-02-01+ (a) 6 B++2000-03-01+ (a) 7 B++ Show the value as of the last day of the report period (2000-02-29):++$ hledger -f- print --value=end date:2000/01-2000/03+2000-01-01+ (a) 2 B++2000-02-01+ (a) 2 B++ With no report period specified, the latest transaction date or price+date is used as valuation date (2000-04-01):++$ hledger -f- print --value=end+2000-01-01+ (a) 3 B++2000-02-01+ (a) 3 B++2000-03-01+ (a) 3 B++ The value today is the same (the 2000-04-01 price is still in+effect):++$ hledger -f- print --value=now+2000-01-01+ (a) 4 B++2000-02-01+ (a) 4 B++2000-03-01+ (a) 4 B++ Show the value on 2000/01/15:++$ hledger -f- print --value=2000-01-15+2000-01-01+ (a) 1 B++2000-02-01+ (a) 1 B++2000-03-01+ (a) 1 B+++File: hledger.info, Node: Interaction of valuation and queries, Next: Effect of valuation on reports, Prev: Valuation examples, Up: Value reporting++28.9 Interaction of valuation and queries+=========================================++When matching postings based on queries in the presence of valuation,+the following happens:++ 1. The query is separated into two parts:+ 1. the currency ('cur:') or amount ('amt:').+ 2. all other parts.++ 2. The postings are matched to the currency and amount queries based+ on pre-valued amounts.+ 3. Valuation is applied to the postings.+ 4. The postings are matched to the other parts of the query based on+ post-valued amounts.++ Related: #1625+++File: hledger.info, Node: Effect of valuation on reports, Prev: Interaction of valuation and queries, Up: Value reporting++28.10 Effect of valuation on reports+====================================++Here is a reference for how valuation is supposed to affect each part of+hledger's reports. It may be useful when troubleshooting. Related:+#329, #1083.++ First, a quick glossary:++_cost_++ calculated using price(s) recorded in the transaction(s).+_value_++ market value using available market price declarations, or the+ unchanged amount if no conversion rate can be found.+_report start_++ the first day of the report period specified with -b or -p or+ date:, otherwise today.+_report or journal start_++ the first day of the report period specified with -b or -p or+ date:, otherwise the earliest transaction date in the journal,+ otherwise today.+_report end_++ the last day of the report period specified with -e or -p or date:,+ otherwise today.+_report or journal end_++ the last day of the report period specified with -e or -p or date:,+ otherwise the latest transaction date in the journal, otherwise+ today.+_report interval_++ a flag (-D/-W/-M/-Q/-Y) or period expression that activates the+ report's multi-period mode (whether showing one or many+ subperiods).++Report '-B', '-V', '-X' '--value=then' '--value=end''--value=DATE',+type '--cost' '--value=now'+------------------------------------------------------------------------------+*print*+posting cost value at value at posting value at value+amounts report end date report or at+ or today journal DATE/today+ end+balance unchanged unchanged unchanged unchanged unchanged+assertions/assignments+*register*+starting cost value at valued at day value at value+balance report or each historical report or at+(-H) journal posting was made journal DATE/today+ end end+starting cost value at valued at day value at value+balance day before each historical day before at+(-H) report or posting was made report or DATE/today+with journal journal+report start start+interval+posting cost value at value at posting value at value+amounts report or date report or at+ journal journal DATE/today+ end end+summary summarised value at sum of postings value at value+posting cost period in interval, period at+amounts ends valued at ends DATE/today+with interval start+report+interval+running sum/average sum/average sum/average of sum/average sum/average+total/averageof of displayed values of of+ displayed displayed displayed displayed+ values values values values+*balance+(bs,+bse, cf,+is)*+balance sums of value at value at posting value at value+changes costs report end date report or at+ or today journal DATE/today+ of sums of end of of+ postings sums of sums+ postings of+ postings+budget like like like balance like like+amounts balance balance changes balances balance+(-budget) changes changes changes+grand sum of sum of sum of displayed sum of sum of+total displayed displayed valued displayed displayed+ values values values values+*balance+(bs,+bse, cf,+is) with+report+interval*+starting sums of value at sums of values value at sums+balances costs of report of postings report of+(-H) postings start of before report start of postings+ before sums of start at sums of before+ report all respective all report+ start postings posting dates postings start+ before before+ report report+ start start+balance sums of same as sums of values balance value+changes costs of -value=end of postings in change in at+(bal, postings period at each DATE/today+is, bs in period respective period, of+-change, posting dates valued at sums+cf period of+-change) ends postings+end sums of same as sums of values period end value+balances costs of -value=end of postings from balances, at+(bal -H, postings before period valued at DATE/today+is -H, from start to period period of+bs, cf) before end at ends sums+ report respective of+ start to posting dates postings+ period end+budget like like like balance like like+amounts balance balance changes/end balances balance+(-budget) changes/end changes/end balances changes/end+ balances balances balances+row sums, sums, sums, averages sums, sums,+totals, averages averages of displayed averages averages+row of of values of of+averages displayed displayed displayed displayed+(-T, -A) values values values values+column sums of sums of sums of sums of sums+totals displayed displayed displayed values displayed of+ values values values displayed+ values+grand sum, sum, sum, average of sum, sum,+total, average of average of column totals average of average+grand column column column of+average totals totals totals column+ totals++ '--cumulative' is omitted to save space, it works like '-H' but with+a zero starting balance.+++File: hledger.info, Node: Lots and capital gains, Next: Generating data, Prev: Value reporting, Up: Top++29 Lots and capital gains+*************************++When you buy (acquire) some amount of an investment commodity (a lot),+it can be important (depending on your local tax rules) to keep track of+its original cost and acquisition date (cost basis), so that when you+sell (dispose) it, you can calculate capital gains (or losses), and+document how you satisfied the rules about disposal order, short term vs+long term gains, and so on.++ For many kinds of investment, each individual lot has its own cost+basis, which must be tracked even if the lot is reduced, split up, or+transferred. Also lots may need to be moved and disposed of in a+prescribed order. All this can be very hard to keep track of by hand,+so usually it is done by an investment broker, cryptocurrency exchange,+or specialised tax software. Now, you can also do it yourself with+hledger.++ Automated lot tracking and capital gains reporting is the biggest new+feature of hledger 2. Lot tracking was first shipped in Ledger, then+improved in Beancount; hledger 2 evolves PTA lot tracking further,+making it more powerful and ergonomic. You can record lot details+explicitly, or let hledger infer them. hledger checks lot entries;+tracks, infers and validates lot movements; and calculates capital gains+when lots are sold.++ Note hledger 2's lot processing happens only for entries that use lot+notation, or where lots are inferred. If you have hledger 1 journal+files that you want to migrate, or use with both hledger 1 and hledger+2, see hledger 1 and hledger 2.++ For practical advice on turning on lot tracking in an existing+journal, see Start tracking lots. For a more technical version of+what's in this manual, see SPEC-lots.++* Menu:++* First lots example::+* Writing lot entries::+* Lot movements::+* Cost basis methods::+* Gains::+* Lot reports::+* Lot details::+* Troubleshooting lots::+++File: hledger.info, Node: First lots example, Next: Writing lot entries, Up: Lots and capital gains++29.1 First lots example+=======================++hledger's lot tracking does not require much extra work. Here is a+small example, using just the familiar @ syntax, and new 'lots' tag.+(Several ways to write lot entries below shows the other notations.):++commodity AAPL ; lots:++2026-01-15 buy+ assets:cash -$500+ assets:stocks 10 AAPL @ $50++2026-02-01 sell some+ assets:stocks -5 AAPL @ $70+ assets:cash $350++ Lot tracking is activated for AAPL by the 'lots' tag, so hledger will++ * keep track of each lot that's acquired (and optionally show them in+ reports)+ * dispose of lots in the right order (FIFO by default)+ * calculate the resulting capital gain, and add the gain posting if+ missing+ * check for many kinds of error (such as selling more than you have).++ 'print' shows the inferred cost basis annotations and gain posting+(so its output can be re-read even without the 'commodity' directive, if+the default cost basis method is used):++$ hledger print+2026-01-15 buy+ assets:cash $-500+ assets:stocks 10 AAPL {$50} @ $50++2026-02-01 sell some+ assets:stocks -5 AAPL {2026-01-15, $50} @ $70+ assets:cash $350+ revenues:gain $-100++ 'print''s '-a' flag (short for '--all') shows maximum detail,+including the lots as subaccounts and tags showing how the entry was+analysed:++$ hledger print -a+2026-01-15 buy+ assets:cash $-500+ assets:stocks:{2026-01-15, $50} 10 AAPL {$50} @ $50 ; ptype: acquire++2026-02-01 sell some+ assets:stocks:{2026-01-15, $50} -5 AAPL {2026-01-15, $50} @ $70 ; ptype: dispose+ assets:cash $350+ revenues:gain $-100 ; ptype: gain, generated-posting:++ If anything looks wrong, see Troubleshooting lots below.++ Once you have lot entries, 'holdings' will show an overview of your+investments - units held, per-unit and total cost and value, realised+and unrealised gain, and XIRR (extended internal rate of return). To+see all of these, add at least one market price declaration, eg:++P 2026-03-31 AAPL $72++ Then:++$ hledger holdings -e 2026-04-01+Holdings on 2026-03-31++ || Date Age Units Avg cost Unit price Total cost Total value Weight UGain UGain% RGain XIRR +===============++===============================================================================================================+ assets:stocks || 2026-01-15 75d 5 AAPL $50 $72 $250 $360 100.0% $110 44.0% $100 1865.3% +---------------++---------------------------------------------------------------------------------------------------------------+ || 5 AAPL $50 $250 $360 100.0% $110 44.0% $100 1865.3% ++ You can add '--lots' to see the individual lots (this works with all+reports):++$ hledger holdings -e 2026-04-01 --lots+Holdings on 2026-03-31++ || Date Age Units Unit cost Unit price Total cost Total value Weight UGain UGain% RGain XIRR +=================================++================================================================================================================+ assets:stocks:{2026-01-15, $50} || 2026-01-15 75d 5 AAPL $50 $72 $250 $360 100.0% $110 44.0% $100 1865.3% +---------------------------------++----------------------------------------------------------------------------------------------------------------+ || 5 AAPL $50 $250 $360 100.0% $110 44.0% $100 1865.3% +++File: hledger.info, Node: Writing lot entries, Next: Lot movements, Prev: First lots example, Up: Lots and capital gains++29.2 Writing lot entries+========================++Lot tracking can be enabled in two ways:++ * _Per posting:_ write explicit cost basis annotations like in Ledger+ or Beancount, or explicit lot subaccount names. These postings+ will be tracked lotfully.++ * _Per commodity:_ declare the commodity lotful with a 'lots' tag.+ All of its postings are tracked lotfully, and the annotations are+ inferred for you. This is convenient, and recommended.++ A posting with any of these is called a lot posting.++* Menu:++* Cost basis annotations::+* Lotful commodities::+* Lot subaccounts::+* Several ways to write lot entries::+* Disabling lot tracking::+++File: hledger.info, Node: Cost basis annotations, Next: Lotful commodities, Up: Writing lot entries++29.2.1 Cost basis annotations+-----------------------------++Each acquisition of an investment creates a _lot_, with a _cost basis_.+In hledger, a lot's cost basis has 2-3 parts:++ 1. The nominal acquisition date (required). Usually this is the date+ you acquired the lot.+ 2. A short text label (optional). This can be used to distinguish+ lots acquired on the same date.+ 3. The nominal acquisition cost (required). Usually this is what you+ paid for it.++ In the journal, we can write _cost basis annotations_, enclosed in {}+after an amount (the syntax is described in Cost basis), above. These+often mention only part of the cost basis, typically just the cost+('{$50}'), or nothing at all ('{}'); hledger infers the rest.++ On an acquisition, the annotation records the new lot's cost basis.+On a disposal or transfer, it is instead a _lot selector_, choosing+which existing lot(s) to take from: a full or partial cost basis, like+'{2026-01-15, $50}' or '{2026-01-15}', identifies one specific lot,+while '{}' (or no annotation) lets hledger choose, using the cost basis+method.+++File: hledger.info, Node: Lotful commodities, Next: Lot subaccounts, Prev: Cost basis annotations, Up: Writing lot entries++29.2.2 Lotful commodities+-------------------------++A more convenient way to record lot transactions, is to declare+commodities as _lotful_, by adding a 'lots' tag in their declaration.+Eg:++commodity AAPL ; lots:++ This tells hledger that postings involving these commodities always+involve lots, so it will infer cost basis annotations automatically, and+you won't need to write them in the journal.++ The 'lots' tag can also have a value, selecting the disposal order+(see Cost basis methods); and on account declarations it disables or+customises lot tracking per account, as described in Disabling lot+tracking below.+++File: hledger.info, Node: Lot subaccounts, Next: Several ways to write lot entries, Prev: Lotful commodities, Up: Writing lot entries++29.2.3 Lot subaccounts+----------------------++Internally, hledger tracks each lot in a subaccount, named like the cost+basis. You don't need to write these subaccounts in the journal;+hledger infers them automatically. They are hidden from reports by+default, since there can be many lots. To show them, add the '--lots'+flag to any report (the holdings command is designed for viewing them).++ If you do write a lot subaccount in the journal, it is equivalent to+writing a cost basis annotation on the amount:++2026-01-15 buy+ assets:stocks:{2026-01-15, $50} 10 AAPL+ assets:cash++$ hledger print +2026-01-15 buy+ assets:stocks 10 AAPL {2026-01-15, $50}+ assets:cash++ A final account name part enclosed in '{' and '}' is reserved for lot+subaccounts, and it must be a valid lot subaccount name (unless using+'-I' or '--ignore-lots'). Lot subaccount names must be complete,+including all cost basis parts - date, label if any, and cost.++ When strictly checking account names, lot subaccounts are ignored -+you only need to declare the base account (eg 'assets:stocks'), not the+lot subaccounts.+++File: hledger.info, Node: Several ways to write lot entries, Next: Disabling lot tracking, Prev: Lot subaccounts, Up: Writing lot entries++29.2.4 Several ways to write lot entries+----------------------------------------++Here are two acquisitions and a disposal, written in several ways.+First, with explicit lot subaccounts:++2026-01-15 buy low+ assets:stocks:{2026-01-15, $50} 10 AAPL+ assets:cash -$500++2026-02-01 buy high+ assets:stocks:{2026-02-01, $60} 10 AAPL+ assets:cash -$600++2026-03-01 sell some+ assets:stocks:{2026-01-15, $50} -5 AAPL @ $70+ assets:cash $350++ Second, with cost basis annotations (here the '{}' selector means:+use the default method, FIFO; and the '@' costs could be omitted, since+hledger can infer them from the cash postings):++2026-01-15 buy low+ assets:stocks 10 AAPL {$50}+ assets:cash -$500++2026-02-01 buy high+ assets:stocks 10 AAPL {$60}+ assets:cash -$600++2026-03-01 sell some+ assets:stocks -5 AAPL {} @ $70+ assets:cash $350++ Third, with a 'lots' tag on the commodity, lots are inferred from the+transacted costs:++commodity AAPL ; lots:++2026-01-15 buy low+ assets:stocks 10 AAPL @ $50+ assets:cash -$500++2026-02-01 buy high+ assets:stocks 10 AAPL @ $60+ assets:cash -$600++2026-03-01 sell some+ assets:stocks -5 AAPL @ $70+ assets:cash $350++ All three notations produce the same lots and the same $100 gain; Lot+reports below shows them.+++File: hledger.info, Node: Disabling lot tracking, Prev: Several ways to write lot entries, Up: Writing lot entries++29.2.5 Disabling lot tracking+-----------------------------++If you want a commodity tracked lotfully in only some accounts, use+annotations rather than the 'lots' tag. Or if it should be tracked+everywhere except certain accounts (eg tax-sheltered accounts where cost+basis doesn't matter), use the 'lots' tag, and add a 'lots: NONE' tag to+those accounts' declarations to disable lot tracking there:++account assets:ira ; lots: NONE++ Postings in such accounts are not lot-tracked and get no lot+subaccounts or gain postings, unless they have explicit lot annotations,+which always enable tracking. Moving a lotful commodity from a tracked+account into such an account is a disposal; moving it out again needs a+cost basis or price on the receiving posting.++ Sometimes you may want to disable lots/gains processing entirely, to+silence lot-related errors when you are working with incomplete journals+(eg, when piping hledger print into another hledger command, or when+fixing a complex journal's problems one at a time). For this, use the+'--ignore-lots' flag, or just '-I'. This skips lot tracking, capital+gains calculation, and all lot error checking, while still doing enough+lot inference that lot entries balance as usual. Reports then show no+lot subaccounts or gains, and 'print' shows lot entries as you wrote+them, without inferred cost basis annotations or gain postings (explicit+annotations are kept, and may not be readable by hledger 1; if that's+needed, use '-O ledger' to write them in Ledger's syntax, which hledger+1 accepts and ignores).+++File: hledger.info, Node: Lot movements, Next: Cost basis methods, Prev: Writing lot entries, Up: Lots and capital gains++29.3 Lot movements+==================++hledger understands three kinds of lot movement: acquire, transfer, and+dispose. Other real-world lot events can usually be modelled using+combinations of these (see Other lot events below). These are described+for lots in asset accounts; in liability accounts, which hold short+positions, the signs are reversed.++ Lots are calculated in date order, and entries on the same date in+the order they are read (an included file is read at the point where it+is included). So an entry which takes lots out of an account must come+after the entries that put them there, even on the same date; hledger+doesn't reorder entries to make lots available. When this goes wrong,+the "no lots available" error names a later entry on the same date which+would have supplied the lots, if there is one.++* Menu:++* Acquire::+* Transfer::+* Dispose::+* Short positions::+* Other lot events::+++File: hledger.info, Node: Acquire, Next: Transfer, Up: Lot movements++29.3.1 Acquire+--------------++A positive lot posting in an asset account creates a new lot.++2026-01-01 buy shares+ assets:cash -$500+ assets:broker 10 ETSY {$50}++ The asset posting's cost is the lot's cost basis; hledger balances+the transaction and calculates gains with it. It can be written as a+cost basis annotation ('{UNITCOST}' or '{{TOTALCOST}}') or as a+transacted cost ('@ UNITCOST' or '@@ TOTALCOST'); in an acquisition+these mean the same thing. (Note, '@' alone makes a lot posting only if+the commodity is declared lotful or the account is named like a lot+subaccount; otherwise it is just a conversion and creates no lot. To+make it an acquisition, adding just '{}' would be enough, eg '10 ETSY {}+@ $50'.) Usually you write just one and the other is inferred; if both+are written, they must agree (at the precision you wrote the basis with;+the exact transacted cost is then used as the basis; see also Basis and+transacted cost must agree). (The total cost forms are useful when the+unit cost is non-terminating.) The cost can also be inferred from a lot+subaccount name, or, for a lotful commodity, from the transaction's+other postings - so even a bare positive posting (no '{}' or '@') can be+an acquire.++ The other postings show what funded the basis, such as:++ * cash for what you paid (including fees if you want those+ capitalised in the basis; see Capitalising fees)+ * an expense posting for any part of what you paid that isn't basis+ (a fee you don't want to capitalise)+ * an income or equity posting for any part you didn't pay (as with a+ gift's carryover basis or shares received as compensation).++ Eg shares received as a gift, with the giver's basis carried over:++2026-01-01 gift of 10 AAPL, carryover basis $50/share+ equity:gifts received $-500+ assets:stocks 10 AAPL @ $50++ Other cases with a basis differing from what was paid include+inheritance (stepped-up basis), stock options and RSUs, and wash sales;+see https://en.wikipedia.org/wiki/Cost_basis. Recording them this way+keeps the accounting equation balanced and shows where the basis came+from.++* Menu:++* Basis and transacted cost must agree::+* Capitalising fees::+++File: hledger.info, Node: Basis and transacted cost must agree, Next: Capitalising fees, Up: Acquire++29.3.1.1 Basis and transacted cost must agree+.............................................++In an acquisition, if both a cost basis ('{}') and a transacted cost+('@') are written, they must be the same. (Ledger and Beancount allow+them to differ; hledger reports an error.) This is because:++ * In hledger, '@' has one consistent meaning: the transacted cost,+ what was actually exchanged. It's what transactions balance with+ (except for lot disposals, which balance with the cost basis; see+ Gains). Market prices are recorded with 'P' directives, and cost+ basis with '{}' annotations. (hledger may infer the '{}' from '@'+ in a lot acquisition, as 'print -a' will show.)++ * If '@' and '{}' could differ, the difference would have no proper+ place. If the entry balanced with '@' while gains were calculated+ from '{}', the difference would be unaccounted for: it would be+ neither gain nor income, and cost reports (eg 'bse -B') would be+ off by it. If it balanced with '{}' instead (as in Ledger and+ Beancount), '@' would need a second meaning, an informational+ market price.++ * Real cases where the basis differs from what was paid (gifts,+ inheritance, RSUs..) don't need it. They are better recorded as+ shown above, with the difference funded by a separate posting,+ recording where it came from.++ * It catches mistakes. Otherwise, a typo in either amount would+ silently miscalculate gains.++ So, if you have such entries (eg from Ledger or Beancount), you can+rewrite them depending on what was intended:++ * If '@' was meant as a market price (the usual Ledger and Beancount+ meaning), drop it, and record the price with a 'P' directive. Eg,+ this Ledger entry, which balances with the basis, and records a+ market price of 1.30 USD:++ 2026-01-01 buy+ assets:test 10.00 EUR {1.23 USD} @ 1.30 USD+ assets:bank++ can be written for hledger like this:++ P 2026-01-01 EUR 1.30 USD+ + 2026-01-01 buy+ assets:test 10.00 EUR {1.23 USD}+ assets:bank++ * If the basis really differs from what you paid, write the same+ amount in both (or just one of them), and record the difference+ with a separate posting, as in the gift example above.++ * If they differ only by rounding, write the basis with more decimal+ places, or use the total cost forms.++ * To load an old journal without errors (and without lot tracking),+ use '-I'/'--ignore-lots'.+++File: hledger.info, Node: Capitalising fees, Prev: Basis and transacted cost must agree, Up: Acquire++29.3.1.2 Capitalising fees+..........................++hledger does not automatically capitalise fees into cost basis (as some+tax treatments allow, for purchase or transfer fees). To capitalise an+acquisition fee, fold it into the acquisition cost:++2026-01-15 buy 10 AAPL at $50, plus a $10 commission, capitalised+ assets:stocks 10 AAPL @@ $510+ assets:cash -$510++ This lot's cost basis is $51 per share. (Recording the commission as+a separate expense posting would instead keep it out of the basis.)+Capitalising an in-kind transfer fee is possible too, but fiddly; see+Other lot events.+++File: hledger.info, Node: Transfer, Next: Dispose, Prev: Acquire, Up: Lot movements++29.3.2 Transfer+---------------++A matching pair of negative/positive lotful postings moves one or more+existing lots between accounts, preserving their cost basis.++2026-05-01 transfer to another broker+ assets:broker -10 ETSY+ assets:broker2 10 ETSY++ Transfer postings should not have a transacted price, and the total+quantities sent and received must match: transferred lots keep their+identity. Within that, source and destination postings need not pair up+one to one - one source posting can feed several destination accounts,+or several sources one destination. The destination amount, or the+source amount, can also be elided, even when the other posting carries a+lot selector (eg 'assets:broker -10 ETSY {2026-01-01}' balanced by a+bare 'assets:broker2' posting, or vice versa).++ A consequence: a disposal entry mistakenly written without a selling+price, and with the other amount left implicit, looks like a lot+transfer, and is quietly read as one, without raising an error. If in+doubt, 'print -a' shows how an entry was read.++* Menu:++* Transfer fees::+* Transfers recorded in two entries::+++File: hledger.info, Node: Transfer fees, Next: Transfers recorded in two entries, Up: Transfer++29.3.2.1 Transfer fees+......................++If the destination receives less than the source sends (eg because an+exchange deducted a fee), record the fee as its own posting in the same+commodity, eg 'expenses:fees 0.001 ETH @ $3000' (or without the price);+several fee postings which together make up the difference also work.+hledger reads the fee as a small disposal (consuming lots in the usual+cost basis method order, before the transfer) and transfers the rest.+With a price, the fee disposal gets a gain calculated; without one, it+doesn't. Otherwise, mismatched sent/received totals are an error.+'print --lots' (or 'print -a') shows how the entry was read.++ Conversely, if the destination receives _more_ than the source sends+(eg a reclaimed fee, or dust from a past bookkeeping error), a fee can't+explain that, and the extra should be recorded as its own acquisition:+give it a real or dummy cost basis (or price) annotation, which keeps it+out of the transfer matching. Eg:++2026-05-01 transfer, plus a reclaimed fee+ assets:broker -10 ETH+ assets:broker2 10 ETH+ expenses:fees -0.001 ETH+ assets:broker2 0.001 ETH {$0}+++File: hledger.info, Node: Transfers recorded in two entries, Prev: Transfer fees, Up: Transfer++29.3.2.2 Transfers recorded in two entries+..........................................++A transfer between your own accounts is sometimes recorded twice, once+from each account's statement, the two entries meeting in a clearing+account:++2026-01-03 send to wallet A ; from wallet B's statement+ assets:wallet B -0.11 ETH+ assets:transfers 0.10 ETH+ expenses:fees 0.01 ETH++2026-01-03 receive from wallet B ; from wallet A's statement+ assets:transfers -0.10 ETH+ assets:wallet A 0.10 ETH++ The receiving entry takes the lots out of the clearing account, so+the sending entry must be read first (see Lot movements). When each+statement is imported into its own file, this depends on the order the+files are included in. Some ways to make it reliable:++ * Record the transfer as one entry, from one statement, and drop it+ from the other (eg with a 'skip' rule in that account's CSV rules).+ This is the most accurate model of a single event, and doesn't+ depend on order.+ * Include the sending account's files before the receiving account's.+ This stops working if, on some date, transfers go both ways.+++File: hledger.info, Node: Dispose, Next: Short positions, Prev: Transfer, Up: Lot movements++29.3.3 Dispose+--------------++A negative lot posting sells from one or more existing lots.++2026-08-01 sell at a gain+ assets:broker2 -10 ETSY {$50} @ $90 ; selecting the lot by specific identification+ assets:cash $900+ revenues:gain $-400 ; gain can be recorded explicitly or left implicit++ The disposal posting must have a transacted price (the selling+price), either explicit or inferred: $90 here.++ One exception: an _in-kind disposal_, where the entry's non-asset+postings receive the disposed units (the same commodity, in the same+total quantity, possibly split across postings), may be priceless. Eg a+transfer fee deducted in the commodity, or an in-kind donation. This is+a simple way to record such outflows when you don't need a gain+calculated: the disposed units leave their lot(s) carrying their own+cost basis, so the remaining units' basis is unchanged, but no gain or+loss is recognised, and the receiving posting holds unpriced commodity+units. To have the gain calculated, give the receiving posting a+transacted price.++ When the gain posting is inferred, it is calculated from the entry's+dispose postings only (the quantity times the difference between selling+price and cost basis, summed); acquire postings in the same entry don't+contribute.+++File: hledger.info, Node: Short positions, Next: Other lot events, Prev: Dispose, Up: Lot movements++29.3.4 Short positions+----------------------++A short position - units sold before they are bought, with the broker+lending them - is recorded as lots in a _liability_ account (type 'L',+declared or inferred from the account name). There the signs are+reversed: a _negative_ lot posting opens a short lot (it is an acquire,+whose cost basis is the short-sale price), and a _positive_ lot posting+closes it, by buying units back (it is a disposal, whose transacted+price is the buying price). A short lot's gain is its basis minus the+buying price, so it is positive when the price has fallen:++commodity XYZ ; lots:++2026-01-02 sell short+ liabilities:broker:XYZ -10 XYZ @ $100+ assets:broker:cash++P 2026-01-31 XYZ $90++2026-02-02 cover+ liabilities:broker:XYZ 10 XYZ @ $90+ assets:broker:cash+ revenues:gain++$ hledger -f short.journal print -x+2026-01-02 sell short+ liabilities:broker:XYZ -10 XYZ {$100} @ $100+ assets:broker:cash $1000++2026-02-02 cover+ liabilities:broker:XYZ 10 XYZ {2026-01-02, $100} @ $90+ assets:broker:cash $-900+ revenues:gain $-100++ Reports work as for long positions. While the position is open, 'bs+-B' shows the liability at cost ($1000), offsetting the cash received;+'bs -V' shows it at market value ($900), so the net worth includes the+unrealised gain; 'bal --gain' shows that gain ($100); and 'holdings'+shows negative units and cost (but no XIRR, which is not meaningful for+a short position). After covering, the realised gain is in+'revenues:gain', and 'bse' balances.++ Everything else is as for lots in asset accounts: cost basis+annotations and lot subaccounts, lot selectors and cost basis methods,+generated or user-written gain postings, and 'lots: NONE' to opt out.+Note that HIFO covers the highest short-sale price first, which realises+the largest gain first; use SPECID to choose. Long lots and short lots+of the same commodity are separate pools, so they may use different+methods.++ Transferring a short position between accounts is not yet supported:+cover it in one account and open it in the other, with prices. ('close+--lots' can move short lots to and from equity, though.) A negative+posting in an _asset_ account holding no lots is still an error, since+it is usually a mistake.+++File: hledger.info, Node: Other lot events, Prev: Short positions, Up: Lot movements++29.3.5 Other lot events+-----------------------++Other real-world events - a gift received with a carryover cost basis,+bonus shares, a stock split, capitalising an in-kind transfer fee - can+be recorded as combinations of acquires, transfers and disposals. Other+lot events on hledger.org has worked examples. The right treatment+varies by jurisdiction, so check your local tax rules.+++File: hledger.info, Node: Cost basis methods, Next: Gains, Prev: Lot movements, Up: Lots and capital gains++29.4 Cost basis methods+=======================++If a lot transfer or a lot disposal doesn't specifically identify the+lot(s) involved, hledger selects from the available lots automatically,+using a _cost basis method_ (AKA disposal method / reduction method /+booking method).++ Use the method your tax jurisdiction requires or allows. The default+method is FIFO (first in, first out). You can override this with a+'lots' tag value on the commodity or account declaration. (An account+tag will take precedence; on an account, the tag requires a method+value.) Eg:++commodity FUND ; lots: AVERAGE+account assets:stocks ; lots: LIFO++ These methods are supported:++Method Lots Disposal Error checking+ selected cost basis+----------------------------------------------------------------------------+*SPECID* one specific specified A matching lot, with sufficient+ lot lot's cost balance, exists in the account.+*FIFO* oldest first each lot's Sufficient lot(s) exist in the+ cost account.+*LIFO* newest first each lot's "+ cost+*HIFO* highest cost each lot's "+ first cost+*AVERAGE* oldest first average "+ cost+*FIFOALL* oldest first each lot's Sufficient lot(s) exist in the+ (all cost account, and are highest priority+ accounts) across all accounts.+*LIFOALL* newest first each lot's "+ (all cost+ accounts)+*HIFOALL* highest cost each lot's "+ first (all cost+ accounts)+*AVERAGEALL*oldest first average Sufficient lot(s) exist across all+ (all cost (all accounts.+ accounts) accounts)++ *SPECID* (specific identification) is what you're using when a+disposal names its lot(s), with a lot selector like '{2026-01-15, $50}'+or an explicit lot subaccount. Select by date (and label) rather than+by cost alone: costs shown in lot names may be rounded (see Cost basis+precision), so a cost-only selector like '{$50}' can match more lots+than intended (an ambiguity error under SPECID; under other methods,+consumed in the method's order).++ *AVERAGE* keeps one running average cost per account (pool),+recalculated at each acquisition and applied to every lot in the pool;+disposals use it, consuming lots in FIFO order so acquisition dates stay+meaningful for holding periods. Lot names omit the cost+('{2026-01-15}'), the average appears in the holdings Avg cost column+and in disposal postings shown by 'print -x', and transferring lots into+or out of the pool carries the average with them (a lot's original cost+can't be recovered from a pool). close -lots writes each lot with the+pool's average cost as of the closing date ('{2026-01-15, $55}'), so+that its output can be read back, eg to start a new file. ('print+--lots' output for AVERAGE lots can't be read back yet.)++ The **ALL* variants additionally check that the lots selected are the+ones that would be chosen across all accounts holding the commodity, and+raise an error naming the other account otherwise; use them to enforce a+global disposal order across brokers, exchanges and wallets. Since they+involve every account, declare them on the commodity, not on accounts.+*AVERAGEALL* likewise keeps a single average across all accounts.++* Menu:++* Changing the cost basis method::+++File: hledger.info, Node: Changing the cost basis method, Up: Cost basis methods++29.4.1 Changing the cost basis method+-------------------------------------++hledger recalculates all lots on each run, using the currently declared+methods. So changing a declared method also reinterprets past history+under the new method. Sometimes that's fine; but usually you'll want+past disposals to keep their original lot selections and gains (tax+authorities generally expect a method change to apply only going+forward). Things to know:++ * Disposals recorded without explicit lot selectors or gain amounts+ will select different lots under the new method, changing their+ cost bases and realised gains.++ * Disposals which do record the old method's selections - as explicit+ gain amounts, lot selectors, lot subaccount names, or balance+ assertions - will be checked against the new method's selections,+ and any differences will be reported as errors.++ hledger doesn't yet support declaring different methods for different+time periods, but you can make a method change apply only to the future,+in either of two ways:++ 1. Make past disposals fully explicit, with lot selectors and gain+ amounts, so they no longer depend on the declared method ('print+ -x' and 'print --lots' can help with this). Then change the+ method.++ 2. Or, start a new journal file at the changeover date, using 'close+ --clopen --lots' to carry the current lots into it, and declare the+ new method in the new file.+++File: hledger.info, Node: Gains, Next: Lot reports, Prev: Cost basis methods, Up: Lots and capital gains++29.5 Gains+==========++Each disposal transaction has a *gain posting*, usually on a Gain-type+account, recording the capital gain (or loss) as revenue (or negative+revenue). (Following the usual PTA style, a negative number here means+profit, a positive number means loss.)++ A disposal balances at cost basis, not at transacted cost: the+disposed units count as their quantity times their cost basis (what they+cost you), the proceeds are what you received, and the gain posting+accounts for the difference. Eg selling 5 AAPL bought at $50 for $70+each: '-5 AAPL {$50} @ $70' counts as -$250, '$350' is received, and+'revenues:gain $-100' balances the entry. (This is the historical cost+accounting convention, and is how hledger 1 users have recorded gains.+Unrealised gains are not recorded as postings, but can be reported from+market prices, eg with holdings or '--gain'. Consequently the+accounting equation stays balanced through disposals.)++ The gain posting can be left implicit (and hledger will infer it); or+it can be written explicitly in the journal. Recording gains below+shows examples of both.++ In an inferred gain posting, the gain amount will be rounded to the+entry's local precision for the gain commodity (or if the local+precision is zero, two decimal digits will be shown - except when both+of those digits are zero). More decimals can be seen by increasing the+display precision (eg 'hledger print --round=soft -c '$1.0000'').++ An explicit gain posting can also be written without an amount, in+which case hledger fills in the calculated gain (as when the gain+posting is omitted, but with your choice of account). At most one gain+posting per entry can be left amountless.++* Menu:++* Gain accounts::+* Recording gains::+++File: hledger.info, Node: Gain accounts, Next: Recording gains, Up: Gains++29.5.1 Gain accounts+--------------------++The *'Gain'* (*'G'*) account type is a subtype of Revenue. Declaring an+account with the G type serves three purposes:++ 1. *Recognising gain postings* - explicit gain postings which use the+ G account will be detected reliably by account type, and error+ messages may be clearer.+ 2. *Customising account names* - inferred gain postings will use the+ first-declared G account, rather than the default+ ('revenues:gain'). (If no account is declared with the G type,+ they use the alphabetically first account whose type is inferred as+ G, if any.)+ 3. *Categorising* - when reporting, you can match on the G account+ type specifically.++ G is inferred from conventional English account names (eg+'revenues:gain', 'income:capital-gains'; see the regex table under+Account types). You can also declare it explicitly:++account revenues:capital gain ; type: G++ (There is also an *'UnrealisedGain'* (*'U'*) account type, a subtype+of Equity, for accounts like 'equity:unrealised-gain'; hledger does not+currently generate postings to these.)++ Why do we post both gains and losses to a revenue account ? It's+more convenient than using separate revenue and expense accounts, and+the sign keeps things correct.+++File: hledger.info, Node: Recording gains, Prev: Gain accounts, Up: Gains++29.5.2 Recording gains+----------------------++In a disposal entry, you can leave the gain posting out and let hledger+infer it. This is the simplest style, and avoids most problems:++2026-02-01 sell+ assets:stocks -1 AAPL {$50} @ $60+ assets:cash $60++ Or you can write it, on an account declared with the G account type.+hledger then checks your amount against the calculated gain, catching+more errors:++account revenues:gain ; type:G++2026-02-01 sell+ assets:stocks -1 AAPL {$50} @ $60+ assets:cash $60+ revenues:gain $-10++ Multiple gain postings are allowed, eg one per lot when disposing+from several lots.++ Your amount needs to match the calculated gain only at the entry's+precision (the most decimal places used by the entry's amounts in that+commodity, as in transaction balancing). hledger then uses the exact+calculated gain, so that the small difference isn't left unaccounted for+(with several gain postings, it adjusts the last one). 'print' still+shows your amount as written.++ A written gain posting also protects your history, like a balance+assertion: hledger recalculates lots and gains from the whole journal+each time it runs, so if a past acquisition is edited, an inferred gain+could silently change, whereas a written one no longer matches and is+reported as an error. 'hledger print -x' shows the inferred gain+postings, if you want to write them into the journal.++ A gain posting on an undeclared account also works: hledger detects+it heuristically (roughly: a posting to a non-asset/liability/equity+account, not itself a lot posting, without which the rest of the entry+balances). But the heuristic fails when the entry has another such+posting, eg a fee, and the entry is then reported as unbalanced. So if+you write gain postings, declare the account's type. 'hledger print -a'+shows what was detected.++ (Earlier hledger 2 previews also generated an+'equity:unrealised-gain' counter posting in each disposal, so that+disposals balanced at transacted cost. This is no longer done, and such+postings, if written explicitly, will now leave the entry unbalanced;+remove them.)+++File: hledger.info, Node: Lot reports, Next: Lot details, Prev: Gains, Up: Lots and capital gains++29.6 Lot reports+================++Once lot entries are in the journal, all the usual reports work as+normal, hiding lot detail by default; '--lots' shows it. Using the+several ways journal above (any version):++ 'holdings' gives an overview of your investments: units held, cost,+value, unrealised and realised gain, and XIRR (see First lots example;+add '--lots' for per-lot detail, '-e' to choose the date).++ 'balance --lots' (or 'bs --lots') shows the current lots:++$ hledger bal assets:stocks --lots -N+ 5 AAPL assets:stocks:{2026-01-15, $50}+ 10 AAPL assets:stocks:{2026-02-01, $60}++* Menu:++* Realised gains::+* Unrealised gains::+++File: hledger.info, Node: Realised gains, Next: Unrealised gains, Up: Lot reports++29.6.1 Realised gains+---------------------++Realised gains are on the Gain-type account (see Gain accounts), so+'type:G' queries select them. The total for a period:++$ hledger bal type:G -p 2026+ $-100 revenues:gain+--------------------+ $-100 ++ Each disposal's gain, with a running total:++$ hledger reg type:G+2026-03-01 sell some revenues:gain $-100 $-100++ The disposal entries, with the lots and gain amounts hledger inferred+('-x' shows inferred amounts, '--lots' the lot subaccounts, '-a'+everything including each posting's classification):++$ hledger print tag:ptype=dispose -x --lots+2026-03-01 sell some+ assets:stocks:{2026-01-15, $50} -5 AAPL {2026-01-15, $50} @ $70+ assets:cash $350+ revenues:gain $-100++ When using the roi command with a journal that records lots, make+sure '--pnl' matches the gain account, eg:++$ hledger roi --inv assets:stocks --pnl revenues:gain++ so that realised gains are counted as profit rather than as cash+flows out of the investment.+++File: hledger.info, Node: Unrealised gains, Prev: Realised gains, Up: Lot reports++29.6.2 Unrealised gains+-----------------------++Unrealised gains - on the units you still hold - are not recorded in the+journal (see Gains); hledger calculates them from market prices when+asked. Adding some month-end prices to the journal above:++P 2026-01-31 AAPL $55+P 2026-02-28 AAPL $65+P 2026-03-31 AAPL $80++ 'holdings' shows the unrealised gain (UGain) next to the realised+gain (RGain), per commodity or per lot ('--lots'), as of today or some+other date ('-e').++ 'balance --gain' shows the unrealised gain per account: the current+value of the units held, minus what they cost. Like '-V', it uses the+market price at the end of the report period (today, unless you specify+'-e' or a period):++$ hledger bal assets:stocks --gain+ $350 assets:stocks+--------------------+ $350 ++ That is: 15 AAPL are held, which cost $850 and are worth $1200 at+$80. '--lots' breaks it down by lot:++$ hledger bal assets:stocks --gain --lots -N+ $150 assets:stocks:{2026-01-15, $50}+ $200 assets:stocks:{2026-02-01, $60}++ With a report interval, '-H' shows the unrealised gain as of each+period end, and without '-H', how much it changed during each period:++$ hledger bal assets:stocks --gain -M -H+Historical gain in 2026Q1, valued at period ends:++ || 2026-01-31 2026-02-28 2026-03-31 +===============++====================================+ assets:stocks || $50 $200 $350 +---------------++------------------------------------+ || $50 $200 $350 ++ (This is not the same as '--valuechange', which shows how much an+account's value changed in each period, from price movements and from+buying and selling.)++ '--gain' needs a market price for the units; where none is found, the+units are shown unconverted, alongside the negated cost. Realised and+unrealised gains don't overlap: the gain on units sold is realised, the+gain on units held is unrealised, and together they are the total gain+on the investment so far (here, $100 + $350).+++File: hledger.info, Node: Lot details, Next: Troubleshooting lots, Prev: Lot reports, Up: Lots and capital gains++29.7 Lot details+================++Some finer points, for reference.++* Menu:++* Lot labels::+* Cost basis precision::+* Lot postings and balance assertions::+++File: hledger.info, Node: Lot labels, Next: Cost basis precision, Up: Lot details++29.7.1 Lot labels+-----------------++Internally, each lot is identified by its cost basis date plus an+optional label. Lots of a commodity acquired on the same date (even in+different accounts) must have unique labels to help identify them. If+you don't provide these, hledger adds sequential labels automatically+('"0001"', '"0002"', ..). Labels are used for sorting, so if you write+your own, make them sortable.++ Automatic labels depend on which transactions hledger reads, so the+same lot can get a different label when files are combined (eg yearly+files with closing and opening balances). If a lot needs a stable+label, eg an acquisition dated to an earlier purchase's date after a+split or demerger, write your own. Use a descriptive label, eg+'"demerger"', not numbers like '"0001"', which can clash with automatic+labels. (More detail: SPEC-lots.)+++File: hledger.info, Node: Cost basis precision, Next: Lot postings and balance assertions, Prev: Lot labels, Up: Lot details++29.7.2 Cost basis precision+---------------------------++An inferred cost basis can be a non-terminating decimal (eg '3 ABC @@+$10' gives a $10/3 unit cost). hledger keeps such costs at high+precision internally and calculates gains from the unrounded value, but+in lot names it displays at most 8 decimal digits, or more if the cost+commodity's declared display style has more. Two consequences: when+lots are carried into a new file as text (eg with 'close --lots'), only+the displayed digits survive, so if you track commodities needing finer+cost precision, declare a wider display style for the cost commodity up+front; and changing a commodity's display precision can change how lot+names render, so lot selectors written with the old rendering will need+updating (see Troubleshooting lots). Selectors using just the date (and+label) don't embed a cost, and are unaffected. (More detail:+SPEC-lots.)+++File: hledger.info, Node: Lot postings and balance assertions, Prev: Cost basis precision, Up: Lot details++29.7.3 Lot postings and balance assertions+------------------------------------------++See also Assertions and lot subaccounts above.++ On a dispose or transfer posting without an explicit lot subaccount,+a balance assertion always refers to the parent account's balance. So+if lot subaccounts are added with '--lots', the assertion is not+affected.++ By contrast, in a journal entry where the lot subaccounts are+recorded explicitly, a balance assertion refers to the lot subaccount's+balance.++ This means that 'hledger print --lots', if it adds explicit lot+subaccounts to a journal entry, could potentially change the meaning of+balance assertions, breaking them. To avoid this, in such cases it will+move the balance assertion to a new zero-amount posting to the parent+account (and make sure it's subaccount-inclusive). (So eg 'hledger -f-+print --lots -x | hledger -f- check assertions' will still pass.)+++File: hledger.info, Node: Troubleshooting lots, Prev: Lot details, Up: Lots and capital gains++29.8 Troubleshooting lots+=========================++hledger analyses lot entries carefully, but it won't understand every+possible shape. When it reports a lot-related error, or a report looks+wrong:++ * 'hledger print -a' shows how each entry was read: the inferred cost+ basis, lot subaccounts and gain posting, and each posting's+ classification ('ptype: acquire', 'dispose', 'transfer-from',+ 'transfer-to' or 'gain'). If an entry was misread, rewrite it more+ explicitly, eg by adding a cost basis annotation, or a transacted+ cost.+ * "no lots matching ..." means a lot selector matched nothing in+ that account; the error lists the account's actual lots. Common+ causes: the lot is in another account, or a cost-only selector no+ longer matches the displayed cost (see Cost basis precision; date+ selectors avoid this).+ * A disposal written without a selling price, with the other amount+ left implicit, is silently read as a transfer. Add the price.+ * "realised gain amount is wrong" means a written gain posting+ doesn't match the calculated gain; the error shows both amounts.+ Check which lots were selected ('print -a') and the amounts.+ * "cost basis ... differs from its transacted cost" means an+ acquisition wrote both a '{}' basis and an '@' cost which don't+ agree. Write just one of them, or see Basis and transacted cost+ must agree for other fixes.+ * "no ... lots available for disposal" means a sale from an account+ holding none of the commodity. If it is a short sale, record it in+ a liability account (see Short positions). If the purchases were+ written with just an '@' cost (common in Ledger journals), they did+ not create lots; declare the commodity lotful.+ * For more detail, '--debug=5' (eg 'hledger check --debug=5') traces+ lot processing step by step. It's verbose, and mostly useful for+ advanced troubleshooting or bug reports.+ * To silence lot processing while fixing other problems, use '-I' or+ '--ignore-lots'.+++File: hledger.info, Node: Generating data, Next: Forecasting, Prev: Lots and capital gains, Up: Top++30 Generating data+******************++hledger can enrich the data provided to it, or generate new data, in a+number of ways. Mostly, this is done only if you request it:++ * Missing amounts, costs, cost basis, and capital gain amounts are+ inferred automatically when possible.+ * Lot subaccounts are also inferred (invisibly by default; '--lots'+ makes them visible in reports).+ * The '--infer-equity' flag infers missing conversion equity postings+ from @/@@ costs.+ * The '--infer-costs' flag infers missing costs from conversion+ equity postings.+ * The '--infer-market-prices' flag infers 'P' price directives from+ costs.+ * The '--auto' flag adds extra postings to transactions matched by+ auto posting rules.+ * The '--forecast' option generates transactions from periodic+ transaction rules.+ * The 'balance --budget' report infers budget goals from periodic+ transaction rules.+ * Commands like 'close', 'rewrite', and 'hledger-interest' generate+ transactions or postings.+ * CSV data is converted to transactions by applying CSV conversion+ rules.. etc.++ Such generated data is temporary, existing only at report time. You+can convert it to permanent recorded data by, eg, capturing the output+of 'hledger print' and saving it in your journal file. This can+sometimes be useful as a data entry aid.++ If you are curious what data is being generated and why, run 'hledger+print -a' (equivalent to '--explicit --lots --verbose-tags').+'-x/--explicit' shows inferred amounts and conversion prices, '--lots'+shows lot subaccounts and lot-specific postings, and '--verbose-tags'+shows the hidden tags which hledger uses for analysing transactions .+++File: hledger.info, Node: Forecasting, Next: Budgeting, Prev: Generating data, Up: Top++31 Forecasting+**************++Forecasting, or speculative future reporting, can be useful for+estimating future balances, or for exploring different future scenarios.++ The simplest and most flexible way to do it with hledger is to+manually record a bunch of future-dated transactions. You could keep+these in a separate 'future.journal' and include that with '-f' only+when you want to see them.++* Menu:++* --forecast::+* Inspecting forecast transactions::+* Forecast reports::+* Forecast tags::+* Forecast period in detail::+* Forecast troubleshooting::+++File: hledger.info, Node: --forecast, Next: Inspecting forecast transactions, Up: Forecasting++31.1 -forecast+==============++There is another way: with the '--forecast' option, hledger can generate+temporary "forecast transactions" for reporting purposes, according to+periodic transaction rules defined in the journal. Each rule can+generate multiple recurring transactions, so by changing one rule you+can change many forecasted transactions.++ Forecast transactions usually start after ordinary transactions end.+By default, they begin after your latest-dated ordinary transaction, or+today, whichever is later, and they end six months from today. (The+exact rules are a little more complicated, and are given below.)++ This is the "forecast period", which need not be the same as the+report period. You can override it - eg to forecast farther into the+future, or to force forecast transactions to overlap your ordinary+transactions - by giving the -forecast option a period expression+argument, like '--forecast=..2099' or '--forecast=2023-02-15..'. Note+that the '=' is required.+++File: hledger.info, Node: Inspecting forecast transactions, Next: Forecast reports, Prev: --forecast, Up: Forecasting++31.2 Inspecting forecast transactions+=====================================++'print' is the best command for inspecting and troubleshooting forecast+transactions. Eg:++~ monthly from 2022-12-20 rent+ assets:bank:checking+ expenses:rent $1000++$ hledger print --forecast --today=2023/4/21+2023-05-20 rent+ ; generated-transaction: ~ monthly from 2022-12-20+ assets:bank:checking+ expenses:rent $1000++2023-06-20 rent+ ; generated-transaction: ~ monthly from 2022-12-20+ assets:bank:checking+ expenses:rent $1000++2023-07-20 rent+ ; generated-transaction: ~ monthly from 2022-12-20+ assets:bank:checking+ expenses:rent $1000++2023-08-20 rent+ ; generated-transaction: ~ monthly from 2022-12-20+ assets:bank:checking+ expenses:rent $1000++2023-09-20 rent+ ; generated-transaction: ~ monthly from 2022-12-20+ assets:bank:checking+ expenses:rent $1000++ Here there are no ordinary transactions, so the forecasted+transactions begin on the first occurrence after today's date. (You+won't normally use '--today'; it's just to make these examples+reproducible.)+++File: hledger.info, Node: Forecast reports, Next: Forecast tags, Prev: Inspecting forecast transactions, Up: Forecasting++31.3 Forecast reports+=====================++Forecast transactions affect all reports, as you would expect. Eg:++$ hledger areg rent --forecast --today=2023/4/21+Transactions in expenses:rent and subaccounts:+2023-05-20 rent as:ba:checking $1000 $1000+2023-06-20 rent as:ba:checking $1000 $2000+2023-07-20 rent as:ba:checking $1000 $3000+2023-08-20 rent as:ba:checking $1000 $4000+2023-09-20 rent as:ba:checking $1000 $5000++$ hledger bal -M expenses --forecast --today=2023/4/21+Balance changes in 2023-05-01..2023-09-30:++ || May Jun Jul Aug Sep +===============++===================================+ expenses:rent || $1000 $1000 $1000 $1000 $1000 +---------------++-----------------------------------+ || $1000 $1000 $1000 $1000 $1000 +++File: hledger.info, Node: Forecast tags, Next: Forecast period in detail, Prev: Forecast reports, Up: Forecasting++31.4 Forecast tags+==================++Forecast transactions generated by -forecast have a hidden tag,+'_generated-transaction'. So if you ever need to match forecast+transactions, you could use 'tag:_generated-transaction' (or just+'tag:generated') in a query.++ For troubleshooting, you can add the '--verbose-tags' flag. Then,+visible 'generated-transaction' tags will be added also, so you can view+them with the 'print' command. Their value indicates which periodic+rule was responsible.+++File: hledger.info, Node: Forecast period in detail, Next: Forecast troubleshooting, Prev: Forecast tags, Up: Forecasting++31.5 Forecast period, in detail+===============================++Forecast start/end dates are chosen so as to do something useful by+default in almost all situations, while also being flexible. Here are+(with luck) the exact rules, to help with troubleshooting:++ The forecast period starts on:++ * the later of+ * the start date in the periodic transaction rule+ * the start date in '--forecast''s argument++ * otherwise (if those are not available): the later of+ * the report start date specified with '-b'/'-p'/'date:'+ * the day after the latest ordinary transaction in the journal++ * otherwise (if none of these are available): today.++ The forecast period ends on:++ * the earlier of+ * the end date in the periodic transaction rule+ * the end date in '--forecast''s argument++ * otherwise: the report end date specified with '-e'/'-p'/'date:'+ * otherwise: 180 days (~6 months) from today.+++File: hledger.info, Node: Forecast troubleshooting, Prev: Forecast period in detail, Up: Forecasting++31.6 Forecast troubleshooting+=============================++When -forecast is not doing what you expect, one of these tips should+help:++ * Remember to use the '--forecast' option.+ * Remember to have at least one periodic transaction rule in your+ journal.+ * Test with 'print --forecast'.+ * Check for typos or too-restrictive start/end dates in your periodic+ transaction rule.+ * Leave at least 2 spaces between the rule's period expression and+ description fields.+ * Check for future-dated ordinary transactions suppressing forecasted+ transactions.+ * Try setting explicit report start and/or end dates with '-b', '-e',+ '-p' or 'date:'+ * Try adding the '-E' flag to encourage display of empty periods/zero+ transactions.+ * Try setting explicit forecast start and/or end dates with+ '--forecast=START..END'+ * Consult Forecast period, in detail, above.+ * Check inside the engine: add '--debug=2' (eg).+++File: hledger.info, Node: Budgeting, Next: Posting types, Prev: Forecasting, Up: Top++32 Budgeting+************++With the balance command's '--budget' report, each periodic transaction+rule generates recurring budget goals in specified accounts, and goals+and actual performance can be compared. See the balance command's doc+below.++ You can generate budget goals and forecast transactions at the same+time, from the same or different periodic transaction rules: 'hledger+bal -M --budget --forecast ...'++ See also: Budgeting on hledger.org.+++File: hledger.info, Node: Posting types, Next: PART 5 MORE ABOUT THE COMMAND LINE, Prev: Budgeting, Up: Top++33 Posting types+****************++hledger detects and tags certain kinds of postings, to help it+understand complex transactions. Here is quick overview of the posting+detection rules.++ By default, these tags are hidden (with a '_' prefix), so they can be+queried but they won't appear in 'print' output. To also add visible+tags, for troubleshooting, use 'print''s '--verbose-tags' or '-a/--all'+flags.++Tag Detected pattern Effect+---------------------------------------------------------------------------+'conversion-posting'A pair of adjacent, single-commodity,Helps transaction+ costless postings to 'Conversion'-type balancer infer costs or+ accounts, with a nearby corresponding avoid redundancy in+ costful or potentially corresponding commodity conversions+ costless posting+'cost-posting'A costful posting whose amount and Helps transaction+ transacted cost correspond to a balancer infer costs or+ conversion postings pair; or a costless avoid redundancy in+ posting matching one of the pair commodity conversions+'generated-posting'Postings generated at runtime Helps users understand+ or find postings added+ at runtime by hledger+'ptype:acquire'Positive postings with lot annotations,Creates a new lot+ or in a lotful commodity, with no+ matching counterposting (negative, in a+ liability account: a short position)+'ptype:dispose'Negative postings with lot annotations,Selects and reduces+ or in a lotful commodity, with no existing lots+ matching counterposting (positive, in a+ liability account: covering a short+ position)+'ptype:transfer-from'The negative posting of a pair ofMoves lots between+ counterpostings, at least one with lot accounts, preserving+ annotation or a lotful commodity; or a cost basis+ negative lot posting with an equity+ counterpart (equity transfer)+'ptype:transfer-to'The positive posting of a transferAs above+ pair; or a positive lot posting with an+ equity counterpart (equity transfer,+ e.g. opening balances)+'ptype:gain'In a disposal: a user-written postingRecords the realised+ to a 'Gain'-type account (or, failing capital gain/loss; set+ that, a non-asset/liability/equity aside by the+ posting without which the entry transaction balancer,+ balances); or the realised-gain posting so the disposal+ hledger generates balances at cost basis+++File: hledger.info, Node: PART 5 MORE ABOUT THE COMMAND LINE, Next: Output, Prev: Posting types, Up: Top++34 PART 5: MORE ABOUT THE COMMAND LINE+**************************************+++File: hledger.info, Node: Output, Next: Charts, Prev: PART 5 MORE ABOUT THE COMMAND LINE, Up: Top++35 Output+*********++* Menu:++* Output destination::+* Output format::+* Debug output::+* Built-in tests::+++File: hledger.info, Node: Output destination, Next: Output format, Up: Output++35.1 Output destination+=======================++hledger commands send their output to the terminal by default. You can+of course redirect this, eg into a file, using standard shell syntax:++$ hledger print > foo.txt++ Some commands (print, register, stats, the balance commands) also+provide the '-o'/'--output-file' option, which does the same thing+without needing the shell. Eg:++$ hledger print -o foo.txt+$ hledger print -o - # write to stdout (the default)++ These commands (except stats) also provide '--view', which writes the+output to a file and opens it in your system's default viewer for that+kind of file, eg a web browser for HTML. The file is the one given by+'-o', or else 'view.FMT' in hledger's cache directory+('$XDG_CACHE_HOME/hledger/' or '~/.cache/hledger/', or+'%LOCALAPPDATA%\hledger\' on Windows), replaced each time, and readable+only by you (on unix systems). hledger shows the file's path; if the+report is sensitive, you can delete the file when you're done with it,+or use '-o' to save it somewhere else. The output format is HTML unless+you choose another, with '-O' or the '-o' file's extension. Eg:++$ hledger is -M --chart --view # see an income statement chart and table in a web browser+$ hledger reg -O csv --view # or a register in a spreadsheet++ To view several reports at once, on one page, use 'run' with+'--view':++$ hledger run --view -- is -M --chart -- bs -Q --chart -- reg expenses -p thismonth+++File: hledger.info, Node: Output format, Next: Debug output, Prev: Output destination, Up: Output++35.2 Output format+==================++Some commands offer other kinds of output, not just text on the+terminal. Here are those commands and the formats currently supported:++command txt journal html csv/tsv fods ledger beancount sql json svg+-----------------------------------------------------------------------------------+aregister Y Y Y Y Y Y+balance Y Y Y Y Y Y+balancesheet Y Y Y Y Y Y+balancesheetequityY Y Y Y Y Y+cashflow Y Y Y Y Y Y+holdings Y Y Y Y Y+incomestatement Y Y Y Y Y Y+print Y Y Y Y Y Y Y Y+register Y Y Y Y Y Y++ You can also see which output formats a command supports by running+'hledger CMD -h' and looking for the '-O'/'--output-format=FMT' option,++ You can select the output format by using that option:++$ hledger print -O csv # print CSV to standard output++ or by choosing a suitable filename extension with the+'-o'/'--output-file=FILE.FMT' option:++$ hledger balancesheet -o foo.csv # write CSV to foo.csv++ The '-O' option can be combined with '-o' to override the file+extension if needed:++$ hledger balancesheet -o foo.txt -O csv # write CSV to foo.txt++ Here are some notes about the various output formats.++* Menu:++* Text output::+* HTML output::+* CSV / TSV output::+* FODS output::+* Ledger output::+* Beancount output::+* SQL output::+* JSON output::+* SVG output::+++File: hledger.info, Node: Text output, Next: HTML output, Up: Output format++35.2.1 Text output+------------------++This is the default: human readable, plain text report output, suitable+for viewing with a monospace font in a terminal. If your data contains+unicode or wide characters, you'll need a terminal and font that render+those correctly. (This can be challenging on MS Windows.)++ Some reports ('register', 'aregister') will normally use the full+window width. If this isn't working or you want to override it, you can+use the '-w'/'--width' option.++ Balance reports ('balance', 'balancesheet', 'incomestatement'...)+use whatever width they need. Multi-period multi-currency reports can+often be wider than the window. Besides using a pager, helpful+techniques for this situation include '--layout=bare', '-X COMM',+'cur:', '--transpose', '--tree', '--depth', '--drop', switching to html+output, etc.++ The display style of amounts (symbol placement, decimal and digit+group marks, number of decimal digits) is inferred per commodity, and+can be overridden with '-c/--commodity-style'; see Amount formatting.++* Menu:++* Box-drawing characters::+* Colour::+* Paging::+++File: hledger.info, Node: Box-drawing characters, Next: Colour, Up: Text output++35.2.1.1 Box-drawing characters+...............................++hledger draws simple table borders by default, to minimise the risk of+display problems caused by a terminal/font not supporting box-drawing+characters.++ But your terminal and font probably do support them, so we recommend+using the '--pretty' flag to show prettier tables in the terminal. This+is a good flag to add to your hledger config file.+++File: hledger.info, Node: Colour, Next: Paging, Prev: Box-drawing characters, Up: Text output++35.2.1.2 Colour+...............++hledger tries to automatically detect ANSI colour and text styling+support and use it when appropriate. (Currently, it is used rather+minimally: some reports show negative numbers in red, and help output+uses bold text for emphasis.) Colour is not used when the 'TERM'+environment variable is 'dumb', or 'NO_COLOR' is set, or output is not+going to a colour-capable terminal.++ You can override this by setting the 'NO_COLOR' environment variable+to disable it, or by using the '--color/--colour' option, perhaps in+your config file, with a 'y'/'yes' or 'n'/'no' value to force it on or+off.+++File: hledger.info, Node: Paging, Prev: Colour, Up: Text output++35.2.1.3 Paging+...............++In unix-like environments, when displaying large output (in any output+format) in the terminal, hledger tries to use a pager when appropriate.+(You can disable this with the '--pager=no' option, perhaps in your+config file.)++ The pager shows one page of text at a time, and lets you scroll+around to see more. While it is active, usually 'SPACE' shows the next+page, 'h' shows help, and 'q' quits. The home/end/page up/page+down/cursor keys, and mouse scrolling, may also work.++ hledger will use the pager specified by the 'PAGER' environment+variable, otherwise 'less' if available, otherwise 'more' if available.+(With one exception: 'hledger help -p TOPIC' will always use 'less', so+that it can scroll to the topic.)++ The pager is expected to display hledger's ANSI colour and text+styling. If you see junk characters, you might need to configure your+pager to handle ANSI codes. Or you could disable colour as described+above.++ If you are using the 'less' pager, hledger tries to provide a+consistently pleasant experience by running it with some extra options+added to your 'LESS' environment variable:++ -chop-long-lines -hilite-unread -ignore-case -no-init+-quit-if-one-screen -shift=8 -squeeze-blank-lines -use-backslash++ and when colour output is enabled:++ -RAW-CONTROL-CHARS++ You can prevent this by setting your preferred options in the+'HLEDGER_LESS' variable, which will be used instead of 'LESS'.+++File: hledger.info, Node: HTML output, Next: CSV / TSV output, Prev: Text output, Up: Output format++35.2.2 HTML output+------------------++HTML output has some default styling built in; eg, it prevents wrapping+within dates and individual commodity amounts. It can be customised (or+overridden) by an optional 'hledger.css' file in the same directory+(there is a sample in the hledger repo).++ With '--chart', commands that can show charts show one (as inline+SVG), with the text report collapsed below it (see Balance charts).++ HTML output will be a HTML fragment, not a complete HTML document.+It has a newline after each table row, for readability. Like other+hledger output, for non-ascii characters it will use the system locale's+text encoding (see Text encoding).+++File: hledger.info, Node: CSV / TSV output, Next: FODS output, Prev: HTML output, Up: Output format++35.2.3 CSV / TSV output+-----------------------++In CSV or TSV output, digit group marks (such as thousands separators)+are disabled automatically.+++File: hledger.info, Node: FODS output, Next: Ledger output, Prev: CSV / TSV output, Up: Output format++35.2.4 FODS output+------------------++FODS is the OpenDocument Spreadsheet format as plain XML, as read by+LibreOffice and OpenOffice. For those spreadsheet applications it is+better than CSV. It works across locales: decimal point or comma, and+the character encoding is stored in the XML header, so non-ascii text is+safe. It supports fixed header rows and columns, cell types (string,+number, date), styles (bold) and borders. And it keeps number and+currency separate, so amounts show their currency but remain numbers+usable in formulas. You can still extract CSV from FODS/ODS if needed,+with utilities like 'libreoffice --headless' or ods2csv.++ ODS supports only the locale's thousands separator as a digit group+mark, so FODS output enables thousands separators if your commodity+style has any digit groups.+++File: hledger.info, Node: Ledger output, Next: Beancount output, Prev: FODS output, Up: Output format++35.2.5 Ledger output+--------------------++This is a Ledger-specific journal format supported by the 'print'+command. It is currently identical to hledger's default 'print' output+except that cost basis annotations will use Ledger's syntax, ('{COST}+[DATE] (NOTE)'), not hledger's ('{DATE, "LABEL", COST}'). With 'print+--export', directives and comments are also reproduced, and directives+which Ledger does not support are commented out.+++File: hledger.info, Node: Beancount output, Next: SQL output, Prev: Ledger output, Up: Output format++35.2.6 Beancount output+-----------------------++This is Beancount's journal format, supported by the 'print' command.+You can use this to export your hledger data to Beancount, eg to use the+Fava web app.++ hledger will try to adjust your data to suit Beancount,+automatically. By default only transactions are converted; with 'print+--export', the options and 'commodity', 'open' and 'price' directives+Beancount needs are generated too, and top-level comments are converted,+so the output can be read by Beancount directly. Be cautious and check+the conversion until you are confident it is good. If you plan to+export to Beancount often, you may want to follow its conventions, for a+cleaner conversion:++ * use Beancount-friendly account names+ * use currency codes instead of currency symbols+ * use cost notation instead of equity conversion postings+ * avoid virtual postings, balance assignments, and secondary dates.++ There is one big adjustment: for Beancount, the top level account+names must be 'Assets', 'Liabilities', 'Equity', 'Income', and/or+'Expenses'. A top level hledger account named 'revenue' or 'revenues'+(case insensitive) will be converted to 'Income'. Any other top level+account whose account type is known (declared or inferred) will have the+corresponding Beancount top level account prepended; eg with 'account+bonds ; type:A', 'bonds:treasury' becomes 'Assets:Bonds:Treasury'.+Otherwise, you should use '--alias' (see '--alias' option, or this+hledger2beancount.conf file).++ Other adjustments hledger makes:++ * *Account names:* aside from the top-level names, hledger makes+ valid Beancount account names by capitalising each part, replacing+ spaces and underscores with '-', replacing other unsupported+ characters with 'C<HEXBYTES>', prepending 'A' to parts which don't+ begin with a letter or digit, and appending ':A' to account names+ which have only one part.++ * *Commodity names:* hledger makes valid Beancount commodity/currency+ names, which must be 2-24 uppercase letters, digits, or ''', '.',+ '_', '-', beginning with a letter and ending with a letter or+ digit. Known currency symbols become ISO 4217 currency codes;+ otherwise letters are capitalised, spaces become '-', other+ unsupported characters become 'C<HEXBYTES>', and 'C' is prepended+ or appended if needed. One-letter symbols are doubled, and the+ no-symbol commodity becomes 'CC'. (hledger tries to keep your+ commodities distinct, but collisions are possible with short+ symbols like 'CC', 'C' and no-symbol, which are distinct in hledger+ but all become 'CC' in Beancount.)++ * *Balance assignments* are not supported by Beancount, so they are+ converted to explicit amounts.++ * *Virtual postings* are not allowed by Beancount, so any virtual+ postings are omitted.++ * *Tags* become Beancount metadata (except tags whose name begins+ with '_'). Metadata names are adjusted to be Beancount-compatible:+ beginning with a lowercase letter, at least two characters long,+ with unsupported characters encoded; values use Beancount's string+ type. A tag repeated with multiple values (eg an account with both+ 'type:Asset' and 'type:Cash') becomes one metadata entry with the+ values comma separated: 'type: "Asset, Cash"'.++ * *Costs:* Beancount doesn't allow redundant costs and conversion+ postings as hledger does; if you have any, the conversion postings+ are omitted. Currently at most one cost + conversion postings+ group per transaction is supported.++ * *Directives:* with 'print --export', hledger generates a+ 'commodity' directive for each declared commodity, and an 'open'+ directive for each declared or used account, dated on the account's+ earliest posting (or the earliest transaction date). Account and+ commodity tags become metadata on these directives, and an+ account's 'lots:' tag becomes its Beancount booking method. Other+ hledger directives have no Beancount equivalent and are dropped.++ * *Tolerance:* with 'print --export', a sample+ 'inferred_tolerance_default' option is provided, commented out. If+ Beancount complains that transactions aren't balanced, this is an+ easy workaround.++ * *Operating currency:* declaring one or more improves Beancount and+ Fava reports. With 'print --export', hledger declares each+ currency used in cost amounts as an operating currency. If needed,+ replace these with your own declaration, like 'option+ "operating_currency" "USD"'.+++File: hledger.info, Node: SQL output, Next: JSON output, Prev: Beancount output, Up: Output format++35.2.7 SQL output+-----------------++SQL output is expected to work at least with SQLite, MySQL and Postgres.++ The SQL statements are expected to be executed in the empty database.+If you already have tables created via SQL output of hledger, you would+probably want to either clear data from these (via 'delete' or+'truncate' SQL statements) or 'drop' the tables completely before+import; otherwise your postings would be duplicated.++ For SQLite, it is more useful if you modify the generated 'id' field+to be a PRIMARY KEY. Eg:++$ hledger print -O sql | sed 's/id serial/id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL/g' | ...+++File: hledger.info, Node: JSON output, Next: SVG output, Prev: SQL output, Up: Output format++35.2.8 JSON output+------------------++Our JSON is rather large and verbose, since it is a faithful+representation of hledger's internal data types. To understand its+structure, read the Haskell type definitions, which are mostly in+https://github.com/hledgerorg/hledger/blob/main/hledger-lib/Hledger/Data/Types.hs.+hledger-web's OpenAPI specification may also be relevant.++ hledger stores numbers with sometimes up to 255 significant digits.+This is too many digits for most JSON consumers, so in JSON output we+round numbers to at most 10 decimal places. (We don't limit the number+of integer digits.) Related: #1195+++File: hledger.info, Node: SVG output, Prev: JSON output, Up: Output format++35.2.9 SVG output+-----------------++SVG output shows a chart of the report, rather than the report's table+(as the '--chart' flag does with text output; see Balance charts). It+is a self-contained image file, viewable in web browsers and many image+viewers. It has a light and a dark colour scheme, chosen by the+viewer's preference, and tooltips showing each bar's or point's values.+Currently the 'aregister', 'balance', 'balancesheet',+'balancesheetequity', 'cashflow', 'incomestatement' and 'register'+commands can produce it. Eg:++$ hledger bal -M expenses -o expenses.svg+++File: hledger.info, Node: Debug output, Next: Built-in tests, Prev: Output format, Up: Output++35.3 Debug output+=================++We intend hledger to be relatively easy to troubleshoot, introspect and+develop. You can add '--debug[=N]' to any hledger command line to see+additional debug output. N ranges from 1 (least output, the default) to+9 (maximum output). Typically you would start with 1 and increase until+you are seeing enough. At level 1 or higher, the output includes timing+lines, showing the run time and memory allocation of each phase of+hledger's work: reading and parsing data, each stage of journal+finalising, and running the command. These can show where the time goes+when processing a large journal. Debug output goes to stderr, and is+not affected by '-o/--output-file' (unless you redirect stderr to+stdout, eg: '2>&1'). It will be interleaved with normal output, which+can help reveal when parts of the code are evaluated. To capture debug+output in a log file instead, you can usually redirect stderr, eg:++hledger bal --debug=3 2>hledger.log++ (This option doesn't work in a config file yet.)+++File: hledger.info, Node: Built-in tests, Prev: Debug output, Up: Output++35.4 Built-in tests+===================++hledger's unit tests are built in to the executable, and '--test' runs+them, printing the results and exiting with a non-zero code if any fail.+'--test=PATTERN' runs just the tests whose names contain PATTERN (it can+also be a tasty pattern). Eg:++$ hledger --test # run all unit tests+$ hledger --test=balance # run tests with "balance" in their name++ This can be a sanity check of an unusual hledger build; failures are+unlikely, but if you see one, please report it as a bug. (hledger-web+also has a '--test' flag, which runs its own tests.)+++File: hledger.info, Node: Charts, Next: Command line tips, Prev: Output, Up: Top++36 Charts+*********++hledger can show many reports as a chart: add '--chart' to a 'balance',+'balancesheet', 'balancesheetequity', 'cashflow', 'incomestatement',+'aregister', 'register' or 'holdings' report. (The 'activity' command+always shows one.) A suitable kind of chart is chosen for the report:+eg stacked bars per period for balance changes, lines for balances over+time, or a bar per account for a single period. In the terminal the+chart is drawn with text characters, filling the terminal's width (or+the width set by '-w'):++$ hledger bal -Q expenses income --chart -w 50+Balance changes in 2008:++░ expenses:food ▒ expenses:supplies+█ income:gifts ▓ income:salary++2008Q1 $-1 ▓▓▓▓▓▓▓▓▓▓▓▓│+2008Q2 $1 ████████████│░░░░░░░░░░░░▒▒▒▒▒▒▒▒▒▒▒▒+2008Q3 0 │+2008Q4 0 │++ With SVG output (eg '-o chart.svg') it is a graphical chart; with+HTML output it is shown with the report's table collapsed below it; and+with CSV, TSV or JSON output you get the chart's data. To see a+graphical chart quickly, add '--view', eg 'hledger is -M --chart+--view'. '--chart' also accepts a chart kind, 'net' (to draw the net+total, which charts leave out by default), and a fixed scale, eg to+compare charts. For the details, see Balance charts, aregister,+Register charts and Holdings charts.+++File: hledger.info, Node: Command line tips, Next: PART 6 COMMON TASKS, Prev: Charts, Up: Top++37 Command line tips+********************++Here are some tips for using hledger at the command line; feel free to+skip these until you need them.++* Menu:++* Special characters::+* Unicode characters::+* Regular expressions::+* Argument files::+* Shell completions::+++File: hledger.info, Node: Special characters, Next: Unicode characters, Up: Command line tips++37.1 Special characters+=======================++In commands you type at the command line, certain characters have+special meaning and sometimes need to be "escaped" or "quoted", by+prefixing backslashes or enclosing in quotes.++ If you are able to minimise the use of special characters in your+data, you won't have to deal with this as much. For example, you could+use hyphen '-' or underscore '_' instead of spaces in account names, and+you could use the 'USD' currency code instead of the '$' currency symbol+in amounts.++ But if you prefer to use spaced account names and '$', it's fine.+Just be aware of this topic so you can check this doc when needed.+(These examples are mostly tested on unix; some details might need to be+adapted if you're on Windows.)++* Menu:++* Escaping shell special characters::+* Escaping regular expression special characters::+* Escaping in other situations::+++File: hledger.info, Node: Escaping shell special characters, Next: Escaping regular expression special characters, Up: Special characters++37.1.1 Escaping shell special characters+----------------------------------------++These are some characters which may have special meaning to your shell+(the program which interprets command lines):++ * SPACE, '<', '>', '(', ')', '|', '\', '%'+ * '$' if followed by a word character++ So for example, to match an account name containing spaces, like+"credit card", don't write:++$ hledger register credit card++ Instead, enclose the name in single quotes:++$ hledger register 'credit card'++ On unix or in Windows powershell, if you use double quotes your shell+will silently treat '$' as variable interpolation. So you should+probably avoid double quotes, unless you want that behaviour, eg in a+script:++$ hledger register "assets:$SOMEACCT"++ But in an older Windows CMD.EXE window, you must use double quotes:++C:\Users\Me> hledger register "credit card"++ On unix or in Windows powershell, as an alternative to quotes you can+write a backslash before each special character:++$ hledger register credit\ card++ Finally, since hledger's query arguments are regular expressions+(described below), you could also fill that gap with '.' which matches+any character:++$ hledger register credit.card+++File: hledger.info, Node: Escaping regular expression special characters, Next: Escaping in other situations, Prev: Escaping shell special characters, Up: Special characters++37.1.2 Escaping regular expression special characters+-----------------------------------------------------++Some characters also have special meaning in regular expressions, which+hledger's arguments often are. Those include:++ * '.', '^', '$', '[', ']', '(', ')', '|', '\'++ To escape one of these, write '\' before it. But note this is in+addition to the shell escaping above. So for characters which are+special to both shell and regular expressions, like '\' and '$', you+will sometimes need two levels of escaping.++ For example, a balance report that uses a 'cur:' query restricting it+to just the $ currency, should be written like this:++$ hledger balance cur:\\$++ Explanation:++ 1. Add a backslash '\' before the dollar sign '$' to protect it from+ regular expressions (so it will be matched literally with no+ special meaning).+ 2. Add another backslash before that backslash, to protect it from the+ shell (so the shell won't consume it).+ 3. '$' doesn't need to be protected from the shell in this case,+ because it's not followed by a word character; but it would be+ harmless to do so.++ But here's another way to write that, which tends to be easier: add+backslashes to escape from regular expressions, then enclose with quotes+to escape from the shell:++$ hledger balance cur:'\$'+++File: hledger.info, Node: Escaping in other situations, Prev: Escaping regular expression special characters, Up: Special characters++37.1.3 Escaping in other situations+-----------------------------------++hledger options and arguments are sometimes used in places other than+the command line, where the escaping/quoting rules are different. For+example, backslash-quoting may not be available. Here's a quick+reference:++In unix shell Use single quotes and/or backslash (or double quotes+ for variable interpolation)+In Windows Use single quotes (or double quotes for variable+'powershell' interpolation)+In Windows 'cmd' Use double quotes+In hledger-ui's Use single or double quotes+filter prompt+In hledger-web's Use single or double quotes+search form+In an argument Don't use spaces, don't shell-escape, do+file regex-escape, write one argument/option per line+In a config file Use single or double quotes, enclosing all or part+ of an argument (''desc:a b'' or 'desc:'a b'', as in+ the unix shell)+In 'repl' or a Use single or double quotes, enclosing all or part+'run' script of an argument+In 'ghci' (the Use double quotes, and enclose the whole argument+Haskell REPL)+++File: hledger.info, Node: Unicode characters, Next: Regular expressions, Prev: Special characters, Up: Command line tips++37.2 Unicode characters+=======================++hledger is expected to handle non-ascii characters correctly:++ * they should be parsed correctly in input files and on the command+ line, by all hledger tools (add, iadd, hledger-web's+ search/add/edit forms, etc.)++ * they should be displayed correctly by all hledger tools, and+ on-screen alignment should be preserved.++ This requires a well-configured environment. Here are some tips:++ * A system locale must be configured, which can decode the characters+ being used. This is essential - see Text encoding and Install:+ Text encoding.++ * Your terminal software (eg Terminal.app, iTerm, CMD.exe, xterm..)+ must support unicode. On Windows, you may need to use Windows+ Terminal.++ * The terminal must be using a font which includes the required+ unicode glyphs.++ * The terminal should be configured to display wide characters as+ double width (for report alignment).++ * On Windows, for best results you should run hledger in the same+ kind of environment in which it was built. Eg hledger built in the+ standard CMD.EXE environment (like the binaries on our download+ page) might show display problems when run in a cygwin or msys+ terminal, and vice versa. (See eg #961).+++File: hledger.info, Node: Regular expressions, Next: Argument files, Prev: Unicode characters, Up: Command line tips++37.3 Regular expressions+========================++A regular expression (regexp) is a small piece of text where certain+characters (like '.', '^', '$', '+', '*', '()', '|', '[]', '\') have+special meanings, forming a tiny language for matching text precisely -+very useful in hledger and elsewhere. To learn all about them, visit+regular-expressions.info.++ hledger supports regexps whenever you are entering a pattern to match+something, eg in query arguments, account aliases, CSV if rules,+hledger-web's search form, hledger-ui's '/' search, etc. You may need+to wrap them in quotes, especially at the command line (see Special+characters above). Here are some examples:++ Account name queries (quoted for command line use):++Regular expression: Matches:+------------------- ------------------------------------------------------------+bank assets:bank, assets:bank:savings, expenses:art:banksy, ...+:bank assets:bank:savings, expenses:art:banksy+:bank: assets:bank:savings+'^bank' none of those ( ^ matches beginning of text )+'bank$' assets:bank ( $ matches end of text )+'big \$ bank' big $ bank ( \ disables following character's special meaning )+'\bbank\b' assets:bank, assets:bank:savings ( \b matches word boundaries )+'(sav|check)ing' saving or checking ( (|) matches either alternative )+'saving|checking' saving or checking ( outer parentheses are not needed )+'savings?' saving or savings ( ? matches 0 or 1 of the preceding thing )+'my +bank' my bank, my bank, ... ( + matches 1 or more of the preceding thing )+'my *bank' mybank, my bank, my bank, ... ( * matches 0 or more of the preceding thing )+'b.nk' bank, bonk, b nk, ... ( . matches any character )++ Some other queries:++desc:'amazon|amzn|audible' Amazon transactions+cur:EUR amounts with commodity symbol EUR+cur:\\$ amounts with commodity symbol $+cur:....? amounts with 3- or 4-character symbols+tag:.=202[1-3] things with any tag whose value contains 2021, 2022 or 2023++ Account name aliases: accept '.' instead of ':' as account separator:++alias /\./=: replaces all periods in account names with colons++ Show multiple top-level accounts combined as one:++--alias='/^[^:]+/=combined' ( [^:] matches any character other than : )++ Show accounts with the second-level part removed:++--alias '/^([^:]+):[^:]+/ = \1'+ match a top-level account and a second-level account+ and replace those with just the top-level account+ ( \1 in the replacement text means "whatever was matched+ by the first parenthesised part of the regexp"++ CSV rules: match CSV records containing dining-related MCC codes:++if \?MCC581[124]++ Match CSV records with a specific amount around the end/start of+month:++if %amount \b3\.99+& %date (29|30|31|01|02|03)$++* Menu:++* hledger's regular expressions::+++File: hledger.info, Node: hledger's regular expressions, Up: Regular expressions++37.3.1 hledger's regular expressions+------------------------------------++hledger's regular expressions come from the regex-tdfa library. If+they're not doing what you expect, it's important to know exactly what+they support:++ 1. they are case insensitive+ 2. they are infix matching (they do not need to match the entire thing+ being matched)+ 3. they are POSIX ERE (extended regular expressions)+ 4. they also support GNU word boundaries ('\b', '\B', '\<', '\>')+ 5. backreferences are supported when doing text replacement in account+ aliases or CSV rules, where backreferences can be used in the+ replacement string to reference capturing groups in the search+ regexp. Otherwise, if you write '\1', it will match the digit '1'.+ 6. they do not support lazy quantifiers ('*?'), mode modifiers+ ('(?s)'), character classes ('\w', '\d'), or anything else not+ mentioned above.+ 7. they may not (I'm guessing not) properly support right-to-left or+ bidirectional text.++ Some things to note:++ * In the 'alias' directive and '--alias' option, regular expressions+ must be enclosed in forward slashes ('/REGEX/'). Elsewhere in+ hledger, these are not required.++ * In queries, to match a regular expression metacharacter like '$' as+ a literal character, prepend a backslash. Eg to search for amounts+ with the dollar sign in hledger-web, write 'cur:\$'.++ * On the command line, some metacharacters like '$' have a special+ meaning to the shell and so must be escaped at least once more.+ See Special characters.+++File: hledger.info, Node: Argument files, Next: Shell completions, Prev: Regular expressions, Up: Command line tips++37.4 Argument files+===================++You can save a set of command line options and arguments in a file, and+then use them by writing '@FILE.args' as a hledger command argument.+The '.args' file extension is conventional, but not required. In an+argument file,++ * Each line can contain one argument, flag, or option.+ * Blank lines or lines beginning with '#' are ignored.+ * An option's flag and value should be joined by '='.+ * An option value or an argument may contain spaces. Don't use+ single or double quotes.+ * And generally, use one less level of quoting/escaping than at the+ command line. Eg 'cur:\$', not 'cur:\\$' as on the command line.++ For example:++# cash.args++assets:cash+assets:charles schwab:sweep+cur:\$+-c=$1.++$ hledger bal @cash.args+++File: hledger.info, Node: Shell completions, Prev: Argument files, Up: Command line tips++37.5 Shell completions+======================++If you use the bash, zsh or fish shells, you can optionally set up+context-sensitive autocompletion for hledger command lines. Try+pressing 'hledger<SPACE><TAB><TAB>' (should list all hledger commands)+or 'hledger reg acct:<TAB><TAB>' (should list your top-level account+names). If completions aren't working, or for more details, see Install+> Shell completions.+++File: hledger.info, Node: PART 6 COMMON TASKS, Next: Setting LEDGER_FILE, Prev: Command line tips, Up: Top++38 PART 6: COMMON TASKS+***********************++For a gentle, step by step introduction to hledger - installing,+starting a journal, recording transactions, and running the main reports+- see hledger by example on the website. For a faster tour, see the 5+minute quick start. Here are a few more tasks which aren't covered+there.+++File: hledger.info, Node: Setting LEDGER_FILE, Next: Reconciling, Prev: PART 6 COMMON TASKS, Up: Top++39 Setting LEDGER_FILE+**********************++hledger looks for your accounting data in a journal file,+'$HOME/.hledger.journal' by default. You can override this by setting+the 'LEDGER_FILE' environment variable (see Environment), eg to+'~/finance/main.journal'. Here's how to do that on different systems:++* Menu:++* Set LEDGER_FILE on unix::+* Set LEDGER_FILE on mac::+* Set LEDGER_FILE on Windows::+++File: hledger.info, Node: Set LEDGER_FILE on unix, Next: Set LEDGER_FILE on mac, Up: Setting LEDGER_FILE++39.1 Set LEDGER_FILE on unix+============================++It depends on your shell, but running these commands in the terminal+will work for many people; adapt if needed:++$ echo 'export LEDGER_FILE=~/finance/main.journal' >> ~/.profile+$ source ~/.profile++ When correctly configured:++ * 'env | grep LEDGER_FILE' will show your new setting+ * and so should 'hledger setup' and 'hledger files'.+++File: hledger.info, Node: Set LEDGER_FILE on mac, Next: Set LEDGER_FILE on Windows, Prev: Set LEDGER_FILE on unix, Up: Setting LEDGER_FILE++39.2 Set LEDGER_FILE on mac+===========================++In a terminal window, follow the unix procedure above.++ Note GUI applications started from the Dock or Spotlight, such as a+GUI Emacs, don't see variables set in your shell profile. If needed,+you can set the variable for them too, until the next reboot, with+'launchctl setenv LEDGER_FILE ~/finance/main.journal' (then restart the+application).+++File: hledger.info, Node: Set LEDGER_FILE on Windows, Prev: Set LEDGER_FILE on mac, Up: Setting LEDGER_FILE++39.3 Set LEDGER_FILE on Windows+===============================++It can be easier to create a default file at+'C:\Users\USER\.hledger.journal', and have it include your other files.+See I'm on Windows, how do I keep my files in 'AppData\Roaming' ?++ Otherwise: using the gui is easiest:++ 1. In task bar, search for 'environment variables', and choose "Edit+ environment variables for your account".+ 2. Create or change a 'LEDGER_FILE' setting in the User variables+ pane. A typical value would be+ 'C:\Users\USER\finance\main.journal'.+ 3. Click OK to complete the change.+ 4. And open a new powershell window. (Existing windows won't see the+ change.)++ Or at the command line, you can do it this way:++ 1. In a powershell window, run+ '[Environment]::SetEnvironmentVariable("LEDGER_FILE",+ "C:\User\USER\finance\main.journal",+ [System.EnvironmentVariableTarget]::User)'+ 2. And open a new powershell window. (Existing windows won't see the+ change.)++ Other methods you may find online are often unreliable: they may not+persist, may not affect the current window, or may need administrator+rights or a newer powershell. If you still have trouble, see eg Setting+Windows PowerShell environment variables or Adding path permanently to+windows using powershell doesn't appear to work.++ When correctly configured:++ * in a new powershell window, '$env:LEDGER_FILE' will show your new+ setting+ * and so should 'hledger setup' and (once the file exists) 'hledger+ files'.+++File: hledger.info, Node: Reconciling, Next: Closing a journal file, Prev: Setting LEDGER_FILE, Up: Top++40 Reconciling+**************++Periodically you should reconcile - compare your hledger-reported+balances against external sources of truth, like bank statements or your+bank's website - to be sure that your ledger accurately represents the+real-world balances (and, that the real-world institutions have not made+a mistake!). This gets easy and fast with (1) practice and (2)+frequency. If you do it daily, it can take 2-10 minutes. If you let it+pile up, expect it to take longer as you hunt down errors and+discrepancies.++ A typical workflow:++ 1. Reconcile cash. Count what's in your wallet. Compare with what+ hledger reports ('hledger bal cash'). If they are different, try+ to remember the missing transaction, or look for the error in the+ already-recorded transactions. A register report can be helpful+ ('hledger reg cash'). If you can't find the error, add an+ adjustment transaction. Eg if you have $105 in your wallet but+ hledger says $107, and can't explain the missing $2, it could be:++ 2023-01-16 * adjust cash+ assets:cash $-2 = $105+ expenses:misc++ 2. Reconcile checking. Log in to your bank's website. Compare+ today's (cleared) balance with hledger's cleared balance ('hledger+ bal checking -C'). If they are different, track down the error or+ record the missing transaction(s) or add an adjustment transaction,+ similar to the above. Unlike the cash case, you can usually+ compare the transaction history and running balance from your bank+ with the one reported by 'hledger reg checking -C'. This will be+ easier if you generally record transaction dates quite similar to+ your bank's clearing dates.++ 3. Repeat for other asset/liability accounts.++ Tip: an institution's numbers can be rounded differently in different+places - its website, its CSV or other exports, its emailed and paper+statements. Choose one as your reference (usually the official+statement), and aim to reproduce its numbers: adjust hledger's display+precision with '-c' or '--round' (see Display rounding), and record any+small remaining differences with an adjustment transaction, eg to an+'expenses:rounding' account.++ Tip: instead of the register command, use hledger-ui to see a+live-updating register while you edit the journal: 'hledger-ui+--register checking -C'++ After reconciling, it could be a good time to mark the reconciled+transactions' status as "cleared and confirmed", if you want to track+that, by adding the '*' marker after the date.++ If you're using version control, this can be a good time to commit:++$ git commit -m 'txns' 2023.journal+++File: hledger.info, Node: Closing a journal file, Next: hledger 1 and hledger 2, Prev: Reconciling, Up: Top++41 Closing a journal file+*************************++At the end of the year, you may want to continue your journal in a new+file, so that old transactions don't slow down or clutter your reports,+and to help ensure the integrity of your accounting history. See the+close command.++ If using version control, don't forget to 'git add' the new file.+++File: hledger.info, Node: hledger 1 and hledger 2, Next: BUGS, Prev: Closing a journal file, Up: Top++42 hledger 1 and hledger 2+**************************++hledger 2 (the 1.99.x previews, and 2.0 when released) reads hledger 1+data, and most hledger 1 journals work unchanged. hledger 1 (1.52.x)+continues to receive essential fixes, and both can be installed side by+side (eg by renaming the hledger 1 executable to 'hledger1').++ To upgrade from hledger 1:++ 1. Back up your data files, or commit them to version control.+ 2. Run 'hledger check' with hledger 2. If you import CSV, also run+ your usual import command with '--dry-run'.+ 3. Compare your usual reports with hledger 1's (eg 'hledger1 bs' and+ 'hledger bs'), and investigate any differences.++ Things that can need attention include cost basis annotations like+'{$50}', which hledger 1 ignored but hledger 2 uses to track lots, and a+few checks that are now stricter. Upgrading to hledger 2 describes them+all, with fixes, and how to switch back, or keep data usable with both+versions.+++File: hledger.info, Node: BUGS, Prev: hledger 1 and hledger 2, Up: Top++43 BUGS+*******++We welcome bug reports in the hledger issue tracker+(https://bugs.hledger.org), or on the hledger chat or mail list+(https://hledger.org/support).++ Some known issues and limitations:++ hledger uses the system's text encoding when reading non-ascii text.+If no system encoding is configured, or if the data's encoding is+different, hledger will give an error. (See Text encoding and+Troubleshooting.)++ On Microsoft Windows, depending what kind of terminal window you use,+non-ascii characters, ANSI text formatting, and/or the add command's TAB+key, may not be fully supported. (For best results, try a powershell+window.)++ When showing colour, hledger sometimes asks the terminal for its+background colour, to choose colours that suit it (for headings, and for+charts in terminals advertising 24-bit colour). Occasionally this can+misbehave: a terminal that doesn't answer (eg some tmux setups) can+delay the output by up to half a second; over a slow connection, a late+answer may appear as stray characters at your shell prompt; on macOS,+hledger can hang if its input is explicitly redirected from '/dev/tty';+and hledger may be stopped if it is run in the background. '--color=no'+avoids these.++ When processing large data files, hledger uses more memory than+Ledger. You can cap its memory use with GHC runtime system options, eg+'hledger +RTS -M2G -RTS ...' (if it needs more, it will stop with an+error), and see memory and garbage collection statistics with '+RTS -s+-RTS'. To use less memory at some cost in speed, add '+RTS -c -RTS' to+use the compacting garbage collector; on large journals this can reduce+memory use by 20-40%, while running 40-60% slower. (A RTS '-M' limit+also enables this automatically, as memory use approaches the limit.) A+multi-period report with more than 10,000 periods, or a '--forecast'+that would generate more than 100,000 transactions (which in practice+means a mistyped date somewhere, making the report or the forecast span+thousands of years), prints a warning before starting, since it may need+a lot of memory, so that you can cancel it.++* Menu:++* Troubleshooting::+++File: hledger.info, Node: Troubleshooting, Up: BUGS++43.1 Troubleshooting+====================++Here are some common issues you might encounter when you run hledger,+and how to resolve them (and remember also you can usually get quick+Support):++ *PATH issues: I get an error like "No command 'hledger' found"*+Depending how you installed hledger, the executables may not be in your+shell's PATH. Eg on unix systems, stack installs hledger in+'~/.local/bin' and cabal installs it in '~/.cabal/bin'. You may need to+add one of these directories to your shell's PATH, and/or open a new+terminal window.++ *LEDGER_FILE issues: I configured LEDGER_FILE but hledger is not+using it*++ * 'LEDGER_FILE' should be a real environment variable, not just a+ shell variable. Eg on unix, the command 'env | grep LEDGER_FILE'+ should show it. You may need to use 'export' (see+ https://stackoverflow.com/a/7411509). On Windows,+ '$env:LEDGER_FILE' should show it.+ * You may need to force your shell to see the new configuration. A+ simple way is to close your terminal window and open a new one.++ *Text decoding issues: I get errors like "Illegal byte sequence" or+"Invalid or incomplete multibyte or wide character" or+"commitAndReleaseBuffer: invalid argument (invalid character)"*+hledger usually needs its input to be decodable with the system locale's+text encoding. See Text encoding and Install: Text encoding.++ *COMPATIBILITY ISSUES: hledger gives an error with my Ledger file*+Not all of Ledger's journal file syntax or feature set is supported.+See hledger and Ledger for full details.+++Tag Table:+Node: Top208+Node: PART 1 USER INTERFACE5255+Node: Input5394+Node: Text encoding6486+Node: Data formats7235+Node: Standard input8969+Node: Multiple files9358+Node: Strict mode10127+Node: Commands10961+Node: Add-on commands12498+Node: Options13928+Node: Config files22803+Node: Command aliases24599+Node: Config file troubleshooting27037+Node: Environment28568+Node: PART 2 COMMANDS30583+Node: User interface commands33329+Node: help33549+Node: repl36407+Node: Examples39337+Node: run39967+Node: Examples 243927+Node: ui44949+Node: web45099+Node: Data entry commands45235+Node: add45433+Node: add and balance assertions49161+Node: add and balance assignments49692+Node: get50521+Node: Phase 1 transactions data51222+Node: Phase 2 prices51623+Node: Merging new prices52625+Node: get's helper scripts53489+Node: getdata53778+Node: getprices54453+Node: import55400+Node: Default import sources57296+Node: Fetching new data first58294+Node: Import dry run58769+Node: Overlap detection60018+Node: First import62902+Node: Importing balance assignments64095+Node: Import and commodity styles65148+Node: Import archiving65580+Node: Import special cases66618+Node: Multiple journals in the same directory66913+Node: Import configurations to avoid67609+Node: Deduplication68583+Node: Varying file name69111+Node: Multiple versions69493+Node: Report commands70598+Node: accounts71048+Node: activity74308+Node: aregister77586+Node: aregister and posting dates84644+Node: balance85685+Node: balance features92921+Node: Simple balance report94997+Node: Balance report line format96805+Node: Filtered balance report99299+Node: List or tree mode99816+Node: Depth limiting103300+Node: Dropping top-level accounts104065+Node: Showing declared accounts104573+Node: Sorting by amount105301+Node: Percentages106153+Node: Multi-period balance report106858+Node: Balance change end balance109706+Node: Balance report modes111341+Node: Calculation mode112018+Node: Accumulation mode113397+Node: Valuation mode114496+Node: Combining balance report modes115838+Node: Budget report117795+Node: Using the budget report120101+Node: Budget date surprises122757+Node: Selecting budget goals124119+Node: Budgeting vs forecasting125065+Node: Balance report layout126740+Node: Wide layout128373+Node: Tall layout130776+Node: Bare layout132080+Node: Barewide layout134146+Node: Tidy layout136274+Node: Balance report output137820+Node: Balance charts139099+Node: Some useful balance reports149004+Node: balancesheet150389+Node: balancesheetequity157066+Node: cashflow164112+Node: codes170580+Node: commodities171594+Node: descriptions173724+Node: files174189+Node: holdings177611+Node: Gains during a period189926+Node: Holdings over time192267+Node: Holdings charts194262+Node: incomestatement196735+Node: notes203285+Node: payees203801+Node: prices205254+Node: prices summary207518+Node: print208533+Node: print explicitness212389+Node: print layout213543+Node: print amount style214591+Node: print parseability215921+Node: print export mode217989+Node: print other features221276+Node: print output format222237+Node: register226312+Node: Custom register output234926+Node: Register charts236140+Node: roi237098+Node: Spaces and special characters in --inv and --pnl241495+Node: Semantics of --inv and --pnl242229+Node: Using roi with lots245200+Node: IRR and TWR explained245893+Node: Checking the results251898+Node: stats254718+Node: tags256801+Node: transactions258947+Node: Maintenance commands259717+Node: setup259932+Node: init261909+Node: check264797+Node: Default checks266039+Node: Strict checks267932+Node: Other checks269150+Node: Assert rules270994+Node: Custom checks271882+Node: diff272232+Node: Data generation commands273425+Node: close273636+Node: close --clopen276937+Node: close --close278833+Node: close --open279357+Node: close --assert279607+Node: close --assign279934+Node: close --retain280613+Node: close customisation281470+Node: close and balance assertions283809+Node: close examples285529+Node: Retain earnings285766+Node: Migrate balances to a new file286269+Node: More detailed close examples287631+Node: rewrite287853+Node: Re-write rules in a file290847+Node: Diff output format292148+Node: rewrite vs print --auto294805+Node: PART 3 DATA FORMATS295519+Node: Journal295677+Node: Journal cheatsheet298119+Node: Comments304372+Node: Transactions305493+Node: Dates306632+Node: Simple dates306786+Node: Posting dates307379+Node: Status308666+Node: Code310434+Node: Description311048+Node: Payee and note311737+Node: Transaction comments312751+Node: Postings313269+Node: Debits and credits314587+Node: Account names315148+Node: Two space delimiter316220+Node: Account hierarchy317549+Node: Other account name features318434+Node: Amounts318854+Node: Decimal marks319862+Node: Digit group marks320926+Node: Commodity321629+Node: Costs323087+Node: Cost basis325413+Node: Balance assertions326789+Node: Assertions and ordering328201+Node: Assertions and multiple files328922+Node: Assertions and costs329845+Node: Assertions and commodities330494+Node: Assertions and subaccounts332155+Node: Assertions and lot subaccounts332826+Node: Assertions and status333899+Node: Assertions and virtual postings334325+Node: Assertions and auto postings334692+Node: Assertions and precision335569+Node: Assertions and hledger add336057+Node: Posting comments336415+Node: Tags336940+Node: Tag propagation338472+Node: Displaying tags339973+Node: When to use tags ?340368+Node: Tag names341034+Node: Tag values343677+Node: Directives343995+Node: Directive scopes344472+Node: Combining file trees346349+Node: Directives summary347814+Node: account directive351740+Node: Account comments353188+Node: Account tags353777+Node: Account aliases354248+Node: Account error checking356229+Node: Account display order358007+Node: Account types359207+Node: alias directive363813+Node: Basic aliases365110+Node: Regex aliases366022+Node: --alias option367068+Node: Combining aliases367988+Node: Aliases and multiple files369526+Node: end aliases directive370587+Node: Aliases can generate bad account names370991+Node: Aliases and account types371826+Node: assert directive372720+Node: How assert rules work378329+Node: Tips for writing assert rules382224+Node: comment directive384234+Node: end comment directive384558+Node: commodity directive384787+Node: Commodity directive syntax385813+Node: Commodity tags387853+Node: Commodity aliases388387+Node: Commodity units389723+Node: Commodity aliases or market prices?391312+Node: Commodity alias scope391949+Node: Commodity error checking392886+Node: decimal-mark directive393326+Node: include directive394834+Node: P directive398022+Node: payee directive399058+Node: tag directive399675+Node: Periodic transactions400281+Node: Periodic rule syntax401751+Node: Periodic rules and relative dates402577+Node: Two spaces between period expression and description!403356+Node: Auto postings404319+Node: Auto postings and multiple files407607+Node: Auto postings and dates408014+Node: Auto postings and transaction balancing / inferred amounts / balance assertions408457+Node: Auto posting tags409248+Node: Auto postings on forecast transactions only410145+Node: Other syntax410617+Node: Amount expressions411457+Node: Amount expression syntax412516+Node: Amount expression rounding414085+Node: Amount expressions are not kept416396+Node: Balance assignments416863+Node: Balance assignments and costs418460+Node: Balance assignments and subaccounts418881+Node: Balance assignments and multiple files420056+Node: Bracketed posting dates420487+Node: D directive421187+Node: apply account directive423032+Node: Y directive424319+Node: apply year directive425298+Node: Secondary dates426125+Node: Star comments427621+Node: Valuation expressions428025+Node: Virtual postings428328+Node: Other Ledger directives429956+Node: Ledger virtual costs430854+Node: Ledger cost basis431198+Node: CSV431739+Node: CSV rules cheatsheet434079+Node: Finding the data436481+Node: source437978+Node: Data cleaning / data generating commands439502+Node: archive442056+Node: File Extension443036+Node: Reading CSV from standard input443769+Node: Reading multiple CSV files444155+Node: Reading the data444767+Node: Valid CSV445296+Node: separator446144+Node: encoding446821+Node: skip447588+Node: date-format448259+Node: timezone449223+Node: decimal-mark450368+Node: newest-first451103+Node: intra-day-reversed451839+Node: CSV fields and hledger fields452437+Node: fields454269+Node: Field assignment456089+Node: Functions457689+Node: Referencing other fields461360+Node: hledger fields463422+Node: date field464023+Node: date2 field464289+Node: status field464487+Node: code field464680+Node: description field465056+Node: comment field465515+Node: account field466075+Node: amount field466797+Node: Setting amounts469899+Node: Amount signs472323+Node: Amount decimal places473686+Node: currency field474894+Node: Setting currency/commodity476125+Node: balance field477396+Node: balance-type477914+Node: if478742+Node: Matchers480550+Node: Multiple matchers482640+Node: Match groups483390+Node: Regular expressions in CSV rules484296+Node: ifs485747+Node: end489390+Node: merge489761+Node: include492591+Node: Working with CSV493342+Node: CSV rules examples493689+Node: Rapid feedback494078+Node: Well factored rules494700+Node: Deduplicating importing495211+Node: Valid transactions496505+Node: How CSV rules are evaluated497292+Node: Timeclock500481+Node: Timedot504552+Node: Timedot examples508561+Node: PART 4 CONCEPTS510641+Node: Time periods510775+Node: Report start & end date511020+Node: Smart dates512496+Node: Report intervals514867+Node: Date adjustments515441+Node: Start date adjustment515664+Node: End date adjustment516528+Node: Period expressions517277+Node: Period expressions with a report interval519412+Node: More complex report intervals519860+Node: Multiple weekday intervals521976+Node: Queries522987+Node: Query types525931+Node: acct query526570+Node: amt query526881+Node: balance and change queries527963+Node: code query533473+Node: cur query533685+Node: desc query534425+Node: date query534608+Node: date2 query535222+Node: depth query535563+Node: find query535899+Node: note query537191+Node: payee query537458+Node: real query537739+Node: status query537944+Node: type query538184+Node: tag query538786+Node: Negative queries539622+Node: not query539804+Node: Space-separated queries540091+Node: Boolean queries540779+Node: expr query541720+Node: any query542449+Node: all query543464+Node: Queries and command options544191+Node: Queries and account aliases544639+Node: Queries and valuation545063+Node: Depth545670+Node: Combining depth options546638+Node: Pivoting547588+Node: Report titles549891+Node: Languages551256+Node: Amount arithmetic553940+Node: Where hledger divides555175+Node: Transaction balancing560108+Node: How balancing is checked560851+Node: Where imbalances come from562276+Node: Accumulated imbalances563028+Node: Showing imbalances564152+Node: Avoiding imbalances567015+Node: Transaction balancing before 150567710+Node: Amount formatting568868+Node: Commodity display style569161+Node: Commodity style override571034+Node: Display rounding572131+Node: Trailing decimal marks572785+Node: Amount parseability573656+Node: Cost reporting575265+Node: Recording costs576057+Node: Reporting at cost577814+Node: Equity conversion postings579184+Node: Inferring equity conversion postings581963+Node: Combining costs and equity conversion postings584245+Node: Requirements for detecting equity conversion postings585586+Node: Value reporting587245+Node: -X Value in specified commodity588210+Node: -V Value in default commoditys589336+Node: Valuation date590073+Node: Finding market price590905+Node: --infer-market-prices market prices from transactions592979+Node: Valuation commodity596003+Node: --value Flexible valuation597436+Node: Valuation examples600053+Node: Interaction of valuation and queries602197+Node: Effect of valuation on reports602914+Node: Lots and capital gains610685+Node: First lots example612682+Node: Writing lot entries616706+Node: Cost basis annotations617506+Node: Lotful commodities618721+Node: Lot subaccounts619489+Node: Several ways to write lot entries620757+Node: Disabling lot tracking622354+Node: Lot movements624052+Node: Acquire625100+Node: Basis and transacted cost must agree627419+Node: Capitalising fees630078+Node: Transfer630799+Node: Transfer fees632021+Node: Transfers recorded in two entries633291+Node: Dispose634595+Node: Short positions636019+Node: Other lot events638543+Node: Cost basis methods639023+Node: Changing the cost basis method642677+Node: Gains644223+Node: Gain accounts646101+Node: Recording gains647474+Node: Lot reports649718+Node: Realised gains650497+Node: Unrealised gains651727+Node: Lot details653903+Node: Lot labels654183+Node: Cost basis precision655139+Node: Lot postings and balance assertions656182+Node: Troubleshooting lots657217+Node: Generating data659392+Node: Forecasting661227+Node: --forecast661883+Node: Inspecting forecast transactions662984+Node: Forecast reports664317+Node: Forecast tags665426+Node: Forecast period in detail666046+Node: Forecast troubleshooting667134+Node: Budgeting668205+Node: Posting types668760+Node: PART 5 MORE ABOUT THE COMMAND LINE671553+Node: Output671744+Node: Output destination671957+Node: Output format673517+Node: Text output675469+Node: Box-drawing characters676665+Node: Colour677167+Node: Paging677898+Node: HTML output679441+Node: CSV / TSV output680227+Node: FODS output680483+Node: Ledger output681417+Node: Beancount output681969+Node: SQL output686694+Node: JSON output687435+Node: SVG output688161+Node: Debug output688825+Node: Built-in tests689966+Node: Charts690657+Node: Command line tips692185+Node: Special characters692554+Node: Escaping shell special characters693556+Node: Escaping regular expression special characters694917+Node: Escaping in other situations696434+Node: Unicode characters697734+Node: Regular expressions699167+Node: hledger's regular expressions702359+Node: Argument files704032+Node: Shell completions704946+Node: PART 6 COMMON TASKS705455+Node: Setting LEDGER_FILE705903+Node: Set LEDGER_FILE on unix706419+Node: Set LEDGER_FILE on mac706934+Node: Set LEDGER_FILE on Windows707488+Node: Reconciling709139+Node: Closing a journal file711923+Node: hledger 1 and hledger 2712390+Node: BUGS713467+Node: Troubleshooting715701++End Tag Table+++Local Variables:+coding: utf-8+End:
+ embeddedfiles/hledger.md view
@@ -0,0 +1,37 @@+# hledger++> A robust, friendly plain text accounting app.+> See also: `hledger-ui` for TUI, `hledger-web` for web interface.+> More information: <https://hledger.org/hledger.html>.++- Record new transactions interactively, saving to the default journal file:++`hledger add`++- Import new transactions from `bank.csv`, using `bank.csv.rules` to convert:++`hledger import {{path/to/bank.csv}}`++- Print all transactions, reading from multiple specified journal files:++`hledger print --file {{path/to/prices-2024.journal}} --file {{path/to/prices-2023.journal}}`++- Show all accounts, as a hierarchy, and their types:++`hledger accounts --tree --types`++- Show asset and liability account balances, including zeros, hierarchically:++`hledger balancesheet --empty --tree --no-elide`++- Show monthly incomes/expenses/totals, largest first, summarised to 2 levels:++`hledger incomestatement --monthly --row-total --average --sort --depth 2`++- Show the `assets:bank:checking` account's transactions and running balance:++`hledger aregister assets:bank:checking`++- Show the amount spent on food from the `assets:cash` account:++`hledger print assets:cash | hledger -f- -I aregister expenses:food`
+ embeddedfiles/hledger.txt view
@@ -0,0 +1,14535 @@++HLEDGER(1) hledger User Manuals HLEDGER(1)++NAME+ hledger - a robust, friendly plain text accounting app (command line ver-+ sion).++SYNOPSIS+ hledger+ or+ hledger COMMAND [OPTS] [ARGS]++DESCRIPTION+ hledger is a robust, user-friendly, cross-platform set of programs for+ tracking money, time, or any other commodity, using double-entry accounting+ and a simple, editable file format. hledger is inspired by and largely+ compatible with ledger(1), and largely interconvertible with beancount(1).++ This manual is for hledger's command line interface, version 2.0. It also+ describes the common options, file formats and concepts used by all hledger+ programs. It might accidentally teach you some bookkeeping/accounting as+ well! You don't need to know everything in here to use hledger produc-+ tively, but when you have a question about functionality, this doc should+ answer it. It is detailed, so do skip ahead or skim when needed. You can+ read it on hledger.org, or as an info manual or man page on your system.+ You can also open a built-in copy, at a point of interest, by running+ hledger help [TOPIC].++ The main function of the hledger CLI is to read plain text files describing+ financial transactions, crunch the numbers, and print a useful report or+ chart on the terminal (or save it as HTML, CSV, JSON, SQL or SVG). Many+ reports are available, as subcommands. hledger will also detect other+ hledger-* executables as extra subcommands.++ hledger usually reads from (and appends to) a journal file specified by the+ LEDGER_FILE environment variable (defaulting to $HOME/.hledger.journal); or+ you can specify files with -f options. It can also read timeclock files,+ timedot files, or any CSV/SSV/TSV file with a date field.++ Here is a small journal file, describing some starting balances and two+ transactions:++ 2025-01-01 * opening balances+ assets:bank:checking $1000 = $1000+ assets:cash $100 = $100+ liabilities:creditcard $-50 = $-50+ equity:opening/closing balances++ 2025-01-10 * gift received+ income:gifts $-20+ assets:cash $20++ 2025-01-12 farmers market+ assets:cash $-13+ expenses:food $13++ Transactions are dated movements of money (etc.) between two or more ac-+ counts: bank accounts, your wallet, revenue/expense categories, people,+ etc. You can choose any account names you wish, using : to indicate subac-+ counts. There must be at least two spaces between account name and amount.+ Positive amounts are inflow to that account (debit), negatives are outflow+ from it (credit). (Some reports show revenue, liability and equity account+ balances as negative numbers as a result; this is normal.)++ Some details from this example: the first entry records your real-world+ balances on a starting date, with the equity account absorbing the differ-+ ence (its amount is inferred); the = AMOUNT parts are optional balance as-+ sertions, for extra error checking; the * after a date is an optional sta-+ tus mark, meaning "cleared"; and the currency symbols are optional, but a+ good habit.++ hledger's add command can help you add transactions, or you can install+ other data entry UIs like hledger-web or hledger-iadd. For more exten-+ sive/efficient changes, use a text editor: Emacs + ledger-mode, VIM ++ vim-ledger, or VS Code + hledger-vscode are some good choices (see+ https://hledger.org/editors.html).++ To get started, run hledger add and follow the prompts, or save some en-+ tries like the above in $HOME/.hledger.journal, then try commands like:++ $ hledger print -x+ $ hledger aregister assets+ $ hledger balance+ $ hledger balancesheet+ $ hledger incomestatement+ $ hledger incomestatement -M --chart++ Run hledger to list the commands.++ In this manual, we'll cover all of hledger's functionality in detail. For+ a more gentle step by step introduction, see hledger by example, or for a+ faster intro, the 5 minute quick start.++ For tips on configuring a default journal file, reconciling with your bank,+ closing a file at end of year, or migrating between hledger 1 and 2, see+ PART 6: COMMON TASKS.++PART 1: USER INTERFACE+Input+ hledger reads one or more data files, each time you run it. You can spec-+ ify a file with -f, like so++ $ hledger -f FILE [-f FILE2 ...] print++ Files are most often in hledger's journal format, with the .journal file+ extension (.hledger or .j also work); these files describe transactions,+ like an accounting general journal.++ When no file is specified, hledger looks for .hledger.journal in your home+ directory.++ But most people prefer to keep financial files in a dedicated folder, per-+ haps with version control. Also, starting a new journal file each year is+ common (it's not required, but helps keep things fast and organised). So+ we usually configure a different journal file, by setting the LEDGER_FILE+ environment variable, to something like ~/finance/2023.journal. For more+ about how to do that on your system, see Common tasks > Setting+ LEDGER_FILE.++ Text encoding+ hledger expects non-ascii input to be decodable with the system locale's+ text encoding. (For CSV/SSV/TSV files, this can be overridden by the en-+ coding CSV rule.)++ So, trying to read non-ascii files which have the wrong text encoding, or+ when no system locale is configured, will fail. To fix this, configure+ your system locale appropriately, and/or convert the files to your system's+ text encoding (using iconv on unix, or powershell or notepad on Windows).+ See Install: Text encoding for more tips.++ hledger's output will use the system locale's encoding.++ hledger's docs and example files mostly use UTF-8 encoding.++ Data formats+ Usually the data file is in hledger's journal format, but it can be in any+ of the supported file formats, which currently are:++ Reader: Reads: Automatically used for+ files with extensions:+ -----------------------------------------------------------------------------+ journal hledger journal files and some .journal .j .hledger+ Ledger journals, for transactions .ledger+ timeclock timeclock files, for precise time .timeclock+ logging+ timedot timedot files, for approximate .timedot+ time logging+ csv Comma- or other delimiter-sepa- .csv+ rated values, for data import+ ssv Semicolon separated values .ssv+ tsv Tab separated values .tsv+ rules CSV/SSV/TSV/other separated val- .rules+ ues, alternate way++ These formats are described in more detail below.++ hledger detects the format automatically based on the file extensions shown+ above. If it can't recognise the file extension, it assumes journal for-+ mat. So for non-journal files, it's important to use a recognised file ex-+ tension, so as to either read successfully or to show relevant error mes-+ sages.++ You can also force a specific reader/format by prefixing the file path with+ the format and a colon. Eg, to read a .dat file containing tab separated+ values:++ $ hledger -f tsv:/some/file.dat stats++ Standard input+ The file name - means standard input:++ $ cat FILE | hledger -f- print++ If reading non-journal data in this way, you'll need to write the format as+ a prefix, like timeclock: here:++ $ echo 'i 2009/13/1 08:00:00' | hledger print -f timeclock:-++ Multiple files+ You can specify multiple -f options, to read multiple files as one big+ journal. When doing this, note that certain features (described below)+ will be affected:++ * Balance assertions will not see the effect of transactions in previous+ files. (Usually this doesn't matter as each file will set the corre-+ sponding opening balances.)++ * Some directives will not affect previous or subsequent files.++ If needed, you can work around these by using a single parent file which+ includes the others (this works with CSV files too), or concatenating the+ files into one, eg: cat a.journal b.journal | hledger -f- CMD.++ Strict mode+ hledger checks input files for valid data. By default, the most important+ errors are detected, while still accepting easy journal files without a lot+ of declarations:++ * Are the input files parseable, with valid syntax ?++ * Are all transactions balanced ?++ * Do all balance assertions pass ?++ With the -s/--strict flag, additional checks are performed:++ * Are all accounts posted to, declared with an account directive ? (Ac-+ count error checking)++ * Are all commodities declared with a commodity directive ? (Commodity er-+ ror checking)++ * Are all commodity conversions declared explicitly ?++ You can use the check command to run individual checks - the ones listed+ above and some more.++Commands+ hledger provides various subcommands for getting things done. Most of+ these commands do not change the journal file; they just read it and output+ a report. A few commands assist with adding data and file management.+ Some commands to start with:++ * hledger add - add transactions, with interactive prompts++ * hledger print - show journal entries++ * hledger aregister assets:checking (areg) - show one account's transac-+ tions and running balance++ * hledger balancesheet (bs) - show assets, liabilities and net worth++ * hledger incomestatement (is) - show revenues and expenses++ To show a summary of commands, run hledger with no arguments. See also+ PART 2: COMMANDS below.++ To use a particular command, run hledger CMD [CMDOPTS] [CMDARGS],++ * CMD is the full command name, or its standard abbreviation shown in the+ commands list, or any unambiguous prefix of the name.++ * CMDOPTS are command-specific options, if any. Command-specific options+ must be written after the command name. Eg: hledger print -x.++ * CMDARGS are additional arguments to the command, if any. Most hledger+ commands accept arguments representing a query, to limit the data in some+ way. Eg: hledger reg assets:checking.++ To list a command's options, arguments, and documentation in the terminal,+ run hledger CMD -h. Eg: hledger bal -h.++ Add-on commands+ In addition to the built-in commands, you can install add-on commands,+ which will also appear in hledger's commands list. Some of these can be+ installed as separate packages; others can be found in hledger's bin/ di-+ rectory, documented at https://hledger.org/scripts.html.++ Add-on commands are programs or scripts in your shell's PATH, whose name+ starts with "hledger-" and ends with no extension or a recognised extension+ (".bat", ".com", ".exe", ".hs", ".js", ".lhs", ".lua", ".php", ".pl",+ ".py", ".rb", ".rkt", or ".sh"), and (on unix and mac) which has executable+ permission for the current user.++ You can run add-on commands directly: hledger-ui --watch.++ Or you can run them with hledger, like built-in commands: hledger ui+ --watch. In this case hledger's config file will be used, so you can set+ custom options for the addon there. (Before hledger 1.50, an -- argument+ was needed before addon options, but not any more.)++ Arguments written after the command name are passed on to the add-on un-+ changed, except for the options specific to the hledger CLI (--conf,+ --no-conf, -n), which hledger consumes. To send one of those to the add-on+ instead, write it after a -- argument: hledger ui -- -n. hledger consumes+ only that first --; later ones are passed on like any other argument.++Options+ Run hledger -h to see general command line help. Options can be written+ either before or after the command name. These options are specific to the+ hledger CLI:++ Flags:+ --conf=CONFFILE Use extra options defined in this config file. If+ not specified, searches upward and in XDG config+ dir for hledger.conf (or .hledger.conf in $HOME).+ -n --no-conf ignore any config file++ And the following general options are common to most hledger commands:++ 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.+ --alias=A=B|/RGX/=RPL transform account names from A to B, or by+ replacing regular expression matches+ --auto generate extra postings by applying auto posting+ rules ("=") to all transactions+ --forecast[=PERIOD] Generate extra transactions from periodic rules+ ("~"), from after the latest ordinary transaction+ until 6 months from now. Or, during the specified+ PERIOD (the equals is required). Auto posting rules+ will also be applied to these transactions. In+ hledger-ui, also make future-dated transactions+ visible at startup.+ --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)++ 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 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)+ --date2 match/use secondary dates instead (deprecated)+ -U --unmarked include only unmarked postings/transactions+ -P --pending include only pending postings/transactions+ -C --cleared include only cleared postings/transactions+ (-U/-P/-C can be combined)+ -R --real include only non-virtual postings+ -E --empty Show zero items, which are normally hidden.+ In hledger-ui & hledger-web, do the opposite.+ --depth=DEPTHEXP if a number (or -NUM): show only top NUM levels+ of accounts. If REGEXP=NUM, only apply limiting to+ accounts matching the regular expression.+ -B --cost 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? 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:+ -? 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+ --test[=PATTERN] run built-in tests (those matching PATTERN) and+ exit+ --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++ Usually hledger accepts any unambiguous flag prefix, eg you can write --dry+ instead of --dry-run.++ You can combine short flags which don't take arguments, eg you can write+ -MAST instead of -M -A -S -T. Flags requiring an argument can't be com-+ bined in this way (-If FILE won't work).++ If the same option appears more than once in a command line, usually the+ last (right-most) wins. Similarly, if mutually exclusive flags are used+ together, the right-most wins. (When flags are mutually exclusive, they'll+ usually have a group prefix in --help.)++ With most commands, arguments are interpreted as a hledger query which fil-+ ters the data. Some queries can be expressed either with options or with+ arguments.++ Config files+ You can configure default command line options and arguments conveniently+ in a hledger config file. Config file options will be inserted near the+ start of your command line, so you can override them with command line op-+ tions.++ You can specify a config file with the --conf option. Otherwise, hledger+ will search for a default config file, in this order:++ * hledger.conf in the current directory or above++ * .hledger.conf in your home directory++ * hledger.conf in your XDG config (~/.config/hledger/hledger.conf).++ Only one config file is used. Here's a small example:++ # General options, used with all hledger commands that support them.+ --pretty++ # Command-specific options.+ [print]+ --explicit --infer-costs++ And here is a commented starter config file:+ https://github.com/hledgerorg/hledger/blob/main/hledger.conf.sample++ You can put not only options, but also arguments in a config file.++ You can ignore all config files by adding the -n/--no-conf flag to the com-+ mand line. This is recommended when using hledger in scripts. When both+ --conf and --no-conf options are used, the right-most wins.++ Note, hledger 1 also reads config files, but some things written for+ hledger 2 make it stop with an error: indented lines (including the contin-+ uation lines of a multi-line command alias), a # inside quotes, quotes+ around only part of an argument, and options in a [COMMAND] section which+ that command doesn't have in hledger 1. (hledger 1 ignores single-line+ command aliases, and unknown options in the general section.) In this sit-+ uation, you can run hledger 1 with -n, or give it a separate config file+ with --conf.++ Command aliases+ In a config file you can also define command aliases: your own custom com-+ mands, which expand to a longer command line (similar to git's aliases).+ (Since 1.99.4.) Eg:++ [alias]+ p = print+ p1 = transactions+ rev10 = balance type:R -2 -X$ -p 'every 10 years from 2000'++ With this in your config file, you'll see a rev10 command in the hledger+ help commands list, and hledger rev10 will run the balance command above.+ Options or arguments written at the command line will be added at the end,+ usually overriding those in the alias; eg hledger rev10 -X a will convert+ to a instead of $. Command aliases can also be used in run command scripts+ and at the repl prompt.++ Each line in an [alias] section should look like NAME = COMMAND [ARGS..].+ A command line can be continued on following lines by indenting them more+ than the NAME; the indented lines are joined to the command line. Blank+ lines and comment lines within it are ignored, so you can space it out or+ comment out individual lines. Eg:++ [alias]+ rev10 = balance+ type:R+ -2+ -X$+ -p 'every 10 years from 2000'+ # --drop 1++ (hledger 1 can't read these continuation lines; see Config files.)++ Command aliases override addon commands with the same name, but they can't+ override builtin command names or abbreviations like balance or bal. If+ the same alias name is defined more than once, the last definition wins.++ An alias's command can be a hledger builtin command, addon command, or an-+ other alias. If there's a [COMMAND] options section for an alias's re-+ solved builtin command, that will also be applied.++ Or if an alias's command line begins with !, the rest is run as a shell+ command (with any extra command line arguments appended). Eg:++ [alias]+ git-commit = ! git commit -p+ jj-commit = ! jj commit -i++ For safety, shell command aliases run only if defined in a trusted config+ file: one you gave explicitly with --conf, or your user config file+ (~/.hledger.conf or the XDG hledger.conf). Shell commands in a nearby au-+ tomatically-found hledger.conf, in the current directory or a parent direc-+ tory, will not run - this prevents a config file from an untrusted down-+ loaded or shared directory from running arbitrary shell commands.++ Config file troubleshooting+ A default config file (one which hledger finds and uses automatically,+ without a --conf option) is convenient, but it can surprise you, eg by qui-+ etly changing report output, or breaking scripts which use hledger. Some+ tips:++ 1. Be mindful about what you put in your config file; consider the effect+ on all your reports.++ 2. If a hledger command isn't doing what you expect, try it again with -n,+ to see if a config file is to blame.++ 3. Run hledger setup to list the currently active config file. (setup is+ not affected by config files.)++ 4. Add --debug or --debug=8 to any command to see config/command line debug+ output.++ 5. In scripts, and in examples you share with others, add -n so that a con-+ fig file can't change the result.++ 6. When you download hledger data from elsewhere, watch out for directories+ containing a hledger.conf file.++ 7. If hledger reports an error in a config file which should be fine, you+ might be running an older hledger version. (Since 1.99.6, config file+ errors show the hledger version; with older versions, check which+ hledger executables are in your PATH.)++ 8. A config file with errors doesn't stop help flags like --help or --ver-+ sion from working, unless they're used with a command alias defined in+ that file, in which case the error is reported.++Environment+ These environment variables affect hledger:++ HLEDGER_FASTPATH hledger parses simple journal entries with a special+ fast-path parser, when possible. Setting this to off disables the fast+ path, so that all entries are parsed by the general parser, which could be+ useful to rule out a parser bug. Setting it to check parses each entry+ with both parsers, and reports an error if they disagree. (--debug=1 shows+ how much of a journal was parsed by the fast path.)++ HLEDGER_LESS If less is your pager, this variable specifies the less op-+ tions hledger should use. (Otherwise, LESS + custom options are used.)++ LEDGER_FILE The default journal file, to be used when no -f/--file option+ is provided. For example, it could be ~/finance/main.journal. This can+ also be a glob pattern, eg ./2???.journal. (If the glob matches multiple+ files, only the alphanumerically first one is used.) If LEDGER_FILE points+ to a non-existent file, an error will be raised. If the value is the empty+ string, it is ignored.++ If LEDGER_FILE is not set and -f is not provided, the default journal file+ is $HOME/.hledger.journal (or if a home directory can't be detected,+ ./.hledger.journal).++ See also Common tasks > Setting LEDGER_FILE.++ NO_COLOR If this environment variable exists (with any value, including+ empty), hledger will not use ANSI color codes in terminal output, unless+ overridden by an explicit --color=y or --colour=y option.++ LANGUAGE, LC_ALL, LC_MESSAGES, LANG When the --lang=auto option is used,+ these select the language of report titles and headings, following the+ usual gettext rules: the effective locale is LC_ALL, else LC_MESSAGES, else+ LANG; if that is C, POSIX or unset, English is used; otherwise the lan-+ guages listed in LANGUAGE (colon-separated) are tried first, then the ef-+ fective locale. See Languages.++PART 2: COMMANDS+ Here are hledger's standard commands. You can list these by running+ hledger help commands, or as a more compact list by running hledger. If+ you have installed more add-on commands, they also will be listed.++ In the following command docs, each command's specific options are shown.+ Most commands also support the general options described above, though some+ of them might have no effect. (Usually if there's a sensible way for a+ general option to affect a command, it will.) You can list all of a com-+ mand's options by running hledger CMD -h.++ User interface commands++ * help (h) - show documentation and examples++ * repl - run multiple commands from an interactive prompt++ * run - run multiple commands from a file or command line++ * ui - (if installed) run a terminal UI++ * web - (if installed) run a web UI++ Data entry commands++ * add - add transactions using terminal prompts++ * get - fetch transaction and price data for import++ * import - add new transactions from other files, eg CSV files++ Report commands++ * accounts (acc) - account names++ * activity - transaction or posting counts, as a bar chart++ * aregister (areg) - an account's transactions & running balance++ * balance (bal) - balance changes, end balances, gains, budgets & more++ * balancesheet (bs) - assets, liabilities and net worth++ * balancesheetequity (bse) - assets, liabilities and equity++ * cashflow (cf) - changes in liquid assets++ * codes - transaction codes++ * commodities (comm) - commodity/currency symbols++ * descriptions (desc) - transaction descriptions++ * files - input files used++ * holdings - investment holdings and performance++ * incomestatement (is) - revenues and expenses++ * notes - the note part of transaction descriptions++ * payees - the payee part of transaction descriptions++ * prices - market prices++ * print - transaction entries, or a whole exported journal++ * register (reg) - matched postings & running total, across accounts++ * roi - return on investments++ * stats - journal statistics++ * tags - tag names++ * transactions (tx) - transactions, in compact one-line format++ Maintenance commands++ * setup - check your hledger installation++ * init - create starter journal files++ * check - check that your journal is valid++ * diff - compare an account's transactions in two journals++ Data generation commands++ * close - generate transactions to zero/restore/assert balances++ * rewrite - generate postings by rule, like print --auto++ Next, these commands are described in detail.++User interface commands+ help+ Show some part of hledger's documentation.++ Flags:+ -i use info when showing the manual+ -m use man when showing the manual+ -p use less (or $PAGER) when showing the manual+ -w use a web browser when showing the manual+ -l just list the manual topics matching TOPIC+ --builtins with commands: show only builtin commands+ --addons with commands: show only addon commands+ --aliases with commands: show only command aliases++ The part shown is selected by arguments:++ * quickref (or no args): a quick reference / overview++ * commands: all commands, including addons and aliases (or just one cate-+ gory, with --builtins/--addons/--aliases)++ * usage [CMD]: command line options help (like -h/--help)++ * examples [CMD]: command line examples++ * manual [TOPIC]: view a topic in the manual, or list them all++ * TOPIC: (like manual TOPIC)++ * home|install|relnotes|docs|support|sponsor: browse hledger.org pages++ TOPIC is a section heading in the hledger, hledger-ui or hledger-web man-+ ual, or part of one, matched case insensitively. Enclose it in quotes if+ it contains spaces. With no TOPIC (hledger help manual), all manual topics+ are listed, indented to show (most of) their hierarchy.++ The manual will be shown in a default viewer (info, man, pager, web+ browser), or you can choose with -i/-m/-p/-w.++ The manual is built in to your hledger executable, so it can be useful when+ offline, or when you prefer the terminal to a web browser, or when the ap-+ propriate hledger manual or viewers are not installed properly on your sys-+ tem.++ By default it chooses the best viewer found in $PATH, trying in this order:+ info, man, $PAGER, less, more, stdout. (If a TOPIC is specified, $PAGER+ and more are not tried.) You can force the use of info, man, or a pager+ with the -i, -m, or -p flags. If no viewer can be found, or if running+ non-interactively, it just prints the manual to stdout.++ Examples:++ $ hledger help # show the quick reference+ $ hledger help -h # show the help command's options+ $ hledger help commands # list all commands+ $ hledger help commands --aliases # list just the command aliases+ $ hledger help 'time periods' # show the "Time periods" section in the manual+ $ hledger help keys # show the "KEYS" section in the hledger-ui manual+ $ hledger help -l # list the manual's topics+ $ hledger help -l journal # list the manual topics matching "journal"+ $ hledger help examples add # show examples for the add command++ repl+ Start an interactive prompt for running hledger commands. Input files are+ reloaded only when they change, so commands run faster.++ Flags:+ --no-watch disable automatic reloading of changed input+ files, config aliases and addon commands++ hledger repl starts a read-eval-print loop (REPL) where you can enter com-+ mands interactively. As with the run command, each input file (or each in-+ put file/input options combination) is parsed just once, so commands will+ run more quickly than if you ran them individually at the command line.++ The input file(s) specified for the repl command will be used throughout+ the session; but you can override this temporarily by specifying new -f op-+ tions for a command.++ Before running a command, any input files which have changed on disk are+ automatically reloaded (including CSV rules files). Also command aliases+ are reloaded if the config file has changed, and addon commands are re-de-+ tected if PATH's contents have changed. The --no-watch flag disables all+ of this reloading, so as to work with a stable snapshot of the data, or to+ avoid file/directory polling on a slow network drive.++ Any other general flags given to repl - input, reporting, or display flags+ such as -I, --strict, --alias, -b/-e, --depth, --cost, --value, --color -+ are also applied to every command you run. A command can still override+ them by specifying its own flags.++ The command syntax is the same as with run:++ * enter one hledger command at a time, without the usual hledger first word++ * empty lines and comment text from # to end of line are ignored++ * enclose arguments in quotes if they contain spaces.++ Use help (or h) to show the quick reference, or help commands to list com-+ mands. Addons in PATH and command aliases defined in a config file can+ also be used. Generally repl should feel much like using hledger at the+ command line. But repl requires full command names or official abbrevia-+ tions (it does not recognise ad hoc abbreviations).++ To run a single shell command, type ! SHELLCMD (eg ! ls or ! git status).++ While it is running, the REPL remembers your command history, and you can+ navigate in the usual ways:++ * Keypad or Emacs navigation keys to edit the current command line++ * UP/DOWN or control-P/control-N to step back/forward through history++ * control-R to search for a past command++ * TAB to complete file paths.++ You can type control-C to cancel a long-running command (but only once;+ typing it a second time will exit the REPL).++ In most shells you can type control-Z to temporarily exit to the shell (and+ then fg to return to the REPL).++ To exit the REPL, use control-D or q or quit or exit.++ Examples+ Start the REPL and enter some commands:++ $ hledger repl+ hledger 1.52+ Enter hledger commands. To exit, enter 'quit' or 'exit', or send EOF / control-d.+ 2025> stats+ Main file : .../2025.journal+ ...+ 2025> stats -f 2024/2024.journal+ Main file : .../2024.journal+ ...+ 2025> stats+ Main file : .../2025.journal+ ...++ or:++ $ hledger repl -f some.journal+ hledger 1.52+ Enter hledger commands. To exit, enter 'quit' or 'exit', or send EOF / control-d.+ some> bs+ ...+ some> print -b 'last week'+ ...+ some> bs -f other.journal+ ...++ run+ Run a sequence of hledger commands, provided as files or command line argu-+ ments. Input files are parsed just once, so the commands run faster.++ Flags:+ -O --output-format=FMT select the output format. Supported formats:+ html.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ --view write output to FILE, or to view.FMT in hledger's+ cache directory, and open it in the system's+ default viewer for its format (eg a web browser for+ html). The default format is html.++ You can use run in three ways:++ * hledger run -- CMD1 -- CMD2 -- CMD3 - read commands from the command+ line, separated by --++ * hledger run SCRIPTFILE1 SCRIPTFILE2 - read commands from one or more+ files++ * cat SCRIPTFILE1 | hledger run - read commands from standard input.++ run first loads the input file(s) specified by LEDGER_FILE or by -f op-+ tions, in the usual way. Then it runs each command in turn, each using the+ same input data. But if you want a particular command to use different in-+ put, you can specify an -f option within that command. This will override+ (not add to) the default input, just for that command.++ Any other general flags given to run - input, reporting, or display flags+ such as -I, --strict, --alias, -b/-e, --depth, --cost, --value, --color -+ are also applied to every command it runs. A command can still override+ them by specifying its own flags.++ Each input file (more precisely, each combination of input file and input+ options) is parsed only once. This means that commands will not see any+ changes made to these files, until the next run. But the commands will run+ more quickly than if run individually (typically about twice as fast).++ Command scripts, whether in a file or written on the command line, have a+ simple syntax:++ * each line may contain a single hledger command and its arguments, without+ the usual hledger first word++ * empty lines are ignored++ * text from # to end of line is a comment, and ignored++ * you can use single or double quotes to quote arguments when needed, as on+ the command line++ * these extra commands are available: echo TEXT prints some text (inter-+ preting the backslash escapes \n, \t, \r, \\), and exit or quit ends the+ run.++ On unix systems you can use #!/usr/bin/env hledger run in the first line of+ a command file to make it a runnable script. If that gives an error, use+ #!/usr/bin/env -S hledger run.++ It's ok to use the run command recursively within a command script.++ With -O html, -o FILE.html or --view, run collects the commands' outputs+ into one HTML page instead of printing them: a section for each command,+ headed by its command line, which can be folded; and a heading for each+ echo. Commands which can produce HTML (the balance commands, register,+ aregister, print, holdings, activity) do so, charts included; others' text+ output is shown as is. --view then opens the page in your web browser (see+ Output destination), which is a convenient way to see several reports, or+ charts, at once:++ $ hledger run --view -- echo Overview -- is -M --chart -- bs -Q --chart -- reg expenses -p thismonth++ Command aliases defined in a config file can also be used in command+ scripts.++ You may find some differences in behaviour between run command lines and+ normal hledger command lines. run is a little stricter; eg it requires+ full command names or official abbreviations (as seen in the commands+ list), and command options must be written after the command name.++ Examples+ Run commands from the command line:++ hledger -f some.journal run -- balance assets --depth 2 -- balance liabilities -f /some/other.journal --depth 3 --transpose -- stats++ This would load some.journal, run balance assets --depth 2 on it, then run+ balance liabilities --depth 3 --transpose on /some/other.journal, and fi-+ nally run stats on some.journal++ Run commands from standard input:++ (echo "files"; echo "stats") | hledger -f some.journal run++ Run commands as a script:++ $ cat report+ #!/usr/bin/env -S hledger run -f some.journal++ echo "List of accounts in some.journal"+ accounts++ echo "Assets of some.journal"+ balance assets --depth 2++ echo "Liabilities from /some/other.journal"+ balance liabilities -f /some/other.journal --depth 3 --transpose++ echo "Commands from another.script, applied to another.journal"+ run -f another.journal another.script++ $ chmod +x report+ $ ./report+ List of accounts in some.journal+ ...++ ui+ Runs hledger-ui, a terminal UI (if installed).++ web+ Runs hledger-web, a web UI (if installed).++Data entry commands+ add+ Add new transactions to a journal file, with interactive prompting.++ Flags:+ --no-new-accounts don't allow creating new accounts+ --layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 - right-align amounts, as in hledger 1+ COL - align decimal marks at column COL+ (default: 53)++ Many hledger users edit their journals directly with a text editor, or gen-+ erate them from CSV. For more interactive data entry, there is the add+ command, which prompts interactively on the console for new transactions,+ and appends them to the main journal file (which should be in journal for-+ mat). Existing transactions are not changed. This is one of the few+ hledger commands that writes to the journal file (see also import).++ To use it, just run hledger add and follow the prompts. You can add as+ many transactions as you like; when you are finished, enter . or press con-+ trol-d or control-c to exit.++ Features:++ * add tries to provide useful defaults, using the most similar (by descrip-+ tion) and nearest-dated transaction (filtered by the query, if any) as a+ template.++ * You can also set the initial defaults with command line arguments.++ * Readline-style edit keys can be used during data entry.++ * The tab key will auto-complete whenever possible - accounts, payees/de-+ scriptions, dates (yesterday, today, tomorrow). If the input area is+ empty, it will insert the default value.++ * A parenthesised transaction code may be entered following a date.++ * Comments and tags may be entered following a description or amount.++ * If you make a mistake, enter < at any prompt to go one step backward.++ * Before saving a transaction, add checks that the journal will still be+ readable with it added, as the next read with the same options will check+ it (eg balance assertions must pass, lots must be valid, and with+ --strict, the strict checks must pass). If not, it shows the error and+ goes one step backward, so you can correct the entry. (With a large+ journal this check may take a moment; it runs while you are deciding+ whether to save.)++ * Input prompts are displayed in a different colour when the terminal sup-+ ports it.++ Notes:++ * If you enter a number with no commodity symbol, and you have declared a+ default commodity with a D directive, you might expect add to add this+ symbol for you. It does not do this; we assume that if you are using a D+ directive you prefer not to see the commodity symbol repeated on amounts+ in the journal.++ * add creates entries in journal format; it won't work with timeclock or+ timedot files.++ * There is a known issue on Windows if this hledger version is built from+ stackage: the prompts will show ANSI junk instead of colours (#2410).+ You can avoid this by using official hledger release binaries or by+ building it with haskeline >=0.8.4; or by running add with --color=no,+ perhaps configured in your config file.++ Examples:++ * Record new transactions, saving to the default journal file:++ hledger add++ * Add transactions to 2024.journal, but also load 2023.journal for comple-+ tions:++ hledger add --file 2024.journal --file 2023.journal++ * Provide answers for the first four prompts:++ hledger add today 'best buy' expenses:supplies '$20'++ There is a detailed tutorial at https://hledger.org/add.html.++ add and balance assertions+ You can add a balance assertion by writing AMOUNT = BALANCE when asked for+ an amount. Eg 100 = 500.++ Also, each time you enter a new amount, hledger re-checks all balance as-+ sertions in the journal and rejects the new amount if it would make any of+ them fail. You can run add with -I or --ignore-assertions to disable bal-+ ance assertion checking.++ add and balance assignments+ Adding a new balance assignment+ When entering a posting amount, you can write a = BALANCEAMOUNT balance as-+ signment (or ==, =*, ==*) instead. The posting amount required to produce+ this balance will be calculated automatically. (Since 1.51)++ Adding a posting dated before an existing balance assignment+ add won't let you add a posting dated earlier than an existing balance as-+ signment in that account. (Because it calculates balance assignments only+ once at startup, converting them to assertions, so adding the new amount+ causes an assertion failure.) To work around this, run add with balance+ assertions ignored: hledger add -I.++ get+ Fetch new transactions and market prices for the journal, by running get-+ data and getprices helper scripts. New prices are merged into prices files+ automatically; new transaction data is just saved, for later conversion &+ import by import.++ Flags:+ --transactions fetch transactions only+ --prices fetch prices only+ --dry-run just print the commands that would be run++ By default, this command fetches both transactions and prices.++ Phase 1: transactions data+ 1. Creates a data/ directory next to the main journal file, if it does not+ exist.++ 2. If the data/getdata helper script exists, runs it in the data directory,+ so it can save downloaded files (CSV/TSV/JSON/OFX/etc.) there.++ Phase 2: prices+ 1. Creates a prices/ directory next to the main journal file, if it does+ not exist.++ 2. If the prices/getprices helper script exists, hledger first guesses the+ journal's base currency (the commodity most used as the target in P+ price directives; or if there are no P directives, the commodity most+ used in postings; or if there are no postings, "USD"). Then for each+ other commodity in the journal, it fetches daily market prices in the+ base currency, from that commodity's earliest transaction until today,+ by running getprices BASECUR COMM START END. Each commodity's prices+ are merged into prices/<COMM>.prices, preserving existing prices.++ Commands being run, and files being updated, are logged to stderr. With+ --dry-run, you can preview the commands without running them.++ Merging new prices+ Complete historical price data can be hard to get, so the prices phase is+ careful to preserve older prices. If prices files already exist, the newly+ fetched prices will be merged as follows:++ * Prices files will be updated only if they contain nothing but P direc-+ tives (or blank lines).++ * New prices for dates already seen are discarded. (So if you want to re-+ place old prices, you must delete them before running get.)++ * If no new prices remain to be added, the prices file is left as-is.++ * Otherwise, the old prices plus the new prices are saved to the file, or-+ dered by: date, from commodity, to commodity. Each price keeps the num-+ ber format it was written with.++ get's helper scripts+ Data downloading varies for everyone, and needs to be easily customisable,+ so it is done via helper scripts:++ getdata+ If you want get to download transaction data for you, make your own getdata+ shell script (or executable program), and install it in the data directory+ next to your main journal file.++ It should download zero or more transaction data files into its current di-+ rectory. Anything it prints (on stdout or stderr) is shown on stderr, as+ progress output. These are typically bank/brokerage CSV/TSV/SSV files, but+ could be anything that your hledger rules files can read. The hledger+ repo's getdata is a stub you can start from, with commented examples.++ getprices+ If you want get to download historical market prices (useful for currency+ conversions, and value or gains reports), install a getprices script in the+ prices directory next to your main journal file.++ You can start with the hledger repo's getprices, customising it if needed.+ This script uses pricehist, so you will need to install that python tool+ also (eg with uv tool install pricehist). Some price providers limit the+ commodity pairs, history, or number of requests available for free; you can+ get better data by paying them and setting up their API keys as environment+ variables.++ Or, you can make your own getprices script. It should accept 3-4 argu-+ ments:++ * ISO code for the base currency++ * ISO code for the commodity to be priced++ * ISO start date++ * optional ISO end date (default: today)++ import+ Import new transactions from one or more data files to the main journal.+ Or with no arguments, import from the rules files in rules/.++ Flags:+ -g --get fetch new data first by running the get command+ --catchup just mark all transactions as already imported+ --dry-run just show the transactions to be imported+ --layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 - right-align amounts, as in hledger 1+ COL - align decimal marks at column COL+ (default: 53)++ This command detects new transactions in one or more data files specified+ as arguments, and appends them to the main journal.++ You can import from any input file format hledger supports, but CSV/SSV/TSV+ files, downloaded from financial institutions, are the most common import+ source.++ The import destination is the default journal file, or another specified in+ the usual way with $LEDGER_FILE or -f/--file. It should be in journal for-+ mat.++ Before writing anything, import checks that the journal will still be read-+ able with the new transactions added, as the next read with the same op-+ tions will check it (eg balance assertions must pass, lots must be valid,+ and with --strict, the strict checks must pass). If not, it shows the er-+ ror and imports nothing (and updates no .latest files). A dry run does+ this check too.++ Examples:++ $ hledger import bank1-checking.csv bank1-savings.csv++ $ hledger import *.csv++ Default import sources+ If import is run with no file arguments, it looks in the journal's rules/+ directory (next to the main journal file) and imports from every .rules+ file found there, in alphabetical order. Files whose name begins with . or+ _ are skipped: the _ prefix is for rules files that are either disabled, or+ shared/common rules included by other rules files and not meant to be read+ directly.++ So a typical setup might be:++ ~/finance/2026.journal+ ~/finance/rules/bank1-checking.rules+ ~/finance/rules/bank1-savings.rules+ ~/finance/rules/_common.rules # included by others, not read directly+ ~/finance/rules/_brokerage.rules # disabled++ and hledger import reads bank1-checking.rules then bank1-savings.rules.++ If the rules/ directory does not exist or contains no usable .rules files,+ import reports an error.++ Fetching new data first+ With -g/--get, import runs the get command first, which runs your data/get-+ data and prices/getprices scripts (if any) to download new transaction and+ price data. The import then proceeds normally, with the new transaction+ data (if any) readable by your rules files' source rules.++ Import dry run+ It's useful to preview the import by running first with --dry-run, to san-+ ity check the range of dates being imported, and to check the effect of+ your conversion rules if converting from CSV. Eg:++ $ hledger import bank.csv --dry-run++ A dry run archives no data files and updates no .latest files. With -g,+ the get command does a dry run too. But source rules' data cleaning and+ data generating commands do run, since their output is needed for the pre-+ view; so these should be safe to repeat.++ The dry run output is valid journal format, so hledger can re-parse it. If+ the output is large, you could show just the uncategorised transactions+ like so:++ $ hledger import --dry-run bank.csv | hledger -f- -I print unknown++ You could also run this repeatedly to see the effect of edits to your con-+ version rules:++ $ watchexec -- "hledger import --dry-run bank.csv | hledger -f- -I print unknown"++ Once the conversion and dates look good enough to import to your journal,+ perhaps with some manual fixups to follow, you would do the actual import:++ $ hledger import bank.csv++ Overlap detection+ Reading CSV files is built in to hledger, and not specific to import; so+ you could also import by doing hledger -f bank.csv print >>$LEDGER_FILE.++ But import is easier and provides some advantages. The main one is that it+ avoids re-importing transactions it has seen on previous runs. This means+ you don't have to worry about overlapping data in successive downloads of+ your bank CSV; just download and import as often as you like, and only the+ new transactions will be imported each time.++ We don't call this "deduplication", as it's generally not possible to reli-+ ably detect duplicates in bank CSV. Instead, import remembers the latest+ date processed previously in each CSV file (saving it in a hidden file),+ and skips any records prior to that date. This works well for most+ real-world CSV, where:++ 1. the data file name is stable (does not change) across imports++ 2. the item dates are stable across imports++ 3. the order of same-date items is stable across imports++ 4. the newest items have the newest dates++ (Occasional violations of 2-4 are often harmless; you can reduce the chance+ of disruption by downloading and importing more often.)++ Overlap detection is automatic, and shouldn't require much attention from+ you, except perhaps at first import (see below). But here's how it works:++ * For each FILE being imported from:++ 1. hledger reads a file named .latest.FILE file in the same directory, if+ any. This file contains the latest record date previously imported+ from FILE, in YYYY-MM-DD format. If multiple records with that date+ were imported, the date is repeated on N lines.++ 2. hledger reads records from FILE. If a latest date was found in step+ 1, any records before that date, and the first N records on that date,+ are skipped.++ * After a successful import from all FILEs, without error and without+ --dry-run, hledger updates each FILE's .latest.FILE for next time.++ If this goes wrong, it's relatively easy to repair:++ * You'll notice it before import when you preview with import --dry-run.++ * Or after import when you try to reconcile your hledger account balances+ with your bank.++ * hledger print -f FILE.csv will show all recently downloaded transactions.+ Compare these with your journal. Copy/paste if needed.++ * Update your conversion rules and print again, if needed.++ * You can manually update or remove the .latest file, or use import+ --catchup FILE.++ * Download and import more often, eg twice a week, at least while you are+ learning. It's easier to review and troubleshoot when there are fewer+ transactions.++ First import+ The first time you import from a file, when no corresponding .latest file+ has been created yet, all of the records will be imported.++ But perhaps you have been entering the data manually, so you know that all+ of these transactions are already recorded in the journal. In this case+ you can run hledger import --catchup once. This will create a .latest file+ containing the latest CSV record date, so that none of those records will+ be re-imported.++ Or, if you know that some but not all of the transactions are in the jour-+ nal, you can create the .latest file yourself. Eg, let's say you previ-+ ously recorded foobank transactions up to 2024-10-31 in the journal. Then+ in the directory where you'll be saving foobank.csv, you would create a+ .latest.foobank.csv file containing++ 2024-10-31++ Or if you had three foobank transactions recorded with that date, you would+ repeat the date that many times:++ 2024-10-31+ 2024-10-31+ 2024-10-31++ Then hledger import foobank.csv [--dry-run] will import only the newer+ records.++ Importing balance assignments+ Journal entries added by import will have all posting amounts made explicit+ (like print -x).++ This means that any balance assignments in the imported entries would need+ to be evaluated. But this generally isn't possible, as the main file's ac-+ count balances are not visible during import. So try to avoid generating+ balance assignments with your CSV rules, or importing from a journal that+ contains balance assignments. (Balance assignments are best avoided any-+ way.)++ But if you must use them, eg because your CSV includes only balances: you+ can import with print, which leaves implicit amounts implicit. (print can+ also do overlap detection like import, with the --new flag):++ $ hledger print --new -f bank.csv >> $LEDGER_FILE++ (If you think import should preserve implicit balances, please test that+ and send a pull request.)++ Import and commodity styles+ Amounts in entries added by import will be formatted according to the jour-+ nal's canonical commodity styles, as declared by commodity directives or+ inferred from the journal's amounts.++ Related: CSV > Amount decimal places.++ Import archiving+ When importing from a CSV rules file (hledger import bank.rules), you can+ use the archive rule to enable automatic archiving of the data file.++ After a successful import, the data file specified by source will be moved+ (or data generated by a command will be saved) to an archive directory.+ This can be useful for troubleshooting, detecting variations in your banks'+ CSV data, regenerating entries with improved rules, etc.++ The archive directory is data/archive/, next to the main journal file,+ auto-created. The archive file name will be similar to the rules file,+ with a date added: the original data file's modification date, or today's+ date if the data was command-generated.++ The archive rule also causes import to handle source glob patterns differ-+ ently: when there are multiple matched files, it will pick the oldest, not+ the newest.++ Import special cases+ Multiple journals in the same directory+ You might want to keep each journal you are importing to in its own direc-+ tory. That way, each will have its own rules/, data/, and data/archive/+ directories (if those are used).++ Otherwise, imports to the same-directory journals will potentially use the+ same rules/, data/ and data/archive/ directories (depending on commands and+ rules configuration). This is not necessarily a problem; it might even be+ desirable in some cases. But see below:++ Import configurations to avoid+ A few unusual workflows which you should generally avoid:++ * Don't import from one input file to different journals. The imports'+ overlap detection would overwrite the same .latest.FILE state file. (In+ effect, the journals would compete for the new records.)++ * Don't import from multiple data files on the same day, reusing the same+ rules file for all, with archive enabled. The archived file names in+ data/archive/ would clash, causing some archives to be overwritten.++ * Don't do argument-less hledger import to more than one journal in the+ same directory. That would read from the same files in rules/, poten-+ tially disrupting both overlap detection and archiving.++ Deduplication+ Here are two kinds of "deduplication" which import does not handle (and+ should not, because these can happen legitimately in financial data):++ * Two or more of the new CSV records are identical, and generate identical+ new journal entries.++ * A new CSV record generates a journal entry identical to one(s) already in+ the journal.++ Varying file name+ If you have a download whose file name varies, you could rename it to a+ fixed name after each download. Or you could use a CSV source rule with a+ suitable glob pattern, and import from the .rules file.++ Multiple versions+ Say you download bank.csv, import it, but forget to delete it from your+ downloads folder. The next time you download it, your web browser will+ save it as (eg) bank (2).csv. The source rule's glob patterns are for just+ this situation: instead of specifying source bank.csv, specify source+ bank*.csv. Then hledger -f bank.rules CMD or hledger import bank.rules+ will automatically pick the newest matched file (bank (2).csv).++ Alternately, what if you download, but forget to import or delete, then+ download again ? Now each of bank.csv and bank (2).csv might contain data+ that's not in the other, and not in your journal. In this case, it's best+ to import each of them in turn, oldest first (otherwise, overlap detection+ could cause new records to be skipped). Enabling import archiving ensures+ this. Then hledger import bank.rules; hledger import bank.rules will im-+ port and archive first bank.csv, then bank (2).csv.++Report commands+ accounts+ (acc)++ List the account names used or declared in the journal.++ Flags:+ -u --used list accounts used+ -d --declared list accounts declared+ --undeclared list accounts used but not declared+ --unused list accounts declared but not used+ --find list the first account matched by the first+ argument (a case-insensitive infix regexp)+ --directives show as account directives, for use in journals+ --locations also show where accounts were declared, or first+ used+ --types also show account types when known+ --show-aliases also show account aliases declared with alias:+ tags+ -l --flat list/tree mode: show accounts as a flat list+ (default)+ -t --tree list/tree mode: show accounts as a tree+ --drop=N flat mode: omit N leading account name parts++ This command lists account names - all of them by default, or just the ones+ which have been used in transactions (-u/--used), or declared with account+ directives (-d/--declared), or used but not declared (--undeclared), or de-+ clared but not used (--unused), or just the first one matched by a pattern+ (--find, returning a non-zero exit code if it fails).++ You can add query arguments to select a subset of transactions or accounts.+ Note that transaction-specific query terms like date: will exclude de-+ clared-but-unused accounts, which don't have that field.++ With --directives, it shows valid account directives which could be pasted+ into a journal file, including any account aliases as alias: tags. This is+ useful together with --undeclared when updating your account declarations+ to satisfy hledger check accounts.++ With --locations, it also shows the file and line number of each account's+ declaration, if any, and the account's overall declaration order; these may+ be useful when troubleshooting account display order. For an undeclared+ account, it shows where the account was first used (posted to), if any-+ where.++ With --types, it also shows each account's type, if it's known. (See De-+ claring accounts > Account types.)++ With --show-aliases, it also shows each account's aliases, declared with+ alias: tags. (Aliases from alias directives or --alias options are not+ shown.) Also, account names in the query will match aliases too, so eg+ hledger accounts --show-aliases chk shows the account(s) with an alias con-+ taining chk.++ It shows a flat list by default. With --tree, it uses indentation to show+ the account hierarchy. In flat mode you can add --drop N to omit the first+ few account name components. Account names can be depth-clipped with+ depth:N or --depth N or -N.++ Examples:++ $ hledger accounts+ assets:bank:checking+ assets:bank:saving+ assets:cash+ expenses:food+ expenses:supplies+ income:gifts+ income:salary+ liabilities:debts++ $ hledger accounts --undeclared --directives >> $LEDGER_FILE+ $ hledger check accounts++ activity+ Show a bar chart of transaction counts per week, or other report interval.++ Flags:+ -O --output-format=FMT select the output format. Supported formats:+ txt, svg, html, csv, tsv, json.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ --view write output to FILE, or to view.FMT in hledger's+ cache directory, and open it in the system's+ default viewer for its format (eg a web browser for+ html). The default format is html.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)+ --txns count transactions, showing just the total+ (default)+ --postings count postings, showing each account's count+ -S --sort-amount with --postings, sort accounts by posting count,+ largest first+ -T --total show the total count, below the chart+ -A --average show the average count per period, below the+ chart (and as a line in SVG charts)++ The activity command shows how many transactions there are in each week (or+ with a report interval, each day, month, quarter etc.), as a bar chart.+ Each transaction is one character, unless there are too many to fit, when+ the bars are scaled down. With query arguments, it counts only the trans-+ actions which have at least one matched posting.++ Or with --postings, it shows how many postings there are in each period,+ with each account's postings stacked in its own colour. With query argu-+ ments, it counts only the matched postings. This is a shortcut for balance+ --count --chart, with a weekly interval by default, so it can show charts+ in all the same ways: eg with -1 or other depth limit to show less detail,+ -0 to show just the total count, without the accounts' detail,+ -S/--sort-amount to show the accounts with most postings first. (Transac-+ tion counts show just the total, since a transaction's postings can be in+ several accounts.)++ --txns selects transaction counts explicitly; if both --txns and --postings+ are given, the last one wins.++ Both kinds of chart can be shown in the usual ways, eg with -w/--width to+ set the width, -T/--total and -A/--average to show the total count and the+ average count per period below the chart (in graphical charts, the average+ is also drawn as a dashed line), or -o FILE.svg (or -O svg) for a graphical+ chart.++ Examples:++ $ hledger activity -M -T -A -w 40+ Transaction counts in 2008:++ Jan 1 a+ Feb 0+ Mar 0+ Apr 0+ May 0+ Jun 3 aaa+ Jul 0+ Aug 0+ Sep 0+ Oct 0+ Nov 0+ Dec 1 a++ Total 5, Average 0.4++ $ hledger activity -M --postings -1 -w 40+ Posting counts in 2008:++ a assets a expenses a income+ a liabilities++ Jan 2 aa+ Feb 0+ Mar 0+ Apr 0+ May 0+ Jun 7 aaaaaaa+ Jul 0+ Aug 0+ Sep 0+ Oct 0+ Nov 0+ Dec 2 aa++ aregister+ (areg)++ Show the transactions and running balances in one account, with one entry+ per transaction.++ Flags:+ --txn-dates filter strictly by transaction date, not posting+ date. Warning: this can show a wrong running+ balance.+ --no-elide don't show only 2 commodities per amount+ --cumulative accumulation mode: show running total from report+ start date+ -H --historical accumulation mode: show historical running+ total/balance (includes postings before report+ start date) (default)+ -A --average show running average of transaction amounts+ instead of balance (implies --empty and, unless -H+ is used, --cumulative)+ -r --related show the other accounts in each transaction+ (default)+ --matched show the matched accounts (this account or its+ subaccounts) instead+ --invert display all amounts with reversed sign+ --drop=N omit N leading account name parts+ --heading=YN show heading row above table: yes (default) or no+ -w --width=N set output width (default: terminal width). -wN,M+ sets description width as well.+ --align-all guarantee alignment across all lines (slower)+ -O --output-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ --view write output to FILE, or to view.FMT in hledger's+ cache directory, and open it in the system's+ default viewer for its format (eg a web browser for+ html). The default format is html.+ --chart[=net,SCALE] show a chart: instead of the table (txt), above+ it (html), or as data (csv, tsv, json). net: also+ draw the net total (a line, or marks in text+ charts). SCALE: the amount that fills the chart (eg+ 1000 or 1000 USD; one per commodity), for+ comparable charts.++ aregister shows the overall transactions affecting a particular account+ (and any subaccounts). Each report line represents one transaction in this+ account. Transactions before the report start date are included in the+ running balance (--historical mode is the default). You can suppress this+ behaviour using the --cumulative option.++ This is a more "real world", bank-like view than the register command+ (which shows individual postings, possibly from multiple accounts, not nec-+ essarily in historical mode). As a quick rule of thumb:++ * aregister is best when reconciling real-world asset/liability accounts++ * register is best when reviewing individual revenues/expenses.++ Note this command's non-standard, and required, first argument; it speci-+ fies the account whose register will be shown. You can write the account's+ name, or (to save typing) a case-insensitive infix regular expression+ matching the name, which selects the alphabetically first matched account.+ (For example, if you have assets:personal checking and assets:business+ checking, hledger areg checking would select assets:business checking.)++ Transactions involving subaccounts of this account will also be shown.+ aregister ignores depth limits, so its final total will always match a his-+ torical balance report with similar arguments.++ Any additional arguments are standard query arguments, which will limit the+ transactions shown. Note some queries will disturb the running balance,+ causing it to be different from the account's real-world running balance.++ An example: this shows the transactions and historical running balance dur-+ ing july, in the first account whose name contains "checking":++ $ hledger areg checking date:jul++ Each aregister line item shows:++ * the transaction's date (or the relevant posting's date if different, see+ below)++ * the names of all the other account(s) involved in this transaction (prob-+ ably abbreviated)++ * the total change to this account's balance from this transaction++ * the account's historical running balance after this transaction.++ The account column normally shows the other accounts in each transaction+ (this is also selectable with -r/--related). With --matched, it shows the+ matched accounts instead: this account, or the subaccounts of it that were+ posted to. This is useful when the account has subaccounts, eg:++ $ hledger areg expenses --matched++ shows which expense categories each transaction touched. Any additional+ query arguments also narrow the matched accounts shown. The amounts and+ running balance are the same in both modes.++ Transactions making a net change of zero are not shown by default; add the+ -E/--empty flag to show them.++ The -A/--average flag shows the running average change per transaction, in-+ stead of the running balance, so the last number shown is the average for+ the whole report period. It implies --empty, since zero-change transac-+ tions also affect the average. Unlike aregister's other reports, it is not+ historical by default; add -H to include the transactions before the report+ start date in the average. Like register -A, it works best with a single+ commodity.++ For performance reasons, column widths are chosen based on the first 1000+ lines; this means unusually wide values in later lines can cause visual+ discontinuities as column widths are adjusted. If you want to ensure per-+ fect alignment, at the cost of more time and memory, use the --align-all+ flag.++ By default, aregister shows a heading above the data. However, when re-+ porting in a language different from English, it is easier to omit this+ heading and prepend your own one. For this purpose, use the --heading=no+ option.++ This command also supports the output destination and output format op-+ tions. The output formats supported are txt, csv, tsv, html, fods and+ json.++ With --chart, or with svg output (-o FILE.svg), it shows a chart of the ac-+ count's balance (or running total or average) over time instead. A text+ chart has a row per transaction (for a row per period instead, use a bal-+ ance report with a report interval and -H). An SVG chart draws the balance+ as a line on a time scale. With --chart -O csv (or tsv or json) it shows+ the chart's data. See also Balance charts.++ aregister and posting dates+ aregister always shows one entry (and one date and amount) per transaction.+ (With a single commodity, this means line = one transaction. But+ multi-commodity amounts will be shown with one line per commodity.) But+ sometimes transactions have postings with different dates. Also, not all+ of a transaction's postings may be within the report period. To resolve+ this, aregister shows the earliest of the transaction's date and posting+ dates that is in-period, and the sum of the in-period postings. In other+ words it will show a combined line item with just the earliest date, and+ the running balance will (temporarily, until the transaction's last post-+ ing) be inaccurate. Use register -H if you need to see the individual+ postings.++ There is also a --txn-dates flag, which filters strictly by transaction+ date, ignoring posting dates. This too can cause an inaccurate running+ balance.++ balance+ (bal)++ Show accounts with some kind of summed numeric data: balance changes per+ period, end balances on period end dates, simple capital gains, budget goal+ performance, etc.++ Flags:+ --sum calculation mode: show sum of posting amounts+ (default)+ --valuechange calculation mode: show total change of value+ of period-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ --gain calculation mode: show capital gain/loss+ (historical balance value minus cost basis, or+ transacted cost where there is none)+ --budget[=DESCPAT] calculation mode: show sum of posting amounts+ together with budget goals defined by periodic+ transactions. With a DESCPAT argument (must be+ separated by = not space),+ use only periodic transactions with matching+ description+ (case insensitive substring match).+ --count calculation mode: show the count of postings+ --change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports, default)+ --cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. -b/--begin) to+ column end+ -H --historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date)+ -l --flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth-clipped.+ -t --tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ --drop=N in list mode, omit N leading account name+ parts+ --declared include non-parent declared accounts (best+ used with -E)+ -A --average show a row average column (in multicolumn+ reports)+ -T --row-total show a row total column (in multicolumn+ reports)+ --summary-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ -N --no-total omit the final total row+ --no-elide in tree mode, don't squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without -E)+ --full-names in tree mode, show full account names instead+ of indented leaf names+ --format=FORMATSTR use this custom line format (in simple+ reports)+ -S --sort-amount sort by amount instead of account code/name+ (in flat mode). With multiple columns, sorts by+ the row total, or by row average if that is+ displayed.+ -% --percent express values in percentage of each column's+ total+ -r --related show the other accounts transacted with,+ instead+ --invert display all amounts with reversed sign+ --transpose switch rows and columns (use vertical time+ axis); repeat to cancel+ --layout=ARG how to lay out multi-commodity amounts and the+ overall table:+ 'wide[,W]': commodities on same line, up to W+ wide+ 'tall' : commodities on separate lines+ 'bare' : commodity symbols in a separate+ column+ 'tidy' : each data field in its own column+ --base-url=URLPREFIX in html output, generate links to hledger-web,+ with this prefix. (Usually the base url shown by+ hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, fods, svg.+ -o --output-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ --view write output to FILE, or to view.FMT in+ hledger's cache directory, and open it in the+ system's default viewer for its format (eg a web+ browser for html). The default format is html.+ --chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: grouped (a bar per account type, side by+ side). net: also draw the net total (a line, or+ marks in text charts). SCALE: the amount that+ fills the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)++ balance is one of hledger's oldest and most versatile commands, for listing+ account balances, balance changes, values, value changes and more, during+ one time period or many. Generally it shows a table, with rows represent-+ ing accounts, and columns representing periods.++ Note there are some variants of the balance command with convenient de-+ faults, which are simpler to use: balancesheet, balancesheetequity, cash-+ flow and incomestatement. When you need more control, then use balance.++ balance features+ Here's a quick overview of the balance command's features, followed by more+ detailed descriptions and examples. Many of these work with the other bal-+ ance-like commands as well (bs, cf, is..).++ balance can show..++ * accounts as a list (-l) or a tree (-t)++ * optionally depth-limited (-[1-9])++ * sorted by declaration order and name, or by amount++ ..and their..++ * balance changes (the default)++ * or actual and planned balance changes (--budget)++ * or value of balance changes (-V)++ * or change of balance values (--valuechange)++ * or capital gain/loss (--gain)++ * or balance changes from sibling postings (--related/-r)++ * or postings count (--count)++ ..in..++ * one time period (the whole journal period by default)++ * or multiple periods (-D, -W, -M, -Q, -Y, -p INTERVAL)++ ..either..++ * per period (the default)++ * or accumulated since report start date (--cumulative)++ * or accumulated since account creation (--historical/-H)++ ..possibly converted to..++ * cost (--value=cost[,COMM]/--cost/-B)++ * or market value, as of transaction dates (--value=then[,COMM])++ * or at period ends (--value=end[,COMM])++ * or now (--value=now)++ * or at some other date (--value=YYYY-MM-DD)++ ..with..++ * totals (-T), averages (-A), percentages (-%), inverted sign (--invert)++ * rows and columns swapped (--transpose)++ * another field used as account name (--pivot)++ * custom-formatted line items (single-period reports only) (--format)++ * commodities displayed on the same line or multiple lines (--layout)++ * a chart instead of a table (--chart)++ This command supports the output destination and output format options,+ with output formats txt, csv, tsv, json, html, fods, and svg. In txt out-+ put in a colour-supporting terminal, negative amounts are shown in red.++ Simple balance report+ With no arguments, balance shows a list of all accounts and their change of+ balance - ie, the sum of posting amounts, both inflows and outflows - dur-+ ing the entire period of the journal. ("Simple" here means just one column+ of numbers, covering a single period. You can also have multi-period re-+ ports, described later.)++ For real-world accounts, these numbers will normally be their end balance+ at the end of the journal period; more on this below.++ Accounts are sorted by declaration order if any, and then alphabetically by+ account name. For instance (using examples/sample.journal):++ $ hledger -f examples/sample.journal bal+ $1 assets:bank:saving+ $-2 assets:cash+ $1 expenses:food+ $1 expenses:supplies+ $-1 income:gifts+ $-1 income:salary+ $1 liabilities:debts+ --------------------+ 0++ Accounts with a zero balance (and no non-zero subaccounts, in tree mode -+ see below) are hidden by default. Use -E/--empty to show them (revealing+ assets:bank:checking here):++ $ hledger -f examples/sample.journal bal -E+ 0 assets:bank:checking+ $1 assets:bank:saving+ $-2 assets:cash+ $1 expenses:food+ $1 expenses:supplies+ $-1 income:gifts+ $-1 income:salary+ $1 liabilities:debts+ --------------------+ 0++ The total of the amounts displayed is shown as the last line, unless+ -N/--no-total is used.++ Balance report line format+ For single-period balance reports displayed in the terminal (only), you can+ use --format FMT to customise the format and content of each line. Eg:++ $ hledger -f examples/sample.journal balance --format "%20(account) %12(total)"+ assets $-1+ bank:saving $1+ cash $-2+ expenses $2+ food $1+ supplies $1+ income $-2+ gifts $-1+ salary $-1+ liabilities:debts $1+ ---------------------------------+ 0++ The FMT format string specifies the formatting applied to each account/bal-+ ance pair. It may contain any suitable text, with data fields interpolated+ like so:++ %[MIN][.MAX](FIELDNAME)++ * MIN pads with spaces to at least this width (optional)++ * MAX truncates at this width (optional)++ * FIELDNAME must be enclosed in parentheses, and can be one of:++ * depth_spacer - a number of spaces equal to the account's depth, or if+ MIN is specified, MIN * depth spaces.++ * account - the account's name++ * total - the account's balance/posted total, right justified++ Also, FMT can begin with an optional prefix to control how multi-commodity+ amounts are rendered:++ * %_ - render on multiple lines, bottom-aligned (the default)++ * %^ - render on multiple lines, top-aligned++ * %, - render on one line, comma-separated++ There are some quirks. Eg in one-line mode, %(depth_spacer) has no effect,+ instead %(account) has indentation built in. Experimentation may be needed+ to get pleasing results.++ Some example formats:++ * %(total) - the account's total++ * %-20.20(account) - the account's name, left justified, padded to 20 char-+ acters and clipped at 20 characters++ * %,%-50(account) %25(total) - account name padded to 50 characters, total+ padded to 20 characters, with multiple commodities rendered on one line++ * %20(total) %2(depth_spacer)%-(account) - the default format for the sin-+ gle-column balance report. The total field keeps this 20-character width+ as a minimum, but widens automatically when displayed amounts need more+ room.++ Filtered balance report+ You can show fewer accounts, a different time period, totals from cleared+ transactions only, etc. by using query arguments or options to limit the+ postings being matched. Eg:++ $ hledger -f examples/sample.journal bal --cleared assets date:200806+ $-2 assets:cash+ --------------------+ $-2++ List or tree mode+ By default, or with -l/--flat, accounts are shown as a flat list with their+ full names visible, as in the examples above.++ With -t/--tree, the account hierarchy is shown, with subaccounts' "leaf"+ names indented below their parent:++ $ hledger -f examples/sample.journal balance+ $-1 assets+ $1 bank:saving+ $-2 cash+ $2 expenses+ $1 food+ $1 supplies+ $-2 income+ $-1 gifts+ $-1 salary+ $1 liabilities:debts+ --------------------+ 0++ Notes:++ * "Boring" accounts are combined with their subaccount for more compact+ output, unless --no-elide is used. Boring accounts have no balance of+ their own and just one subaccount (eg assets:bank and liabilities above).++ * All balances shown are "inclusive", ie including the balances from all+ subaccounts. Note this means some repetition in the output, which re-+ quires explanation when sharing reports with non-plaintextaccount-+ ing-users. A tree mode report's final total is the sum of the top-level+ balances shown, not of all the balances shown.++ * Each group of sibling accounts (ie, under a common parent) is sorted sep-+ arately.++ In list mode, --no-elide shows parent accounts as well, with their exclu-+ sive balances. These are zero unless the parent has postings of its own,+ so -E/--empty is usually also needed to make them visible. Together, these+ flags guarantee a complete table of all posted-to accounts and their par-+ ents, with full names:++ $ hledger -f examples/sample.journal balance --no-elide -E+ 0 assets+ 0 assets:bank+ 0 assets:bank:checking+ $1 assets:bank:saving+ $-2 assets:cash+ 0 expenses+ $1 expenses:food+ $1 expenses:supplies+ 0 income+ $-1 income:gifts+ $-1 income:salary+ 0 liabilities+ $1 liabilities:debts+ --------------------+ 0++ This can be useful eg when exporting to a spreadsheet which will look up+ balances by account name.++ In tree mode, --full-names writes each account's full name instead of in-+ denting leaf names, while keeping tree mode's inclusive balances. So+ --tree --no-elide --full-names -E shows the same complete table as above,+ but with inclusive balances:++ $ hledger -f examples/sample.journal balance --tree --no-elide --full-names -E+ $-1 assets+ $1 assets:bank+ 0 assets:bank:checking+ $1 assets:bank:saving+ $-2 assets:cash+ $2 expenses+ $1 expenses:food+ $1 expenses:supplies+ $-2 income+ $-1 income:gifts+ $-1 income:salary+ $1 liabilities+ $1 liabilities:debts+ --------------------+ 0++ Note that in this variant, parent and subaccount balances overlap, so (as+ in any tree mode report) the rows sum to more than the final total.++ Depth limiting+ With a depth:NUM query, or --depth NUM option, or just -NUM (eg: -3) bal-+ ance reports will show accounts only to the specified depth, hiding the+ deeper subaccounts. This can be useful for getting an overview without too+ much detail.++ Account balances at the depth limit always include the balances from any+ deeper subaccounts (even in list mode). Eg, limiting to depth 1:++ $ hledger -f examples/sample.journal balance -1+ $-1 assets+ $2 expenses+ $-2 income+ $1 liabilities+ --------------------+ 0++ Dropping top-level accounts+ You can also hide one or more top-level account name parts, using --drop+ NUM. This can be useful for hiding repetitive top-level account names:++ $ hledger -f examples/sample.journal bal expenses --drop 1+ $1 food+ $1 supplies+ --------------------+ $2++ Showing declared accounts+ With --declared, accounts which have been declared with an account direc-+ tive will be included in the balance report, even if they have no transac-+ tions. (Since they will have a zero balance, you will also need -E/--empty+ to see them.)++ More precisely, leaf declared accounts (with no subaccounts) will be in-+ cluded, since those are usually the more useful in reports.++ The idea of this is to be able to see a useful "complete" balance report,+ even when you don't have transactions in all of your declared accounts yet.++ Sorting by amount+ With -S/--sort-amount, accounts with the largest (most positive) balances+ are shown first. Eg: hledger bal expenses -MAS shows your biggest averaged+ monthly expenses first. When more than one commodity is present, they will+ be sorted by the alphabetically earliest commodity first, and then by sub-+ sequent commodities (if an amount is missing a commodity, it is treated as+ 0).++ Revenues and liability balances are typically negative, however, so -S+ shows these in reverse order. To work around this, you can add --invert to+ flip the signs. Or you could use one of the higher-level balance reports+ (bs, is..), which flip the sign automatically (eg: hledger is -MAS).++ Percentages+ With -%/--percent, balance reports show each account's value expressed as a+ percentage of the (column) total.++ Note it is not useful to calculate percentages if the amounts in a column+ have mixed signs. In this case, make a separate report for each sign, eg:++ $ hledger bal -% amt:`>0`+ $ hledger bal -% amt:`<0`++ Similarly, if the amounts in a column have mixed commodities, convert them+ to one commodity with -B, -V, -X or --value, or make a separate report for+ each commodity:++ $ hledger bal -% cur:\\$+ $ hledger bal -% cur:a++ Multi-period balance report+ With a report interval (set by the -D/--daily, -W/--weekly, -M/--monthly,+ -Q/--quarterly, -Y/--yearly, or -p/--period flag), balance shows a tabular+ report, with columns representing successive time periods (and a title):++ $ hledger -f examples/sample.journal bal --quarterly income expenses -E+ Balance changes in 2008:++ || 2008q1 2008q2 2008q3 2008q4+ ===================++=================================+ expenses:food || 0 $1 0 0+ expenses:supplies || 0 $1 0 0+ income:gifts || 0 $-1 0 0+ income:salary || $-1 0 0 0+ -------------------++---------------------------------+ || $-1 $1 0 0++ Notes:++ * The report's start/end dates will be expanded, if necessary, to fully en-+ compass the displayed subperiods (so that the first and last subperiods+ have the same duration as the others).++ * Leading and trailing periods (columns) containing all zeroes are not+ shown, unless -E/--empty is used.++ * Accounts (rows) containing all zeroes are not shown, unless -E/--empty is+ used.++ * Amounts with many commodities are shown in abbreviated form, unless+ --no-elide is used.++ * Average and/or total columns can be added with the -A/--average and+ -T/--row-total flags.++ * The --transpose flag can be used to exchange rows and columns. Repeating+ it reverses its effect (an even number of --transpose flags has no ef-+ fect).++ * The --pivot FIELD option causes a different transaction field to be used+ as "account name". See PIVOTING.++ * The --summary-only flag (--summary also works) hides all but the Total+ and Average columns (those should be enabled with --row-total and+ -A/--average).++ Multi-period reports with many periods can be too wide for easy viewing in+ the terminal. Here are some ways to handle that:++ * Hide the totals row with -N/--no-total++ * Filter to a single currency with cur:++ * Convert to a single currency with -V [--infer-market-price]++ * Use a more compact layout like --layout=bare++ * Maximize the terminal window++ * Reduce the terminal's font size++ * View with a pager like less, eg: hledger bal -D --color=yes | less -RS++ * Output as CSV and use a CSV viewer like visidata (hledger bal -D -O csv |+ vd -f csv), Emacs' csv-mode (M-x csv-mode, C-c C-a), or a spreadsheet+ (hledger bal -D -o a.csv && open a.csv)++ * Output as HTML and view with a browser: hledger bal -D -o a.html && open+ a.html++ Balance change, end balance+ It's important to be clear on the meaning of the numbers shown in balance+ reports. Here is some terminology we use:++ A balance change is the net amount added to, or removed from, an account+ during some period.++ An end balance is the amount accumulated in an account as of some date (and+ some time, but hledger doesn't store that; assume end of day in your time-+ zone). It is the sum of previous balance changes.++ We call it a historical end balance if it includes all balance changes+ since the account was created. For a real world account, this means it+ will match the "historical record", eg the balances reported in your bank+ statements or bank web UI. (If they are correct!)++ In general, balance changes are what you want to see when reviewing rev-+ enues and expenses, and historical end balances are what you want to see+ when reviewing or reconciling asset, liability and equity accounts.++ balance shows balance changes by default. To see accurate historical end+ balances:++ 1. Initialise account starting balances with an "opening balances" transac-+ tion (a transfer from equity to the account), unless the journal covers+ the account's full lifetime.++ 2. Include all of of the account's prior postings in the report, by not+ specifying a report start date, or by using the -H/--historical flag.+ (-H causes report start date to be ignored when summing postings.)++ Balance report modes+ The balance command is quite flexible; here is the full detail on how to+ control what it reports. If the following seems complicated, don't worry -+ this is for advanced reporting, and it does take time and experimentation+ to get familiar with all the report modes.++ There are three important option groups:++ hledger balance [CALCULATIONMODE] [ACCUMULATIONMODE] [VALUATIONMODE] ...++ Calculation mode+ The basic calculation to perform for each table cell. It is one of:++ * --sum : sum the posting amounts (default)++ * --budget : sum the amounts, but also show the budget goal amount (for+ each account/period)++ * --valuechange : show the change in period-end historical balance values+ (caused by deposits, withdrawals, and/or market price fluctuations)++ * --gain : show capital gain/loss for each account: the current valued bal-+ ance minus its cost. For lot-tracked commodities the cost is the cost+ basis of the units still held, so this is the unrealised gain. For other+ commodities it is the net of postings' transacted costs (acquisition+ costs minus disposal proceeds): where nothing has been sold this too is+ the unrealised gain, but once disposals exist the figure also includes+ the realised gain on the disposed units, so it is best read as "total+ gain since inception" (to separate realised and unrealised gains, track+ lots). Compare --valuechange, which shows how much the value moved in a+ period, from price changes and from buying and selling. See Unrealised+ gains for examples.++ * --count : show the count of postings++ Accumulation mode+ How amounts should accumulate across a report's subperiods/columns. An-+ other way to say it: which time period's postings should contribute to each+ cell's calculation. It is one of:++ * --change : calculate with postings from column start to column end, ie+ "just this column". Typically used to see revenues/expenses. (default+ for balance, cashflow, incomestatement)++ * --cumulative : calculate with postings from report start to column end,+ ie "previous columns plus this column". Typically used to show changes+ accumulated since the report's start date. Not often used.++ * --historical/-H : calculate with postings from journal start to column+ end, ie "all postings from before report start date until this column's+ end". Typically used to see historical end balances of assets/liabili-+ ties/equity. (default for balancesheet, balancesheetequity)++ Valuation mode+ Which kind of value or cost conversion should be applied, if any, before+ displaying the report. See Cost reporting and Value reporting for more+ about conversions.++ A valuation (or cost) mode can be selected with the --value option:++ * no conversion : don't convert to cost or value (default)++ * --value=cost[,COMM] : convert amounts to cost (then optionally to some+ other commodity)++ * --value=then[,COMM] : convert amounts to market value on transaction+ dates++ * --value=end[,COMM] : convert amounts to market value on period end+ date(s)+ (default with --valuechange, --gain)++ * --value=now[,COMM] : convert amounts to market value on today's date++ * --value=YYYY-MM-DD[,COMM] : convert amounts to market value on another+ date++ or with the legacy -B/-V/-X options, which are equivalent and easier to+ type:++ * -B/--cost : like --value=cost++ * -V/--market : like --value=end++ * -X COMM/--exchange COMM : like --value=end,COMM++ Note that --value can also convert to cost, as a convenience; but actually+ --cost and --value are independent options, and could be used together.++ Combining balance report modes+ Most combinations of these modes produce reasonable reports. The following+ restrictions are applied:++ * --valuechange implies --value=end++ * --valuechange makes --change the default when used with the bal-+ ancesheet/balancesheetequity commands++ * --cumulative or --historical disables --row-total/-T++ For reference, here is what the combinations of accumulation and valuation+ show:++ Valua- no valuation --value= then --value= end --value=+ tion:> YYYY-MM-DD+ Accumu- /now+ lation:v+ -----------------------------------------------------------------------------------+ --change change in period sum of post- period-end DATE-value of+ ing-date market value of change change in pe-+ values in period in period riod+ --cumu- change from re- sum of post- period-end DATE-value of+ lative port start to ing-date market value of change change from+ period end values from re- from report report start+ port start to pe- start to period to period end+ riod end end+ --his- change from sum of post- period-end DATE-value of+ torical journal start to ing-date market value of change change from+ /-H period end (his- values from jour- from journal journal start+ torical end bal- nal start to pe- start to period to period end+ ance) riod end end++ Budget report+ The balance --budget report is like a regular balance report, but with two+ main differences:++ * Budget goals and performance percentages are also shown, in brackets++ * Accounts which don't have budget goals are hidden by default.++ This is useful for comparing planned and actual income, expenses, time us-+ age, etc.++ Periodic transaction rules are used to define budget goals. For example,+ here's a periodic rule defining monthly goals for bus travel and food ex-+ penses:++ ;; Budget+ ~ monthly+ (expenses:bus) $30+ (expenses:food) $400++ After recording some actual expenses,++ ;; Two months worth of expenses+ 2017-11-01+ income $-1950+ expenses:bus $35+ expenses:food:groceries $310+ expenses:food:dining $42+ expenses:movies $38+ assets:bank:checking++ 2017-12-01+ income $-2100+ expenses:bus $53+ expenses:food:groceries $380+ expenses:food:dining $32+ expenses:gifts $100+ assets:bank:checking++ we can see a budget report like this:++ $ hledger bal -M --budget+ Budget performance in 2017-11-01..2017-12-31:++ || Nov Dec+ ===============++============================================+ <unbudgeted> || $-425 $-565+ expenses || $425 [ 99% of $430] $565 [131% of $430]+ expenses:bus || $35 [117% of $30] $53 [177% of $30]+ expenses:food || $352 [ 88% of $400] $412 [103% of $400]+ ---------------++--------------------------------------------+ || 0 [ 0% of $430] 0 [ 0% of $430]++ This is "goal-based budgeting"; you define goals for accounts and periods,+ often recurring, and hledger shows performance relative to the goals. This+ contrasts with "envelope budgeting", which is more detailed and strict -+ useful when cash is tight, but also quite a bit more work. https://plain-+ textaccounting.org/Budgeting has more on this topic.++ Using the budget report+ Historically this report has been confusing and fragile. hledger's version+ should be relatively robust and intuitive, but you may still find sur-+ prises. Here are more notes to help with learning and troubleshooting.++ * In the above example, expenses:bus and expenses:food are shown because+ they have budget goals during the report period.++ * Their parent expenses is also shown, with budget goals aggregated from+ the children.++ * The subaccounts expenses:food:groceries and expenses:food:dining are not+ shown since they have no budget goal of their own, but they contribute to+ expenses:food's actual amount.++ * Unbudgeted accounts expenses:movies and expenses:gifts are also not+ shown, but they contribute to expenses's actual amount.++ * The other unbudgeted accounts income and assets:bank:checking are grouped+ as <unbudgeted>.++ * --depth or depth: can be used to limit report depth in the usual way (but+ will not reveal unbudgeted subaccounts).++ * Amounts are always inclusive of subaccounts (even in -l/--list mode).++ * Numbers displayed in a --budget report will not always agree with the to-+ tals, because of hidden unbudgeted accounts; this is normal. -E/--empty+ can be used to reveal the hidden accounts.++ * In the periodic rules used for setting budget goals, unbalanced postings+ are convenient.++ * You can filter budget reports with the usual queries, eg to focus on par-+ ticular accounts. It's common to restrict them to just expenses. (The+ <unbudgeted> account is occasionally hard to exclude; this is because of+ date surprises, discussed below.)++ * Only the account, account type, depth, date and commodity parts of the+ query are applied to the budget goals; the other parts (status:/-U/-P/-C,+ code:, desc:, payee:, note:, tag:, real:, amt:) select actual transac-+ tions and postings only. So eg --budget --cleared compares your cleared+ spending against the full budget goals.++ * When you have multiple currencies, you may want to convert them to one+ (-X COMM --infer-market-prices) and/or show just one at a time+ (cur:COMM). If you do need to show multiple currencies at once, --layout+ bare can be helpful.++ * You can "roll over" amounts (actual and budgeted) to the next period with+ --cumulative.++ See also: https://hledger.org/budgeting.html.++ Budget date surprises+ With small data, or when starting out, some of the generated budget goal+ transaction dates might fall outside the report periods. Eg with the fol-+ lowing journal and report, the first period appears to have no ex-+ penses:food budget. (Also the <unbudgeted> account should be excluded by+ the expenses query, but isn't.):++ ~ monthly in 2020+ (expenses:food) $500++ 2020-01-15+ expenses:food $400+ assets:checking++ $ hledger bal --budget expenses+ Budget performance in 2020-01-15:++ || 2020-01-15+ ===============++====================+ <unbudgeted> || $400+ expenses:food || 0 [ 0% of $500]+ ---------------++--------------------+ || $400 [80% of $500]++ In this case, the budget goal transactions are generated on first days of+ of month (this can be seen with hledger print --forecast tag:generated ex-+ penses). Whereas the report period defaults to just the 15th day of janu-+ ary (this can be seen from the report table's column headings).++ To fix this kind of thing, be more explicit about the report period (and/or+ the periodic rules' dates). In this case, adding -b 2020 does the trick.++ Selecting budget goals+ By default, the budget report uses all available periodic transaction rules+ to generate goals. This includes rules with a different report interval+ from your report. Eg if you have daily, weekly and monthly periodic rules,+ all of these will contribute to the goals in a monthly budget report.++ You can select a subset of periodic rules by providing an argument to the+ --budget flag. --budget=DESCPAT will match all periodic rules whose de-+ scription contains DESCPAT, a case-insensitive substring (not a regular ex-+ pression or query). This means you can give your periodic rules descrip-+ tions (remember that two spaces are needed between period expression and+ description), and then select from multiple budgets defined in your jour-+ nal.++ Budgeting vs forecasting+ --forecast and --budget both use the periodic transaction rules in the+ journal to generate temporary transactions for reporting purposes. However+ they are separate features - though you can use both at the same time if+ you want. Here are some differences between them:++ --forecast --budget+ --------------------------------------------------------------------------+ is a general option; it enables fore- is a balance command option; it+ casting with all reports selects the balance report's+ budget mode+ generates visible transactions which generates invisible transactions+ appear in reports which produce goal amounts+ generates forecast transactions from generates budget goal transac-+ after the last regular transaction, to tions throughout the report pe-+ the end of the report period; or with riod, optionally restricted by+ an argument --forecast=PERIODEXPR gen- periods specified in the peri-+ erates them throughout the specified odic transaction rules+ period, both optionally restricted by+ periods specified in the periodic+ transaction rules+ uses all periodic rules uses all periodic rules; or with+ an argument --budget=DESCPAT+ uses just the rules matched by+ DESCPAT++ Balance report layout+ The --layout option affects how balance and the other balance-like commands+ show multi-commodity amounts and commodity symbols. It can improve read-+ ability, for humans and/or machines (other software). It has four possible+ values:++ * --layout=wide[,WIDTH]: commodities are shown on a single line, optionally+ elided to WIDTH++ * --layout=tall: each commodity is shown on a separate line++ * --layout=bare: commodity symbols are in their own column, amounts are+ bare numbers++ * --layout=barewide: commodities are shown on a single line, all in sepa-+ rate columns, amounts are bare numbers++ * --layout=tidy: data is normalised to easily-consumed "tidy" form, with+ one row per data value. (This one is currently supported only by the+ balance command.)++ Here are the --layout modes supported by each output format Only CSV output+ supports all of them:++ - txt csv html json sql+ -----------------------------------------+ wide Y Y Y+ tall Y Y Y+ bare Y Y Y+ barewide Y Y Y+ tidy Y++ Choice of layouts for budget reports is more restricted:++ - txt csv html json sql+ -----------------------------------------+ wide Y Y Y+ tall Y+ bare Y Y Y+ barewide Y Y+ tidy++ Examples:++ Wide layout+ With many commodities, reports can be very wide:++ $ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -T -Y --layout=wide+ Balance changes in 2012-01-01..2014-12-31:++ || 2012 2013 2014 Total+ ==================++====================================================================================================================================================================================================================+ Assets:US:ETrade || 10.00 ITOT, 337.18 USD, 12.00 VEA, 106.00 VHT 70.00 GLD, 18.00 ITOT, -98.12 USD, 10.00 VEA, 18.00 VHT -11.00 ITOT, 4881.44 USD, 14.00 VEA, 170.00 VHT 70.00 GLD, 17.00 ITOT, 5120.50 USD, 36.00 VEA, 294.00 VHT+ ------------------++--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ || 10.00 ITOT, 337.18 USD, 12.00 VEA, 106.00 VHT 70.00 GLD, 18.00 ITOT, -98.12 USD, 10.00 VEA, 18.00 VHT -11.00 ITOT, 4881.44 USD, 14.00 VEA, 170.00 VHT 70.00 GLD, 17.00 ITOT, 5120.50 USD, 36.00 VEA, 294.00 VHT++ A width limit reduces the width, but some commodities will be hidden:++ $ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -T -Y --layout=wide,32+ Balance changes in 2012-01-01..2014-12-31:++ || 2012 2013 2014 Total+ ==================++===========================================================================================================================+ Assets:US:ETrade || 10.00 ITOT, 337.18 USD, 2 more.. 70.00 GLD, 18.00 ITOT, 3 more.. -11.00 ITOT, 3 more.. 70.00 GLD, 17.00 ITOT, 3 more..+ ------------------++---------------------------------------------------------------------------------------------------------------------------+ || 10.00 ITOT, 337.18 USD, 2 more.. 70.00 GLD, 18.00 ITOT, 3 more.. -11.00 ITOT, 3 more.. 70.00 GLD, 17.00 ITOT, 3 more..++ Tall layout+ Each commodity gets a new line (may be different in each column), and ac-+ count names are repeated:++ $ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -T -Y --layout=tall+ Balance changes in 2012-01-01..2014-12-31:++ || 2012 2013 2014 Total+ ==================++==================================================+ Assets:US:ETrade || 10.00 ITOT 70.00 GLD -11.00 ITOT 70.00 GLD+ Assets:US:ETrade || 337.18 USD 18.00 ITOT 4881.44 USD 17.00 ITOT+ Assets:US:ETrade || 12.00 VEA -98.12 USD 14.00 VEA 5120.50 USD+ Assets:US:ETrade || 106.00 VHT 10.00 VEA 170.00 VHT 36.00 VEA+ Assets:US:ETrade || 18.00 VHT 294.00 VHT+ ------------------++--------------------------------------------------+ || 10.00 ITOT 70.00 GLD -11.00 ITOT 70.00 GLD+ || 337.18 USD 18.00 ITOT 4881.44 USD 17.00 ITOT+ || 12.00 VEA -98.12 USD 14.00 VEA 5120.50 USD+ || 106.00 VHT 10.00 VEA 170.00 VHT 36.00 VEA+ || 18.00 VHT 294.00 VHT++ Bare layout+ Commodity symbols are kept in one column, each commodity has its own row,+ amounts are bare numbers, account names are repeated:++ $ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -T -Y --layout=bare+ Balance changes in 2012-01-01..2014-12-31:++ || Commodity 2012 2013 2014 Total+ ==================++=============================================+ Assets:US:ETrade || GLD 0 70.00 0 70.00+ Assets:US:ETrade || ITOT 10.00 18.00 -11.00 17.00+ Assets:US:ETrade || USD 337.18 -98.12 4881.44 5120.50+ Assets:US:ETrade || VEA 12.00 10.00 14.00 36.00+ Assets:US:ETrade || VHT 106.00 18.00 170.00 294.00+ ------------------++---------------------------------------------+ || GLD 0 70.00 0 70.00+ || ITOT 10.00 18.00 -11.00 17.00+ || USD 337.18 -98.12 4881.44 5120.50+ || VEA 12.00 10.00 14.00 36.00+ || VHT 106.00 18.00 170.00 294.00++ Bare layout also affects CSV output, which is useful for producing data+ that is easier to consume, eg for making charts:++ $ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -O csv --layout=bare+ "account","commodity","balance"+ "Assets:US:ETrade","GLD","70.00"+ "Assets:US:ETrade","ITOT","17.00"+ "Assets:US:ETrade","USD","5120.50"+ "Assets:US:ETrade","VEA","36.00"+ "Assets:US:ETrade","VHT","294.00"+ "Total:","GLD","70.00"+ "Total:","ITOT","17.00"+ "Total:","USD","5120.50"+ "Total:","VEA","36.00"+ "Total:","VHT","294.00"++ Bare layout will sometimes display an extra row for the no-symbol commod-+ ity, because of zero amounts (hledger treats zeroes as commodity-less, usu-+ ally). This can break hledger-bar confusingly (workaround: add a cur:+ query to exclude the no-symbol row).++ Barewide layout+ Commodity symbols are spread in the table headers, each commodity has its+ own column, all column groups share the same set of commodities even if in+ one commodity column all values are zero. For consistency you may think of+ layout bare as baretall.++ $ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -T -Y --layout=barewide+ Balance changes in 2012-01-01..2014-12-31:++ || 2012 (GLD) 2012 (ITOT) 2012 (USD) 2012 (VEA) 2012 (VHT) 2013 (GLD) 2013 (ITOT) 2013 (USD) 2013 (VEA) 2013 (VHT) 2014 (GLD) 2014 (ITOT) 2014 (USD) 2014 (VEA) 2014 (VHT) Total (GLD) Total (ITOT) Total (USD) Total (VEA) Total (VHT)+ ==================++===================================================================================================================================================================================================================================================================+ Assets:US:ETrade || 0 10.00 337.18 12.00 106.00 70.00 18.00 -98.12 10.00 18.00 0 -11.00 4881.44 14.00 170.00 70.00 17.00 5120.50 36.00 294.00+ ------------------++-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ || 0 10.00 337.18 12.00 106.00 70.00 18.00 -98.12 10.00 18.00 0 -11.00 4881.44 14.00 170.00 70.00 17.00 5120.50 36.00 294.00++ Barewide layout is very useful for FODS and CSV output, since you can eas-+ ily use LibreOffice's VLOOKUP function for accessing numbers in a table+ with mixed commodities.++ Tidy layout+ This produces normalised "tidy data" (see+ https://cran.r-project.org/web/packages/tidyr/vignettes/tidy-data.html)+ where every variable has its own column and each row represents a single+ data point. This is the easiest kind of data for other software to con-+ sume:++ $ hledger -f examples/bcexample.journal bal assets:us:etrade -3 -Y -O csv --layout=tidy+ "account","period","start_date","end_date","commodity","value"+ "Assets:US:ETrade","2012","2012-01-01","2012-12-31","GLD","0"+ "Assets:US:ETrade","2012","2012-01-01","2012-12-31","ITOT","10.00"+ "Assets:US:ETrade","2012","2012-01-01","2012-12-31","USD","337.18"+ "Assets:US:ETrade","2012","2012-01-01","2012-12-31","VEA","12.00"+ "Assets:US:ETrade","2012","2012-01-01","2012-12-31","VHT","106.00"+ "Assets:US:ETrade","2013","2013-01-01","2013-12-31","GLD","70.00"+ "Assets:US:ETrade","2013","2013-01-01","2013-12-31","ITOT","18.00"+ "Assets:US:ETrade","2013","2013-01-01","2013-12-31","USD","-98.12"+ "Assets:US:ETrade","2013","2013-01-01","2013-12-31","VEA","10.00"+ "Assets:US:ETrade","2013","2013-01-01","2013-12-31","VHT","18.00"+ "Assets:US:ETrade","2014","2014-01-01","2014-12-31","GLD","0"+ "Assets:US:ETrade","2014","2014-01-01","2014-12-31","ITOT","-11.00"+ "Assets:US:ETrade","2014","2014-01-01","2014-12-31","USD","4881.44"+ "Assets:US:ETrade","2014","2014-01-01","2014-12-31","VEA","14.00"+ "Assets:US:ETrade","2014","2014-01-01","2014-12-31","VHT","170.00"++ Balance report output+ As noted in Output format, if you choose HTML output (by using -O html or+ -o somefile.html), you can create a hledger.css file in the same directory+ to customise the report's appearance.++ The HTML and FODS output formats can generate hyperlinks to hledger-web+ register views: an account name links to the account's transactions, a pe-+ riod heading to the period's transactions, and, in the default layout, a+ figure to the transactions it is made of, in a register whose final balance+ is that figure (a historical balance report asks the register for its his-+ torical mode). The two can differ when a transaction's postings have dates+ of their own, since the report counts such a posting in its own period+ while the register shows its whole transaction. Each link says where it+ leads in its title, which browsers show on hover. E.g. if your+ hledger-web server is reachable at http://localhost:5000 then you might run+ the balance command with the extra option --base-url=http://localhost:5000.+ You can also produce relative links, like --base-url="some/path" or+ --base-url="".)++ Balance charts+ With --chart, balance shows a chart of the report instead of a table,+ choosing a useful kind of chart automatically. In the terminal, this is a+ bar chart drawn with text characters:++ $ hledger -f examples/bcexample.journal bal -M expenses:food -b 2013 -e 2013-04 cur:USD --chart -w 70+ Balance changes in 2013Q1:++ a Expenses:Food:Groceries a Expenses:Food:Restaurant++ Jan 396.46 USD aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa+ Feb 481.48 USD aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa+ Mar 603.32 USD aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa++ * A multi-period report of balance changes is charted as stacked bars per+ period, showing the net total as the value (and with net, see below, as a+ line mark, a in text).++ * A multi-period report of end balances (--cumulative, -H) is charted the+ same way in text (and as lines in graphical charts).++ * With --chart=grouped, the accounts are stacked in a bar for each account+ type (assets, liabilities, equity, revenues, expenses, then any accounts+ of unknown type), side by side in each period, so that the types can be+ compared. Amounts keep their signs (eg liabilities are usually below+ zero), and end balances are drawn as bars too. In text charts, each pe-+ riod has a row for each type, and one for the total. Without a report+ interval, the whole report period is charted this way, as one period.++ * A single-period report is charted as one bar per account, with the total+ below the chart (as a number only, since it belongs to no account's bar,+ even with net).++ Negative amounts grow left from an axis, positive amounts right. Each ac-+ count has its own colour (when colour is enabled) and fill character; fill+ characters repeat after four accounts. The legend lists the accounts visi-+ ble in the chart (an account too small to fill a character cell is left+ out). Accounts are coloured by their account type, with conventional+ colours: assets blue, liabilities amber, equity violet, revenues green, ex-+ penses red; several accounts of one type get different shades of its colour+ (up to eight; beyond that, shades are shared). (In terminals which adver-+ tise 24-bit colour support, by setting COLORTERM=truecolor, these are the+ same exact colours as in SVG charts; otherwise they are the terminal's ba-+ sic blue, yellow, magenta, green and red, whose shades depend on its colour+ theme.) Accounts of unknown type get distinct colours instead. But when+ it shows just one account (in each panel), there is nothing to tell apart,+ so the account has its type's colour, or if its type is unknown, cyan, a+ colour no account type uses. A chart showing just a total (eg with -0, or+ of all accounts' transaction counts) is also cyan. Colours and fill char-+ acters are chosen by account name, not by position, so an account usually+ keeps its colour in other charts: with or without -S, or when you exclude+ other accounts to see more detail. (Not always, since there are only a few+ colours: an account may get a different one when some accounts are added or+ removed.) The chart fills the terminal width, or the width set by+ -w/--width (except for posting counts, with --count, which use at most one+ character per posting). It is drawn with unicode block characters, or with+ ASCII characters if the system's text encoding is not UTF-8.++ There is one chart panel per commodity. You can reduce this by converting+ to one commodity (eg -X USD) or selecting some (eg cur:USD); hledger sug-+ gests this when there are more than 8 panels. In tree mode, each account's+ own amounts are stacked, excluding its subaccounts', so that nothing is+ counted twice. At most 8 accounts are shown per panel; the smallest are+ combined into "other" series, one for each account type (so eg assets and+ liabilities are never combined), and each type keeps at least its largest+ account. "other" series are grey, or when coloured by type, a greyed ver-+ sion of their type's colour. The total is omitted with -N or --percent.+ Charts draw it (as a line or marks) only with net, eg --chart=net (or+ --chart=grouped,net). net draws the total where a bar combines several+ amounts; a chart of one account, or with one bar per account, does not draw+ it. (Text charts show it as a number either way.)++ In a chart of balance changes per period, -T/--row-total and -A/--average+ show the net total's total and average per period on a line below the+ chart, eg Total 11, Average 0.9; and in graphical charts, the average is+ also drawn as a dashed line across the chart, with an entry in the legend.+ In a chart of end balances (eg with -H, or bs), -A shows the average of the+ net total's period-end balances in the same way (there is no total).++ Each chart is scaled to fit its values. To draw charts at a fixed scale+ instead, so that you can compare them (eg this month's chart with last+ month's), add a SCALE amount: --chart=SCALE. This is the amount that the+ chart spans; eg with --chart=5000, a bar of 5000 fills the chart. If the+ chart also has negative values, they take the room they need and positive+ values get the rest. Bars that don't fit are clipped, with a mark at the+ edge (a or a in text, a small triangle in SVG); lines go off the edge. A+ SCALE with a commodity symbol (eg --chart='5000 USD') applies to that com-+ modity's panel, and one without, to the others. SCALE can follow KIND and+ net, and several SCALEs can be given, separated by commas (eg+ --chart='auto,5000 USD,4000 EUR'); so a SCALE can't contain a comma: write+ it without digit group marks, or with spaces or periods (eg 10 000 EUR). A+ number like 10.000 is read using that commodity's decimal mark, as it is+ shown in the report: eg in a journal where EUR is written with a decimal+ comma, 10.000 EUR is ten thousand. For the same scale in text charts, use+ the same width too (-w).++ With SVG output (-o FILE.svg or -O svg), balance always shows a chart, as a+ graphical image. Time runs along the x axis, and end balances are drawn as+ lines. A single-period report is drawn as vertical bars, one per account,+ with the account names below (angled if needed) and values above the bars+ (where they fit); or with more than 30 accounts, as horizontal bars. The y+ axis shows the unit only on its top (or bottom) label. In an HTML page,+ the chart shrinks to fit a narrower window.++ With HTML output, --chart shows the chart (as SVG), with the report's table+ collapsed below it (click Report details to show it).++ With -O csv, -O tsv or -O json, --chart shows the chart's data, eg to in-+ spect it or chart it with other tools.++ The compound balance commands (balancesheet, balancesheetequity, cashflow,+ incomestatement) can show charts in the same ways. They chart their sec-+ tions' accounts, with the net total (as a number in text charts, and with+ net, as a mark in text charts or a line in SVG charts), in one of two lay-+ outs:++ * diverging (the default, or with --chart=diverging): at each period, all+ accounts are stacked in one bar, showing each amount as its contribution+ to the net total: sections that add to it (eg assets, revenues) above+ zero, and sections that subtract from it (eg liabilities, expenses) below+ zero. (This is also why an is chart draws expenses below zero while bal+ draws them above, as their raw amounts are positive; bal --invert gives+ the same signs.) In text charts, each period is a row showing the net+ total, the totals of the sections on each side at the ends of the bar (as+ the report's table shows them; headed by the sections' names), and with+ net, a mark at the net total's position.++ * grouped (with --chart=grouped): at each period, each section's accounts+ are stacked in a bar of their own, side by side, so that the sections'+ sizes can be compared. Amounts are shown as the tables show them, eg ex-+ penses as well as revenues are positive. In text charts, each period has+ a row for each section, showing its total, and a row showing the net to-+ tal (and with net, marking it).++ Contra amounts - those with the opposite sign to their section's usual+ sign, like a refund recorded as a negative expense, or a contra account+ like accumulated depreciation - are drawn next to the zero line, hatched in+ their account's colour (below zero in the grouped layout, and on the other+ side from their section in the diverging layout). They are included in+ their section's totals. (Cash flows, in cf, have no usual sign: decreases+ are drawn like increases, below zero.) Each section shows at most five ac-+ counts, combining the smallest into "other"; use a depth limit (eg -1 or+ -2) for less detail. A single-period report is charted the same way, with+ one period. The chart data has one record per value, with fields: commod-+ ity, series (usually an account name), role (item, other or total), mark+ (bar, line or marker), x (a period heading, period end date, or account+ name), and value. With -T or -A, each commodity's total or average fol-+ lows, with role rowtotal or average, and an empty mark and x. Eg:++ $ hledger -f examples/sample.journal bal -M expenses -N --chart -O csv+ "commodity","series","role","mark","x","value"+ "$","expenses:food","item","bar","Jan","0"+ "$","expenses:food","item","bar","Feb","0"+ ...++ Some useful balance reports+ Some frequently used balance options/reports are:++ * bal -M revenues expenses+ Show revenues/expenses in each month. Also available as the incomestate-+ ment command.++ * bal -M -H assets liabilities+ Show historical asset/liability balances at each month end. Also available+ as the balancesheet command.++ * bal -M -H assets liabilities equity+ Show historical asset/liability/equity balances at each month end. Also+ available as the balancesheetequity command.++ * bal -M assets not:receivable+ Show changes to liquid assets in each month. Also available as the cash-+ flow command.++ Also:++ * bal -M expenses -2 -SA+ Show monthly expenses summarised to depth 2 and sorted by average amount.++ * bal -M --budget expenses+ Show monthly expenses and budget goals.++ * bal -M --valuechange investments+ Show monthly change in market value of investment assets.++ * bal -M -H --gain investments+ Show unrealised gain on investment assets (market value minus cost) at each+ month end.++ * bal investments --valuechange -D date:lastweek amt:'>1000' -STA [--in-+ vert]+ Show top gainers [or losers] last week++ balancesheet+ (bs)++ Show the end balances in asset and liability accounts. Amounts are shown+ with normal positive sign, as in conventional financial statements.++ Flags:+ --sum calculation mode: show sum of posting amounts+ (default)+ --valuechange calculation mode: show total change of value+ of period-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ --gain calculation mode: show unrealised capital+ gain/loss (historical balance value minus cost+ basis)+ --count calculation mode: show the count of postings+ --change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports)+ --cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. -b/--begin) to+ column end+ -H --historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date) (default)+ -l --flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth-clipped.+ -t --tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ --drop=N in list mode, omit N leading account name+ parts+ --declared include non-parent declared accounts (best+ used with -E)+ -A --average show a row average column (in multicolumn+ reports)+ -T --row-total show a row total column (in multicolumn+ reports)+ --summary-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ -N --no-total omit the final total row+ --no-elide in tree mode, don't squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without -E)+ --full-names in tree mode, show full account names instead+ of indented leaf names+ --format=FORMATSTR use this custom line format (in simple+ reports)+ -S --sort-amount sort by amount instead of account code/name+ -% --percent express values in percentage of each column's+ total+ --layout=ARG how to show multi-commodity amounts:+ 'wide[,WIDTH]': all commodities on one line+ 'tall' : each commodity on a new line+ 'bare' : bare numbers, symbols in a+ column+ --base-url=URLPREFIX in html output, generate hyperlinks to+ hledger-web, with this prefix. (Usually the base+ url shown by hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ -o --output-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ --view write output to FILE, or to view.FMT in+ hledger's cache directory, and open it in the+ system's default viewer for its format (eg a web+ browser for html). The default format is html.+ --chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: diverging (sections above and below zero;+ the default) or grouped (sections side by side).+ net: also draw the net total (a line, or marks+ in text charts). SCALE: the amount that fills+ the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)++ This command displays a balance sheet, showing historical ending balances+ of asset and liability accounts. (To see equity as well, use the bal-+ ancesheetequity command.)++ Accounts declared with the Asset, Cash or Liability type are shown (see ac-+ count types). Or if no such accounts are declared, it shows top-level ac-+ counts named asset or liability (case insensitive, plurals allowed) and+ their subaccounts.++ Example:++ $ hledger balancesheet+ Balance Sheet 2008-12-31++ || 2008-12-31+ ====================++============+ Assets ||+ --------------------++------------+ assets:bank:saving || $1+ assets:cash || $-2+ --------------------++------------+ || $-1+ ====================++============+ Liabilities ||+ --------------------++------------+ liabilities:debts || $-1+ --------------------++------------+ || $-1+ ====================++============+ Net: || 0++ This command is a higher-level variant of the balance command, and supports+ many of that command's features, such as multi-period reports. It is simi-+ lar to hledger balance -H assets liabilities, but with smarter account de-+ tection, and liabilities displayed with their sign flipped.++ This command also supports the output destination and output format options+ The output formats supported are txt, csv, tsv, html, json, and svg (a+ chart; see Balance charts).++ balancesheetequity+ (bse)++ Show a balance sheet, with historical ending balances of asset, liability+ and equity accounts. Amounts are shown with normal positive sign, as in+ conventional financial statements.++ Flags:+ --sum calculation mode: show sum of posting amounts+ (default)+ --valuechange calculation mode: show total change of value+ of period-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ --gain calculation mode: show unrealised capital+ gain/loss (historical balance value minus cost+ basis)+ --count calculation mode: show the count of postings+ --change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports)+ --cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. -b/--begin) to+ column end+ -H --historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date) (default)+ -l --flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth-clipped.+ -t --tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ --drop=N in list mode, omit N leading account name+ parts+ --declared include non-parent declared accounts (best+ used with -E)+ -A --average show a row average column (in multicolumn+ reports)+ -T --row-total show a row total column (in multicolumn+ reports)+ --summary-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ -N --no-total omit the final total row+ --no-elide in tree mode, don't squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without -E)+ --full-names in tree mode, show full account names instead+ of indented leaf names+ --format=FORMATSTR use this custom line format (in simple+ reports)+ -S --sort-amount sort by amount instead of account code/name+ -% --percent express values in percentage of each column's+ total+ --layout=ARG how to show multi-commodity amounts:+ 'wide[,WIDTH]': all commodities on one line+ 'tall' : each commodity on a new line+ 'bare' : bare numbers, symbols in a+ column+ --base-url=URLPREFIX in html output, generate hyperlinks to+ hledger-web, with this prefix. (Usually the base+ url shown by hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ -o --output-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ --view write output to FILE, or to view.FMT in+ hledger's cache directory, and open it in the+ system's default viewer for its format (eg a web+ browser for html). The default format is html.+ --chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: diverging (sections above and below zero;+ the default) or grouped (sections side by side).+ net: also draw the net total (a line, or marks+ in text charts). SCALE: the amount that fills+ the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)++ This report shows accounts declared with the Asset, Cash, Liability or Eq-+ uity type (see account types). Or if no such accounts are declared, it+ shows top-level accounts named asset, liability or equity (case insensi-+ tive, plurals allowed) and their subaccounts.++ Example:++ $ hledger balancesheetequity+ Balance Sheet With Equity 2008-12-31++ || 2008-12-31+ ====================++============+ Assets ||+ --------------------++------------+ assets:bank:saving || $1+ assets:cash || $-2+ --------------------++------------+ || $-1+ ====================++============+ Liabilities ||+ --------------------++------------+ liabilities:debts || $-1+ --------------------++------------+ || $-1+ ====================++============+ Equity ||+ --------------------++------------+ --------------------++------------+ || 0+ ====================++============+ Net: || 0++ This command is a higher-level variant of the balance command, and supports+ many of that command's features, such as multi-period reports. It is simi-+ lar to hledger balance -H assets liabilities equity, but with smarter ac-+ count detection, and liabilities/equity displayed with their sign flipped.++ This report is the easiest way to see if the accounting equation (A+L+E =+ 0) is satisfied (after you have done a close --retain to merge revenues and+ expenses with equity, and perhaps added --infer-equity to balance your com-+ modity conversions).++ This command also supports the output destination and output format options+ The output formats supported are txt, csv, tsv, html, json, and svg (a+ chart; see Balance charts).++ cashflow+ (cf)++ Show a (simple) cashflow statement, with the inflows and outflows affecting+ "cash" (ie, liquid, easily convertible) assets. Amounts are shown with+ normal positive sign, as in conventional financial statements.++ Flags:+ --sum calculation mode: show sum of posting amounts+ (default)+ --valuechange calculation mode: show total change of value+ of period-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ --gain calculation mode: show unrealised capital+ gain/loss (historical balance value minus cost+ basis)+ --count calculation mode: show the count of postings+ --change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports) (default)+ --cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. -b/--begin) to+ column end+ -H --historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date)+ -l --flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth-clipped.+ -t --tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ --drop=N in list mode, omit N leading account name+ parts+ --declared include non-parent declared accounts (best+ used with -E)+ -A --average show a row average column (in multicolumn+ reports)+ -T --row-total show a row total column (in multicolumn+ reports)+ --summary-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ -N --no-total omit the final total row+ --no-elide in tree mode, don't squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without -E)+ --full-names in tree mode, show full account names instead+ of indented leaf names+ --format=FORMATSTR use this custom line format (in simple+ reports)+ -S --sort-amount sort by amount instead of account code/name+ -% --percent express values in percentage of each column's+ total+ --layout=ARG how to show multi-commodity amounts:+ 'wide[,WIDTH]': all commodities on one line+ 'tall' : each commodity on a new line+ 'bare' : bare numbers, symbols in a+ column+ --base-url=URLPREFIX in html output, generate hyperlinks to+ hledger-web, with this prefix. (Usually the base+ url shown by hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ -o --output-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ --view write output to FILE, or to view.FMT in+ hledger's cache directory, and open it in the+ system's default viewer for its format (eg a web+ browser for html). The default format is html.+ --chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: diverging (sections above and below zero;+ the default) or grouped (sections side by side).+ net: also draw the net total (a line, or marks+ in text charts). SCALE: the amount that fills+ the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)++ This report shows accounts declared with the Cash type (see account types).+ Or if no such accounts are declared, it shows accounts++ * under a top-level account named asset (case insensitive, plural allowed)++ * whose name contains some variation of cash, bank, checking or saving.++ More precisely: all accounts matching this case insensitive regular expres-+ sion:++ ^assets?(:.+)?:(cash|bank|che(ck|que?)(ing)?|savings?|currentcash)(:|$)++ and their subaccounts.++ An example cashflow report:++ $ hledger cashflow+ Cashflow Statement 2008++ || 2008+ ====================++======+ Cash flows ||+ --------------------++------+ assets:bank:saving || $1+ assets:cash || $-2+ --------------------++------+ || $-1++ This command is a higher-level variant of the balance command, and supports+ many of that command's features, such as multi-period reports. It is simi-+ lar to hledger balance assets not:fixed not:investment not:receivable, but+ with smarter account detection.++ This command also supports the output destination and output format options+ The output formats supported are txt, csv, tsv, html, json, and svg (a+ chart; see Balance charts).++ codes+ List the codes seen in transactions, in the order parsed.++ Flags:+ no command-specific flags++ This command prints the value of each transaction's code field, in the or-+ der transactions were parsed. The transaction code is an optional value+ written in parentheses between the date and description, often used to+ store a cheque number, order number or similar.++ Transactions aren't required to have a code, and missing or empty codes+ will not be shown by default. With the -E/--empty flag, they will be+ printed as blank lines.++ You can add a query to select a subset of transactions.++ Examples:++ 2022/1/1 (123) Supermarket+ Food $5.00+ Checking++ 2022/1/2 (124) Post Office+ Postage $8.32+ Checking++ 2022/1/3 Supermarket+ Food $11.23+ Checking++ 2022/1/4 (126) Post Office+ Postage $3.21+ Checking++ $ hledger codes+ 123+ 124+ 126++ $ hledger codes -E+ 123+ 124++ 126++ commodities+ (comm)++ List the commodity symbols used or declared in the journal.++ Flags:+ --used list commodities used in transactions+ --priced list commodities appearing in P directives+ --declared list commodities declared by commodity directives+ --undeclared list commodities used or priced but not declared+ --unused list commodities declared but not used or priced+ --find list the first commodity matched by the first+ argument (a case-insensitive infix regexp)+ --directives show as commodity directives (with their display+ styles), for use in journals++ Most of these flags can be combined. With --directives, it shows valid+ commodity directives, declaring each commodity's (declared or inferred)+ display style, which could be pasted into a journal file. Some kinds of+ query argument are supported: cur:, tag:, and date: (also -b/-e/-p report+ period options).++ Providing a date query will affect which commodities are reported, as fol-+ lows:++ Flag No date query With a date query+ -----------------------------------------------------------------------------+ (none) declared a transacted a (transacted a priced) in the+ priced period+ --used transacted in the journal transacted in the period+ --priced appearing in any P directive appearing in a P directive in+ the period+ --declared declared with a commodity same+ directive+ --unde- (transacted a priced) a de- (transacted a priced in the pe-+ clared clared riod) a declared+ --unused declared a (transacted a same+ priced)+ --find the first commodity matching same+ the argument++ Example:++ $ hledger commodities+ $+ AAPL+ EUR++ descriptions+ (desc)++ List the unique descriptions used in transactions.++ Flags:+ no command-specific flags++ This command lists the unique descriptions that appear in transactions, in+ alphabetic order. You can add a query to select a subset of transactions.++ Example:++ $ hledger descriptions+ Store Name+ Gas Station | Petrol+ Person A++ files+ List all input files used by the journal(s), in the order they were read.+ This includes the files used to read CSV data: each CSV file is followed by+ its rules file and any rules files that includes, and each rules file is+ followed by any rules files it includes and the data file it read (if any).+ With a REGEX argument, only file names matching the regular expression+ (case sensitive) are shown.++ To find the files, hledger reads them only as far as needed, without pro-+ cessing their data. So this command works even when the journal has er-+ rors, such as unbalanced entries or failing balance assertions (but not+ syntax errors), and it does not run source commands. If an included file+ does not exist (or an include's glob pattern matches no files), it is omit-+ ted from the list, with a warning; this is not an error. (This helps tools+ which generate included files, and need to find them before they exist.)+ If a rules file's source pattern matches several files, only the one it+ would read is shown.++ With -t/--tree, the files are shown as a tree: each included file is in-+ dented below the file that includes it, and shown with its path relative to+ that file's directory (for a file included by name, the path as written in+ the include directive). The files used to read a CSV or rules file are+ shown one level below it, in the same way. A file included more than once+ appears at each place it is included. With a REGEX argument (which is+ matched against full paths), the files including a matched file are also+ shown.++ Flags:+ -l --flat list/tree mode: show files as a flat list+ (default)+ -t --tree list/tree mode: show files as a tree, indenting+ included files below the file that includes them+ -O --output-format=FMT select the output format. Supported formats:+ txt, json.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.++ With -O json, the files are listed as JSON, for use by other tools. Each+ file is an object with these fields: path (the file's path, or - for stan-+ dard input), depth (0 for a main file, 1 for a file it includes or uses,+ and so on), parent (the path of the file that included or used this one, or+ null for a main file), and exists (false for a missing included file, or an+ include's glob pattern which matched nothing). --tree does not affect JSON+ output, and a REGEX argument selects just the matching files.++ Examples:++ $ hledger -f main.journal files+ /home/user/finance/main.journal+ /home/user/finance/2024.journal++ $ hledger -f main.journal files 2024+ /home/user/finance/2024.journal++ $ hledger -f main.journal files --tree+ /home/user/finance/main.journal+ 2024.journal+ 2025.journal+ prices/2025.prices+ checking.rules+ common.rules+ data/checking.csv++ $ hledger -f main.journal files -O json checking+ [+ {+ "depth": 1,+ "exists": true,+ "parent": "/home/user/finance/main.journal",+ "path": "/home/user/finance/checking.rules"+ },+ {+ "depth": 2,+ "exists": true,+ "parent": "/home/user/finance/checking.rules",+ "path": "/home/user/finance/data/checking.csv"+ }+ ]++ holdings+ Show a report of investment holdings.++ Flags:+ -l --flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth-clipped.+ -t --tree list/tree mode: show accounts as a tree. Amounts+ include subaccount amounts.+ --no-elide in tree mode, don't squash boring parent+ accounts; in list mode, also show parent accounts+ (usually zero, hidden without -E)+ --full-names in tree mode, show full account names instead of+ indented leaf names+ --drop=N omit N leading account name parts; in tree mode,+ remove the first N levels+ -S --sort-amount sort by value (or with -B, cost) instead of+ account name, largest first+ -N --no-total omit the final total row+ --change show gains during the report period, or with a+ report interval, during each period (default with a+ start date and no interval)+ --cumulative with a report interval, show gains from the+ report start date to each period's end+ -H --historical show gains since acquisition, ignoring the report+ start date (default with a report interval)+ --round=TYPE how much rounding or padding should be done when+ displaying amounts ?+ none - show original decimal digits+ soft - just add or remove decimal zeros+ to match precision+ hard - round amounts to precision (default)+ all - also round cost amounts to precision+ --chart[=net,SCALE] show a chart: instead of the table (txt), above+ it (html), or as data (csv, tsv, json). net: also+ draw the net total (a line, or marks in text+ charts). SCALE: the amount that fills the chart (eg+ 1000 or 1000 USD; one per commodity), for+ comparable charts.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)+ -O --output-format=FMT select the output format. Supported formats:+ txt, csv, tsv, html, fods, json, svg.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ --view write output to FILE, or to view.FMT in hledger's+ cache directory, and open it in the system's+ default viewer for its format (eg a web browser for+ html). The default format is html.++ This command shows your lot-tracked assets (see Lots and capital gains),+ and their performance, as of the report end date. An example:++ $ hledger holdings -e 2023-04-02+ Holdings on 2023-04-01++ || Date Age Units Avg cost Unit price Total cost Total value Weight UGain UGain% RGain XIRR+ ===========================++===========================================================================================================================+ assets:investments:stocks || 2022-04-07 359d 10 INFY 2.00 a 100.00 a 20.00 a 1,000.00 a 6.4% 980.00 a 4900.0% 5252.4%+ assets:investments:stocks || 73 LTTS 4.79 a 200.00 a 350.00 a 14,600.00 a 93.6% 14,250.00 a 4071.4% 140.00 a 4290.2%+ ---------------------------++---------------------------------------------------------------------------------------------------------------------------+ || 370.00 a 15,600.00 a 100.0% 15,230.00 a 4116.2% 140.00 a 4342.1%++ With --lots, the individual lots are shown:++ $ hledger holdings --lots -e 2023-04-02+ Holdings on 2023-04-01++ || Date Age Units Unit cost Unit price Total cost Total value Weight UGain UGain% RGain XIRR+ =========================================================++============================================================================================================================+ assets:investments:stocks:{2022-04-06, "0002", 10.00 a} || 2022-04-06 360d 13 LTTS 10.00 a 200.00 a 130.00 a 2,600.00 a 16.7% 2,470.00 a 1900.0% 140.00 a 3876.1%+ assets:investments:stocks:{2022-04-07, 2.00 a} || 2022-04-07 359d 10 INFY 2.00 a 100.00 a 20.00 a 1,000.00 a 6.4% 980.00 a 4900.0% 5252.4%+ assets:investments:stocks:{2022-05-06, "0002", 11.00 a} || 2022-05-06 330d 20 LTTS 11.00 a 200.00 a 220.00 a 4,000.00 a 25.6% 3,780.00 a 1718.2% 5032.7%+ assets:investments:stocks:{2022-06-06, "0002", 0.00 a} || 2022-06-06 299d 40 LTTS 0 200.00 a 0 8,000.00 a 51.3% 8,000.00 a+ ---------------------------------------------------------++----------------------------------------------------------------------------------------------------------------------------+ || 370.00 a 15,600.00 a 100.0% 15,230.00 a 4116.2% 140.00 a 4342.1%++ The columns show:++ * each holding's acquisition date (or earlier basis date) and age++ * the number of units held++ * the unit cost basis (Unit cost; or Avg cost, the average unit cost of+ several lots, or for accounts using the AVERAGE method, the pool's run-+ ning average on the report date)++ * the unit market price on the report date (Unit price)++ * the total cost basis (Total cost)++ * the total market value (Total value)++ * the percentage of the portfolio's total value (Weight). A holding with+ no market price has no Weight and isn't counted in that total, so the+ others' weights are a little overstated. No weights are shown if the+ holdings are valued in more than one commodity.++ * the unrealised gain and gain percent (UGain, UGain%)++ * the realised gain from disposals so far (RGain)++ * and the annualised rate of return, as of the report end date (XIRR, cal-+ culated from the holding's dated cashflows and current value, like roi's+ IRR; it includes realised gains). Lots received without a transacted+ cost (eg transferred from another account) count as invested at their+ cost basis on their acquisition date.++ Fully disposed commodities and accounts ("closed positions") are not shown,+ unless you add -E/--empty. But the totals row's RGain and XIRR always in-+ clude them, so those columns may not add up to their totals; a note below+ the table then says how many closed positions are not shown.++ To see a commodity's performance, a market price should be declared for it+ (as of the report end date). Market prices come from P directives or (with+ --infer-market-prices) from transacted prices, as usual. Each lot is val-+ ued in its cost commodity. A holding with no market price has no value or+ gains; the totals' Total value, UGain, UGain% and XIRR are then those of+ the other holdings, and a note below the table names the excluded ones.+ (With a report interval, the periods whose totals exclude some are starred;+ and a period's gains exclude the holdings with no market price at either+ its start or its end, so that they compare the same holdings.) In a+ multi-currency portfolio, aggregated values may contain multiple curren-+ cies; use -X COMM for a single-currency view.++ With -V, -X COMM or --value (Valuation), holdings are valued in the default+ or given valuation commodity instead, and the cost columns are also con-+ verted to it (at the valuation date, so percent gain is unaffected). Cash-+ flows are not converted, however, so the XIRR column is left blank for+ holdings whose cashflows are in a different commodity. --value=then is not+ supported, and -B/--cost doesn't change the report's figures (but see sort-+ ing and balance: below).++ -S/--sort-amount sorts the lines by their Total value, largest first, wher-+ ever their account. Holdings with no market price come after the priced+ ones, sorted by their Total cost. In tree mode, sibling accounts are+ sorted likewise by their subtree's totals, as shown on their headings (an+ account sorts with the unpriced ones only when none of its holdings has a+ market price), and the holdings under each account as in list mode. With+ -B, everything is sorted by Total cost. Values in different commodities+ are compared by their numbers alone; to compare them properly, convert them+ to one commodity with -X COMM.++ Amounts are displayed with their commodity's display precision. --round+ can select another rounding strategy. The percent columns (Weight, UGain%,+ XIRR) are shown with the display style configured for the % commodity (eg+ by -c '0.00 %'). With colour enabled, the gain columns (UGain, UGain%,+ RGain, XIRR) show gains in green and losses in red.++ Query arguments and report flags like --depth, --title etc. work as usual.+ balance: and change: query terms test each line (one commodity in one ac-+ count). A line has two amounts, its units and its Total value, and the+ term's commodity symbol selects which is tested:++ * holdings balance:'>100' - holdings of more than 100 units (with no sym-+ bol, units are tested)++ * holdings balance:'>100 AAPL' - holdings of more than 100 AAPL++ * holdings balance:'>$1000' - holdings worth more than $1000. Lines with+ no market price have no value, and don't match.++ * holdings -B balance:'>$1000' - holdings which cost more than $1000 (with+ -B, Total cost is tested instead of Total value)++ change: tests the line's change in units during the report period (so it+ needs a start date, eg -b), or with the value's commodity symbol, the value+ of that change at the valuation date. Unlike in other reports, -V/-X don't+ change which amount is tested; to test the value, write its commodity sym-+ bol. But as in other reports, -B tests cost: the line's Total cost, or the+ cost of its change, instead of their value. The totals and tree mode's ac-+ count headings then cover just the lines shown. But Weight is still each+ line's share of all the holdings, including the hidden ones (so the total+ Weight shows what share the lines shown make up).++ With -t/--tree, holdings are grouped into account sections: an account with+ subaccounts or several commodities becomes a heading row, showing its sub-+ tree's totals computed like the totals row, with its own holdings beneath+ it named by their commodity; an account holding one commodity with no sub-+ accounts is a single combined row; and with --lots, each holding's lots ap-+ pear beneath it. Boring parent accounts are squashed into their child as+ usual (considering only accounts with holdings), unless --no-elide is used.++ With -O html, an HTML table is produced instead. With -O fods, a spread-+ sheet document readable by LibreOffice etc. is produced. With -O csv or+ -O tsv, machine-readable output is produced: one record per holding (or+ lot, with --lots), with full account names, age in days, bare units and+ gain percent numbers, and no totals or tree-mode heading records. With -O+ json, a JSON array of holding objects is produced. In both, the cost and+ value fields are named unitcost, unitprice, totalcost and totalvalue.++ Gains during a period+ Normally the gain columns show each holding's gains since it was acquired.+ With a report start date (eg -b, -p, or date:), they show the gains during+ the report period instead, and the report title says so (eg "gains in+ 2026-11"):++ $ hledger holdings -p today # today's gains+ $ hledger holdings -p thisyear # this year's gains so far+ $ hledger holdings -b 2026-10-01 # gains since a date (until today)+ $ hledger holdings -p 2026-q3 # gains in a past period (the report shows holdings at its end)++ The units, cost, price, value and Weight columns are unchanged; they show+ holdings as of the report end date. But:++ * UGain is the change in unrealised gain during the period: the unrealised+ gain at the end, minus that on the day before the start date. (Note that+ selling realises gains: UGain decreases and RGain increases.)++ * UGain% is that as a percentage of the holding's value on the day before+ the start date, plus the net cost added since.++ * RGain is the realised gain from disposals during the period.++ * XIRR is the annualised rate of return for the period, counting the value+ on the day before the start date as invested then. For a short period+ this can be a very large number (or blank, when too large to calculate);+ UGain% shows the period's un-annualised gain.++ The start date is the first day of the period, so gains are measured from+ the previous day's closing prices: -p today shows today's gains (today's+ market prices compared with the latest ones before today), and -b yesterday+ shows yesterday's and today's. This way consecutive periods' gains add up,+ and a month's gains start from the previous month's last prices, as in a+ broker's statement. If a market price is missing at the start or the end,+ the gains depending on it are left blank. With -E, holdings fully disposed+ during the period are shown too.++ A report start date before your first acquisition gives the same gains as+ no start date. -H/--historical shows the gains since acquisition despite a+ start date. (With a report interval, gains are since acquisition unless+ you ask otherwise; see below.)++ Holdings over time+ With a report interval (eg -M, -Q, -Y), holdings shows how your holdings+ changed: their totals at the end of each period, each computed as on that+ date (eg valued at its market prices). When the holdings are all of one+ commodity (eg with a cur: query), their Units, Avg cost and Unit price are+ shown too.++ The gain columns' period is selected as in other periodic reports (accumu-+ lation mode):++ * -H/--historical (the default): gains since acquisition, up to each pe-+ riod's end++ * --change: gains during each period, as in a single-date report of that+ period (above); these add up: the periods' UGain and RGain sum to those+ of the whole report period++ * --cumulative: gains from the report start date up to each period's end.++ With no end date, the periods continue up to today, even after your last+ transaction (since values change with market prices), and the current pe-+ riod's row shows today's holdings, like the report without an interval.+ List/tree mode and --lots make no difference to these totals, and are ig-+ nored. With -O csv, tsv or json, there is one record per period end, whose+ unpriced field lists the commodities excluded from its totals for having no+ market price.++ $ hledger holdings -M -e 2026-04-01+ Monthly holdings, 2026-01-31..2026-03-31++ || Units Avg cost Unit price Total cost Total value UGain UGain% RGain XIRR+ ============++======================================================================================+ 2026-01-31 || 10 AAA $10 $12 $100 $120 $20 20.0% 820.5%+ 2026-02-28 || 6 AAA $10 $15 $60 $90 $30 50.0% $20 1566.4%+ 2026-03-31 || 6 AAA $10 $9 $60 $54 $-6 -10.0% $20 108.0%++ Holdings charts+ With --chart, holdings are shown as a chart: a bar for each holding (or+ lot, with --lots), labelled by account and commodity. A holding's bar+ shows its cost basis, and its unrealised gain stacked on top, reaching its+ market value (which is shown); or if it has lost value, the part of its+ cost basis it is still worth, reaching its market value, and the part lost+ beyond it (hatched). So the solid part of a bar always reaches the market+ value. In graphical charts these are coloured like assets (blue), revenues+ (green) and expenses (red). Each bar's unrealised gain percent is shown+ after its value, in green if positive or red if negative. Graphical charts+ show it instead of the value (which the axis shows), at the right of the+ bars, which are horizontal so that there is room for all of them. With a+ report interval, each period's gain percent is above its bar, when there is+ room for them all. A holding without a market price is shown as its cost+ basis, in grey. There is a chart panel for each commodity the holdings are+ valued in; use -X COMM to see them all in one. With a report interval,+ there is a bar for each period end instead, showing all the holdings then:+ their total cost basis, and their net unrealised gain or loss (with+ --chart=net, also their value: in graphical charts, a line joining the pe-+ riods, like other reports' totals). With --change or --cumulative, the+ bars show the gains the table shows instead: realised gains, and unrealised+ gains (hatched, since they are not yet final), with losses below zero, and+ with --chart=net, the net gain (in graphical charts, a line joining the pe-+ riods, like other reports' totals). As in the table, the periods whose+ values and gains exclude holdings with no market price are starred, with a+ note below the chart. With SVG output (eg -o holdings.svg, or --view) it+ is a graphical chart, and with HTML output it is shown above the report's+ table. See Charts for more.++ $ hledger holdings --chart -w 70+ Holdings on 2024-12-31++ USD+ a Cost a Unrealised gain a+/- Unrealised loss a No market price++ assets:broker AAPL 2,500.00 USD +66.7% aaaaaaaaaaaaaaaaaaaaaaaaaaaa+ assets:broker NEW a+ assets:broker XYZ 450.00 USD -40.0% aaaaaa+/-a+/-a+/-++ incomestatement+ (is)++ Show revenue inflows and expense outflows during the report period.+ Amounts are shown with normal positive sign, as in conventional financial+ statements.++ Flags:+ --sum calculation mode: show sum of posting amounts+ (default)+ --valuechange calculation mode: show total change of value+ of period-end historical balances (caused by+ deposits, withdrawals, market price+ fluctuations)+ --gain calculation mode: show unrealised capital+ gain/loss (historical balance value minus cost+ basis)+ --count calculation mode: show the count of postings+ --change accumulation mode: accumulate amounts from+ column start to column end (in multicolumn+ reports) (default)+ --cumulative accumulation mode: accumulate amounts from+ report start (specified by e.g. -b/--begin) to+ column end+ -H --historical accumulation mode: accumulate amounts from+ journal start to column end (includes postings+ before report start date)+ -l --flat list/tree mode: show accounts as a flat list+ (default). Amounts exclude subaccount amounts,+ except where the account is depth-clipped.+ -t --tree list/tree mode: show accounts as a tree.+ Amounts include subaccount amounts.+ --drop=N in list mode, omit N leading account name+ parts+ --declared include non-parent declared accounts (best+ used with -E)+ -A --average show a row average column (in multicolumn+ reports)+ -T --row-total show a row total column (in multicolumn+ reports)+ --summary-only display only row summaries (e.g. row total,+ average) (in multicolumn reports)+ -N --no-total omit the final total row+ --no-elide in tree mode, don't squash boring parent+ accounts; in list mode, also show parent+ accounts (usually zero, hidden without -E)+ --full-names in tree mode, show full account names instead+ of indented leaf names+ --format=FORMATSTR use this custom line format (in simple+ reports)+ -S --sort-amount sort by amount instead of account code/name+ -% --percent express values in percentage of each column's+ total+ --layout=ARG how to show multi-commodity amounts:+ 'wide[,WIDTH]': all commodities on one line+ 'tall' : each commodity on a new line+ 'bare' : bare numbers, symbols in a+ column+ --base-url=URLPREFIX in html output, generate hyperlinks to+ hledger-web, with this prefix. (Usually the base+ url shown by hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ txt, html, csv, tsv, json, svg.+ -o --output-file=FILE write output to FILE. A file extension+ matching one of the above formats selects that+ format.+ --view write output to FILE, or to view.FMT in+ hledger's cache directory, and open it in the+ system's default viewer for its format (eg a web+ browser for html). The default format is html.+ --chart[=KIND,net,SCALE] show a chart: instead of the table (txt),+ above it (html), or as data (csv, tsv, json).+ KIND: diverging (sections above and below zero;+ the default) or grouped (sections side by side).+ net: also draw the net total (a line, or marks+ in text charts). SCALE: the amount that fills+ the chart (eg 1000 or 1000 USD; one per+ commodity), for comparable charts.+ -w --width=N with --chart: draw the chart N characters wide+ (default: the terminal width)++ This command displays an income statement, showing revenues and expenses+ during one or more periods.++ It shows accounts declared with the Revenue or Expense type (see account+ types). Or if no such accounts are declared, it shows top-level accounts+ named revenue or income or expense (case insensitive, plurals allowed) and+ their subaccounts.++ Example:++ $ hledger incomestatement+ Income Statement 2008++ || 2008+ ===================++======+ Revenues ||+ -------------------++------+ income:gifts || $1+ income:salary || $1+ -------------------++------+ || $2+ ===================++======+ Expenses ||+ -------------------++------+ expenses:food || $1+ expenses:supplies || $1+ -------------------++------+ || $2+ ===================++======+ Net: || 0++ This command is a higher-level variant of the balance command, and supports+ many of that command's features, such as multi-period reports. It is simi-+ lar to hledger balance '(revenues|income)' expenses, but with smarter ac-+ count detection, and revenues/income displayed with their sign flipped.++ This command also supports the output destination and output format options+ The output formats supported are txt, csv, tsv, html, json, and svg (a+ chart; see Balance charts).++ notes+ List the unique notes that appear in transactions.++ Flags:+ no command-specific flags++ This command lists the unique notes that appear in transactions, in alpha-+ betic order. You can add a query to select a subset of transactions. The+ note is the part of the transaction description after a | character (or if+ there is no |, the whole description).++ Example:++ $ hledger notes+ Petrol+ Snacks++ payees+ List the payee/payer names used or declared in the journal.++ Flags:+ --used list payees used+ --declared list payees declared+ --undeclared list payees used but not declared+ --unused list payees declared but not used+ --find list the first payee matched by the first+ argument (a case-insensitive infix regexp)+ --directives show as payee directives, for use in journals++ This command lists unique payee/payer names - all of them by default, or+ just the ones which have been used in transaction descriptions, or declared+ with payee directives, or used but not declared, or declared but not used,+ or just the first one matched by a pattern (with --find, returning a+ non-zero exit code if it fails).++ The payee/payer name is the part of the transaction description before a |+ character (or if there is no |, the whole description).++ With --directives, it shows valid payee directives, which could be pasted+ into a journal file.++ You can add query arguments to select a subset of transactions or payees.+ Note that transaction-specific query terms like date: will exclude de-+ clared-but-unused payees, which don't have that field.++ Example:++ $ hledger payees+ Store Name+ Gas Station+ Person A++ prices+ Print the market prices declared with P directives. With --infer-mar-+ ket-prices, also show any additional prices inferred from costs. With+ --show-reverse, also show additional prices inferred by reversing known+ prices. With --show-aliases, also show the exchange rates provided by com-+ modity aliases.++ Flags:+ --show-reverse also show the prices inferred by reversing known+ prices+ --show-aliases also show the exchange rates provided by+ commodity aliases+ --summary summarise declared prices per commodity instead+ of listing them+ --locations also show where prices where declared++ With --locations, each price line gets a trailing ; location: FILE:LINE+ comment showing where it came from. Declared prices point at their P di-+ rective; prices inferred from costs point at the parent transaction's first+ line. Reversed prices keep the source position of the directive they were+ derived from.++ With --show-aliases, each commodity alias which provides an exchange rate+ (between a commodity and its alias, when there are no market prices between+ them) is shown as a price dated 0000-01-01 with a ; commodity alias com-+ ment. Its location is the commodity directive which declared the alias.+ These are used only when market prices can't provide a conversion, see+ Finding market price.++ Price amounts are always displayed with their full precision, except for+ reverse prices which are limited to 8 decimal digits.++ Prices can be filtered by a date:, cur:, amt: or find: query.++ Generally if you run this command with --infer-market-prices --show-reverse+ --show-aliases, it will show the same prices used internally to calculate+ value reports. But if in doubt, you can inspect those directly by running+ the value report with --debug=2.++ Examples:++ $ hledger prices+ P 2024-01-01 AAPL $150+ P 2024-02-01 AAPL $160+ P 2024-02-01 EUR $1.08++ $ hledger prices --infer-market-prices+ P 2024-01-01 AAPL $150+ P 2024-01-05 AAPL $150+ P 2024-02-01 AAPL $160+ P 2024-02-01 EUR $1.08++ prices summary+ With --summary, instead of listing individual prices, prices prints one row+ per commodity used in the journal (other than the base currency), with the+ following columns:++ * Commodity -- the commodity, as an ISO 4217 code if possible.++ * Prices -- the number of market price declarations for that commodity.++ * Earliest / Latest -- the date range of those prices.++ * Period -- the duration between earliest and latest.++ * Coverage -- the percentage of weekdays in that period that have a price+ declared (or blank when fewer than two prices).++ Summary mode is a quick way to spot gaps in your price data, and pairs nat-+ urally with getprices. Only prices declared with P directives are counted;+ prices inferred with --show-reverse or --infer-market-prices are ignored.++ Queries (cur:, date:, amt:, find:) can be used to narrow the prices that+ are summarised.++ print+ Show transactions' journal entries, or export journal data to another for-+ mat.++ Flags:+ -a --all show all details (--explicit --lots+ --verbose-tags)+ -x --explicit show all inferred info explicitly+ --verbose-tags add tags indicating generated/modified data+ --invert display all amounts with reversed sign+ --locations add tags showing file paths and line numbers+ --export reproduce the whole journal, with directives and+ comments preserved and included files inlined+ -m --match=DESC fuzzy search for one recent transaction with+ description closest to DESC+ --new show only newer-dated transactions added in each+ file since last run+ --round=TYPE how much rounding or padding should be done when+ displaying amounts ?+ none - show original decimal digits,+ as in journal (default)+ soft - just add or remove decimal zeros+ to match precision+ hard - round posting amounts to precision+ (can unbalance transactions)+ all - also round cost amounts to precision+ (can unbalance transactions)+ --layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 - right-align amounts, as in hledger 1+ COL - align decimal marks at column COL+ (default: 53)+ --base-url=URLPREFIX in html output, generate links to hledger-web,+ with this prefix. (Usually the base url shown by+ hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ journal, ledger, beancount, csv, tsv, html, fods,+ json, sql.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ --view write output to FILE, or to view.FMT in hledger's+ cache directory, and open it in the system's+ default viewer for its format (eg a web browser for+ html). The default format is html.++ The print command displays full journal entries (transactions) from the+ journal file, sorted by date (or with --date2, by secondary date). (For a+ compact one-line-per-transaction overview, see the transactions command.)++ By default, directives and inter-transaction comments are not shown (except+ for comment lines immediately preceding a transaction, which are shown with+ it), and entries are sorted by date. So the default print output is some-+ what lossy. To reproduce the whole journal, including directives and com-+ ments, use --export (see below).++ Eg:++ $ hledger print -f examples/sample.journal date:200806+ 2008/06/01 gift+ assets:bank:checking $1+ income:gifts $-1++ 2008/06/02 save+ assets:bank:saving $1+ assets:bank:checking $-1++ 2008/06/03 * eat & shop+ expenses:food $1+ expenses:supplies $1+ assets:cash $-2++ print explicitness+ Normally, whether posting amounts are implicit or explicit is preserved.+ For example, when an amount is omitted in the journal, it will not appear+ in the output. Similarly, if a conversion cost is implied but not written,+ it will not appear in the output.++ You can use the -x/--explicit flag to force explicit display of all amounts+ and costs. This can be useful for troubleshooting or for making your jour-+ nal more readable and robust against data entry errors. -x is also implied+ by using any of -B,-V,-X,--value.++ The -x/--explicit flag will cause any postings with a multi-commodity+ amount (which can arise when a multi-commodity transaction has an implicit+ amount) to be split into multiple single-commodity postings, keeping the+ output parseable.++ To see more details -- not just inferred amounts and costs, but also lot+ subaccounts and postings, and the hidden tags that hledger adds to classify+ things -- use -a/--all, which is equivalent to --explicit --lots --ver-+ bose-tags.++ print layout+ By default, print aligns posting amounts so that their decimal mark is at+ column 53 (or would be if they had a decimal mark). If needed, it will+ shift a transaction's amounts further to the right to ensure at least 2+ spaces between account names and amounts. Also, any balance assertion/as-+ signment operators (=, =* etc.) are aligned to the right of the posting+ amounts; and the assertion/assignment amounts will be aligned by their dec-+ imal marks.++ You can customise this with --layout:++ * --layout=COL -- sets a different target column for posting amounts' deci-+ mal mark++ * --layout=hledger1 -- use hledger 1 layout (right-aligned posting amounts+ in each transaction).++ If you want to change the default, put something like this in+ ~/.hledger.conf:++ [print]+ --layout=hledger1++ Other print-like commands (close, import, rewrite, add) also accept --lay-+ out.++ print amount style+ Amounts will be displayed mostly in their commodity's display style, with+ standardised symbol placement, decimal mark, and digit group marks. This+ does not apply to their decimal digits; print normally shows the same deci-+ mal digits that are recorded in each journal entry. (Calculated amounts+ with a repeating decimal, eg from converting 10 min to hours, are shown+ with 8 decimal places.)++ You can override the decimal precisions with print's special --round op-+ tion. --round tries to show amounts with their commodities' standard deci-+ mal precisions, increasingly strongly:++ * --round=none show amounts with original precisions (default)++ * --round=soft add/remove decimal zeros in amounts (except costs)++ * --round=hard round amounts (except costs), possibly hiding significant+ digits++ * --round=all round all amounts and costs++ soft is good for non-lossy cleanup, displaying more consistent decimals+ where possible, without making entries unbalanced.++ hard or all can be good for stronger cleanup, when decimal rounding is+ wanted. Note rounding can produce unbalanced journal entries, perhaps re-+ quiring manual fixup.++ print parseability+ Usually, print's output is a valid hledger journal, which you can pipe into+ a second hledger command for further processing. This is sometimes conve-+ nient for rewriting journal entries:++ # Make today's shopping entry explicit. (-f - means read from standard input.)+ $ hledger print date:today desc:shop | hledger -f- print -x++ or for achieving certain kinds of query:++ # Show running total of food expenses paid from cash.+ $ hledger print assets:cash | hledger -f- reg expenses:food++ But here are some things which can cause print's output to become un-+ parseable:++ * --round (see above) can disrupt transaction balancing.++ * Account aliases or pivoting can disrupt account names, balance asser-+ tions, or balance assignments.++ * Value reporting also can disrupt balance assertions or balance assign-+ ments.++ * Auto postings can generate too many amountless postings.++ * --infer-costs or --infer-equity can generate too-complex redundant costs.++ * Because print always shows transactions in date order, balance assertions+ involving non-date-ordered transactions (and same-day postings) could be+ disrupted.++ Also, printing a subset of journal entries can disrupt validation of bal-+ ance assertions or lot entries. And print does not reproduce directives+ (unless --export is used). Lot entries are printed with their inferred+ cost basis annotations, so they can still be read without the commodity's+ lots: declaration when the default cost basis method is used; but with+ other methods, or lots: NONE accounts, the missing declarations will change+ how they are read. (--export output keeps lot entries as written, since it+ reproduces the declarations.) To suppress errors from these, we often use+ the -I flag (short for --ignore-assertions --ignore-lots). So any time you+ are reading from standard input with -f-, consider adding -I also.++ print export mode+ With --export, print reproduces the whole journal in its original order,+ with directives, top-level comment lines and comment blocks preserved ver-+ batim, and with each transaction shown as print normally shows it (so -x,+ --round, --layout etc. still apply). Blank lines are normalised: there is+ one blank line between transactions, and between groups of directive or+ comment lines. The output can be read by hledger as an equivalent journal,+ so this is the mode to use when reformatting or regenerating a journal+ file. Some details:++ * Included files are inlined at the position of their include directive,+ and the include line itself is dropped. If you want to preserve a+ multi-file structure rather than flattening it, currently the best way+ is: comment out the include directives (they will be preserved as com-+ ments), export each file individually, then uncomment the include direc-+ tives in the exported main file. (A file which depends on directives in+ its parent file, such as Y or decimal-mark, might need those added tem-+ porarily while it is exported.)++ * apply account, alias and their end directives are dropped, since their+ effect is already applied to the account names shown. (An account decla-+ ration inside an apply account block is reproduced as written, without+ the parent account prefix.)++ * Directives which hledger ignores (for compatibility with Ledger) are not+ exported.++ * By default, periodic transaction rules (~) and auto posting rules (=) are+ exported as directives. With --forecast and/or --auto, the generated+ transactions (at the end of the output) and postings are exported in-+ stead, and the rules are not. In other words, these flags materialise+ the rules. Postings generated by --infer-equity are exported too. (In+ Beancount output, these rules are never exported, only whatever has been+ generated.)++ * A query still selects which transactions are shown, but all directives+ and comments are kept.++ * Transactions from non-journal files (eg an included CSV file) are added+ at the end.++ * The journal (default), ledger and beancount output formats are supported.+ With -O ledger, transactions use Ledger's lot syntax, and directives+ which hledger accepts but Ledger does not (decimal-mark, a one-line com-+ modity directive with an amount, a periodic transaction rule with a de-+ scription, an auto posting rule with *N amount multipliers) are commented+ out, with an explanatory comment. Other hledger-specific syntax may re-+ main; see Ledger output. With -O beancount, Beancount option, commodity,+ open and price directives are generated from the journal's declarations+ and data, other directives (which have no Beancount equivalent) are+ dropped, and comments are converted to Beancount comments; see Beancount+ output. Note for both Ledger and Beancount, manual fixups may still be+ required in some cases; but the export will be a good start.++ print, other features+ With -B/--cost, amounts with costs are shown converted to cost.++ With --invert, posting amounts are shown with their sign flipped. It could+ be useful if you have accidentally recorded some transactions with the+ wrong signs.++ With --new, print shows only transactions it has not seen on a previous+ run. This uses the same deduplication system as the import command. (See+ import's docs for details.)++ With -m DESC/--match=DESC, print shows one recent transaction whose de-+ scription is most similar to DESC. DESC should contain at least two char-+ acters. If there is no similar-enough match, no transaction will be shown+ and the program exit code will be non-zero.++ With --locations, print adds the source file and line number to every+ transaction, as a tag.++ print output format+ This command also supports the output destination and output format options+ The output formats supported are journal (the default; txt is also ac-+ cepted), ledger, beancount, csv, tsv, html, fods, json and sql.++ The ledger format is currently the same as journal except it renders+ amounts' cost basis using Ledger's lot syntax ([DATE] (LABEL) {COST}) in-+ stead of hledger's ({DATE, "LABEL", COST}).++ The beancount format tries to produce Beancount-compatible output, as fol-+ lows:++ * Transaction and postings with unmarked status are converted to cleared+ (*) status.++ * Transactions' payee and note are backslash-escaped and double-quote-es-+ caped and wrapped in double quotes.++ * Transaction and posting tags are converted to Beancount metadata lines.++ * Commodity symbols are converted to upper case, and a small number of cur-+ rency symbols like $ are converted to the corresponding currency names.++ * Account name parts are capitalised and unsupported characters are re-+ placed with -. The first part must be one of Assets, Liabilities, Eq-+ uity, Income or Expenses; if it is not, but the account's type is known+ (declared or inferred), the corresponding one of those is prepended; oth-+ erwise an error is raised. (Or, use --alias options to bring your ac-+ counts into compliance.)++ * Balance assignments are converted to explicit amounts.++ * Virtual and balanced virtual postings are dropped.++ By default only transactions are shown. With --export, the directives+ Beancount needs are also generated: options (a commented-out tolerance op-+ tion, and operating_currency for the currencies used in costs), a commodity+ directive for each declared commodity, an open directive for each declared+ or used account (on the account's earliest posting date, or the earliest+ transaction date), and price directives. Account and commodity tags become+ metadata on those directives, and an account's lots: tag becomes the Bean-+ count booking method. Other hledger directives are dropped, and top-level+ comments are converted to Beancount comments.++ Here's an example of print's CSV output:++ $ hledger print -Ocsv+ "txnidx","date","date2","status","code","description","comment","account","amount","commodity","debit","credit","posting-status","posting-comment"+ "1","2008/01/01","","","","income","","assets:bank:checking","1","$","1","","",""+ "1","2008/01/01","","","","income","","income:salary","-1","$","","1","",""+ "2","2008/06/01","","","","gift","","assets:bank:checking","1","$","1","","",""+ "2","2008/06/01","","","","gift","","income:gifts","-1","$","","1","",""+ "3","2008/06/02","","","","save","","assets:bank:saving","1","$","1","","",""+ "3","2008/06/02","","","","save","","assets:bank:checking","-1","$","","1","",""+ "4","2008/06/03","","*","","eat & shop","","expenses:food","1","$","1","","",""+ "4","2008/06/03","","*","","eat & shop","","expenses:supplies","1","$","1","","",""+ "4","2008/06/03","","*","","eat & shop","","assets:cash","-2","$","","2","",""+ "5","2008/12/31","","*","","pay off","","liabilities:debts","1","$","1","","",""+ "5","2008/12/31","","*","","pay off","","assets:bank:checking","-1","$","","1","",""++ * There is one CSV record per posting, with the parent transaction's fields+ repeated.++ * The "txnidx" (transaction index) field shows which postings belong to the+ same transaction. (This number might change if transactions are re-+ ordered within the file, files are parsed/included in a different order,+ etc.)++ * The amount is separated into "commodity" (the symbol) and "amount" (nu-+ meric quantity) fields.++ * The numeric amount is repeated in either the "debit" or "credit" column,+ for convenience. (Those names are not accurate in the accounting sense;+ it just puts zero or greater amounts under debit and negative amounts un-+ der credit.)++ register+ (reg)++ Show postings & running total across accounts.++ Flags:+ --cumulative accumulation mode: show running total from report+ start date (default)+ -H --historical accumulation mode: show historical running+ total/balance (includes postings before report+ start date)+ -A --average show running average of posting amounts instead+ of total (implies --empty)+ -m --match=DESC fuzzy search for one recent posting with+ description closest to DESC+ -r --related show postings' siblings instead+ --invert display all amounts with reversed sign+ --drop=N omit N leading account name parts+ --sort=FIELDS sort by: date, desc, account, amount, absamount,+ or a comma-separated combination of these. For a+ descending sort, prefix with -. (Default: date)+ -w --width=N set output width (default: terminal width). -wN,M+ sets description width as well.+ --align-all guarantee alignment across all lines (slower)+ --base-url=URLPREFIX in html output, generate links to hledger-web,+ with this prefix. (Usually the base url shown by+ hledger-web; can also be relative.)+ -O --output-format=FMT select the output format. Supported formats:+ txt, csv, tsv, html, fods, json, svg.+ -o --output-file=FILE write output to FILE. A file extension matching+ one of the above formats selects that format.+ --view write output to FILE, or to view.FMT in hledger's+ cache directory, and open it in the system's+ default viewer for its format (eg a web browser for+ html). The default format is html.+ --chart[=net,SCALE] show a chart: instead of the table (txt), above+ it (html), or as data (csv, tsv, json). net: also+ draw the net total (a line, or marks in text+ charts). SCALE: the amount that fills the chart (eg+ 1000 or 1000 USD; one per commodity), for+ comparable charts.++ The register command displays matched postings, across all accounts, in+ date order, with their running total or running historical balance. (See+ also the aregister command, which shows matched transactions in a specific+ account.)++ register normally shows line per posting, but note that multi-commodity+ amounts will occupy multiple lines (one line per commodity).++ It is typically used with a query selecting a particular account, to see+ that account's activity:++ $ hledger register checking+ 2008/01/01 income assets:bank:checking $1 $1+ 2008/06/01 gift assets:bank:checking $1 $2+ 2008/06/02 save assets:bank:checking $-1 $1+ 2008/12/31 pay off assets:bank:checking $-1 0++ With --date2, it shows and sorts by secondary date instead.++ Postings with a zero amount (including amounts inferred from a balance as-+ signment) are not shown by default; use the --empty/-E flag to see them.++ For performance reasons, column widths are chosen based on the first 1000+ lines; this means unusually wide values in later lines can cause visual+ discontinuities as column widths are adjusted. If you want to ensure per-+ fect alignment, at the cost of more time and memory, use the --align-all+ flag.++ The --historical/-H flag adds the balance from any undisplayed prior post-+ ings to the running total. This is useful when you want to see only recent+ activity, with a historically accurate running balance:++ $ hledger register checking -b 2008/6 --historical+ 2008/06/01 gift assets:bank:checking $1 $2+ 2008/06/02 save assets:bank:checking $-1 $1+ 2008/12/31 pay off assets:bank:checking $-1 0++ The --depth option limits the amount of sub-account detail displayed.++ The --drop option will trim leading segments from account names.++ The --average/-A flag shows the running average posting amount instead of+ the running total (so, the final number displayed is the average for the+ whole report period). This flag implies --empty (see below). It is af-+ fected by --historical. It works best when showing just one account and+ one commodity.++ The --related/-r flag shows the other postings in the transactions of the+ postings which would normally be shown.++ The --invert flag negates all amounts. For example, it can be used on an+ income account where amounts are normally displayed as negative numbers.+ It's also useful to show postings on the checking account together with the+ related account:++ The --sort=FIELDS flag sorts by the fields given, which can be any of ac-+ count, amount, absamount, date, or desc/description, optionally separated+ by commas. For example, --sort account,amount will group all transactions+ in each account, sorted by transaction amount. Each field can be negated+ by a preceding -, so --sort -amount will show transactions ordered from+ smallest amount to largest amount.++ $ hledger register --related --invert assets:checking++ With a reporting interval, register shows summary postings, one per inter-+ val, aggregating the postings to each account:++ $ hledger register --monthly income+ 2008/01 income:salary $-1 $-1+ 2008/06 income:gifts $-1 $-2++ Here too, periods with no activity, and summary postings with a zero+ amount, are not shown by default; use the --empty/-E flag to see them:++ $ hledger register --monthly income -E+ 2008/01 income:salary $-1 $-1+ 2008/02 0 $-1+ 2008/03 0 $-1+ 2008/04 0 $-1+ 2008/05 0 $-1+ 2008/06 income:gifts $-1 $-2+ 2008/07 0 $-2+ 2008/08 0 $-2+ 2008/09 0 $-2+ 2008/10 0 $-2+ 2008/11 0 $-2+ 2008/12 0 $-2++ Often, you'll want to see just one line per interval. The --depth option+ helps with this, causing subaccounts to be aggregated:++ $ hledger register --monthly assets --depth 1+ 2008/01 assets $1 $1+ 2008/06 assets $-1 0+ 2008/12 assets $-1 $-1++ Note when using report intervals, if you specify start/end dates these will+ be adjusted outward if necessary to contain a whole number of intervals.+ This ensures that the first and last intervals are full length and compara-+ ble to the others in the report.++ If you have a deeply nested account tree some reports might benefit from+ trimming leading segments from the account names using --drop.++ $ hledger register --monthly income --drop 1+ 2008/01 salary $-1 $-1+ 2008/06 gifts $-1 $-2++ With -m DESC/--match=DESC, register does a fuzzy search for one recent+ posting whose description is most similar to DESC. DESC should contain at+ least two characters. If there is no similar-enough match, no posting will+ be shown and the program exit code will be non-zero.++ Custom register output+ register normally uses the full terminal width (or 80 columns if it can't+ detect that). You can override this with the --width/-w option.++ The description and account columns normally share the space equally (about+ half of (width - 40) each). You can adjust this by adding a description+ width as part of --width's argument, comma-separated: --width W,D . Here's+ a diagram (won't display correctly in --help):++ <--------------------------------- width (W) ---------------------------------->+ date (10) description (D) account (W-41-D) amount (12) balance (12)+ DDDDDDDDDD dddddddddddddddddddd aaaaaaaaaaaaaaaaaaa AAAAAAAAAAAA AAAAAAAAAAAA++ and some examples:++ $ hledger reg # use terminal width (or 80 on windows)+ $ hledger reg -w 100 # use width 100+ $ hledger reg -w 100,40 # set overall width 100, description width 40++ This command also supports the output destination and output format options+ The output formats supported are txt, csv, tsv, html, fods, json, and svg.++ Register charts+ With --chart, or with svg output (-o FILE.svg), it shows a chart instead.+ Without a report interval, this is the running total (or average) after+ each posting, as a line over time; with postings to several accounts, each+ account's own running total is shown too, in its account type's colour+ (starting from its balance before the report period, with -H), at most+ eight of them, the smallest combined into "other". A text chart has a row+ per posting, with the accounts' running totals stacked. With a report in-+ terval, it is each account's amount in each period, as stacked bars, with+ the period's total. Charts draw the overall running total (with several+ accounts) or the periods' totals only with --chart=net. With --chart -O+ csv (or tsv or json) it shows the chart's data. See also Balance charts.++ roi+ Show the money-weighted (IRR) and time-weighted (TWR) rate of return on+ your investments.++ Flags:+ --cashflow show all amounts that were used to compute+ returns+ --investment=QUERY query to select your investment transactions+ --profit-loss=QUERY --pnl query to select profit-and-loss or+ appreciation/valuation transactions (optional)++ At a minimum, you need to supply a query (which could be just an account+ name) to select your investment(s) with --inv.++ An optional second query to identify your profit and loss transactions+ could be given with --pnl. If your investment's value changes are captured+ solely through price directives (rather than manual P&L journal entries),+ or if you do not need TWR, you can simply omit --pnl, and no transactions+ will be classed as profit and loss in this case.++ This command will compute and display the internal rate of return (IRR,+ also known as money-weighted rate of return) and time-weighted rate of re-+ turn (TWR) for your investments for the time period requested. IRR is al-+ ways annualized due to the way it is computed, but TWR is reported both as+ a rate over the chosen reporting period and as an annual rate.++ Price directives will be taken into account if you supply appropriate+ --cost or --value flags (see Value reporting).++ Some special cases of IRR have no solution in the usual sense, and are re-+ ported as:++ * 0%, when there are no cash flows, or when they all fall on the same day+ and add up to zero (nothing is gained or lost, and no time passes)++ * -100%, when money is put in, but nothing comes out of the investment or+ is left in it (all of it is lost). A total loss is -100% however long+ the money was invested, even for a day. (But a partial loss within one+ day is an error, below, since its annual rate depends on how much time+ passes.)++ In some cases a rate of return can't be computed. Then its cell in the re-+ port shows error, the rest of the report is still shown, and the reasons+ (each with its period) are printed after it as a warning. The reasons can+ be:++ * No solution for Internal Rate of Return (IRR). Possible causes: IRR is+ huge (>1000000%), balance of investment becomes negative at some point in+ time.++ * No solution for Internal Rate of Return (IRR), because money only came+ out of the investment in that period (or is still in it at the end), and+ none was put in (counting its value at the start as put in), so the IRR+ is infinite.++ * No solution for Internal Rate of Return (IRR), because all of a period's+ cash flows (including the values at its start and end) fall on the same+ day, so no time passes for the gain or loss to happen in.++ * Failed to find solution for Internal Rate of Return (IRR). Either search+ does not converge to a solution, or converges too slowly.++ * Cannot compute the time-weighted return for DATES (PART): the invest-+ ment's value at the start (...) plus deposits (...) is negative. Pos-+ sible cause: the balance of the investment becomes negative, eg more is+ sold than is held (a short position).++ And in some cases the whole report can't be produced:++ * Error: Could not value the investment on DATE: no market price ... is+ known for COMMODITY on or before that date. A holding has no market+ price, and none of the investment's transactions on or before that date+ records a price for buying or selling it. Add a P directive for it, or+ record the price of its purchase.++ * Error: Period ... has multiple commodities: ... The investment, its+ cash flows or its profit and loss are in more than one commodity. Use+ --value to convert them to one (eg --value=end,$ --infer-market-prices).++ Examples:++ * Using roi to compute total return of investment in stocks:+ https://github.com/hledgerorg/hledger/blob/main/examples/invest-+ ing/roi-unrealised.ledger++ * Cookbook > Return on Investment: https://hledger.org/roi.html++ Spaces and special characters in --inv and --pnl+ Note that --inv and --pnl's argument is a query, and queries could have+ several space-separated terms (see QUERIES).++ To indicate that all search terms form single command-line argument, you+ will need to put them in quotes (see Special characters):++ $ hledger roi --inv 'term1 term2 term3 ...'++ If any query terms contain spaces themselves, you will need an extra level+ of nested quoting, eg:++ $ hledger roi --inv="'Assets:Test 1' cur:USD" --pnl="'Equity:Unrealized Profit and Loss'"++ Semantics of --inv and --pnl+ Query supplied to --inv has to match all transactions that are related to+ your investment. Transactions not matching --inv will be ignored.++ In these transactions, ROI will consider postings that match --inv to be+ "investment postings" and other postings (not matching --inv) will be+ sorted into two categories: "cash flow" and "profit and loss", as ROI needs+ to know which part of the investment value is your contributions and which+ is due to the return on investment.++ * "Cash flow" is depositing or withdrawing money, buying or selling assets,+ or otherwise converting between your investment commodity and any other+ commodity. Example:++ 2019-01-01 Investing in Snake Oil+ assets:cash -$100+ investment:snake oil++ 2020-01-01 Selling my Snake Oil+ assets:cash $10+ investment:snake oil = 0++ * "Profit and loss" is change in the value of your investment:++ 2019-06-01 Snake Oil falls in value+ investment:snake oil = $57+ equity:unrealized profit or loss++ All non-investment postings are assumed to be "cash flow", unless they+ match --pnl query. Changes in value of your investment due to "profit and+ loss" postings will be considered as part of your investment return.++ The amount of each cash flow is measured from the investment's perspective:+ it is the cost of the transaction's investment postings, minus any profit+ and loss in that transaction. Its date is the date of those investment+ postings, even if the money's posting has a different date (eg a settlement+ date). This means that other postings in the same transaction, such as+ fees, don't change the amount of the cash flow.++ In this example, the investment receives $100, so without --pnl the cash+ flow is a $100 deposit, and the $1 fee is not part of the investment at+ all. With --pnl expenses, the fee counts as part of the investment's re-+ turn instead: the cash flow is a $101 deposit, of which $1 is immediately+ lost (shown as profit/loss of -$1):++ 2019-01-01 Buying Snake Oil, with a fee+ assets:cash -$101+ expenses:fees $1+ investment:snake oil $100++ Example: if you use --inv snake --pnl equity:unrealized, then postings in+ the example below would be classifed as:++ 2019-01-01 Snake Oil #1+ assets:cash -$100 ; cash flow posting+ investment:snake oil ; investment posting++ 2019-03-01 Snake Oil #2+ equity:unrealized pnl -$100 ; profit and loss posting+ snake oil ; investment posting++ 2019-07-01 Snake Oil #3+ equity:unrealized pnl ; profit and loss posting+ cash -$100 ; cash flow posting+ snake oil $50 ; investment posting++ Using roi with lots+ If your journal records lots, each disposal transaction has a realised gain+ posting, by default to revenues:gain. Make sure --pnl matches that ac-+ count, eg --pnl revenues:gain, so realised gains are counted as profit.+ Cash flows are measured at the investment postings' cost, which for lots is+ their cost basis, so without --pnl a sale is a withdrawal of its cost basis+ only, and its gain is not counted at all: IRR and TWR will understate the+ return (eg showing 0% for a buy and a sale at a profit).++ IRR and TWR explained+ "ROI" stands for "return on investment". Traditionally this was computed+ as a difference between current value of investment and its initial value,+ expressed in percentage of the initial value.++ However, this approach is only practical in simple cases, where the invest-+ ment receives no in-flows or out-flows of money and the rate of growth is+ fixed over time. For more complex scenarios you need different ways to+ compute rate of return, and this command implements two of them: IRR and+ TWR.++ Internal rate of return (IRR), also called money-weighted rate of return,+ answers the question: what single constant annual interest rate, applied to+ your actual sequence of deposits and withdrawals, would produce exactly the+ ending balance you have?++ IRR is inherently personal. If you deposited a large sum right before a+ bad period, your IRR is dragged down - not because the investment was+ poorly managed, but because your timing was bad. Conversely, investing+ heavily just before a rally makes your IRR look great. This is what makes+ IRR "money-weighted": periods when more of your money is at stake con-+ tribute more to the result.++ In technical terms, IRR uses the same approach as computation of net+ present value, and tries to find a discount rate that makes the net present+ value of all the cash flows of your investment add up to zero. The imple-+ mentation in hledger produces results that match the =XIRR formula in Ex-+ cel.++ Time-weighted rate of return (TWR) strips out the effect of your deposit+ and withdrawal timing, measuring the investment's own performance rather+ than your experience of it.++ hledger computes TWR from the value of your investment at the end of each+ day: its balance at the end of the day, valued (with --value) using the+ prices in effect on that day. The order of transactions and prices within+ a day doesn't matter.++ * The days between two days with cash flows form one stretch, which starts+ at the end of the earlier cash flow day and ends at the end of the day+ before the later one. Its return is the ratio of the investment's values+ at those two moments. For example, with cash flows on March 1 and March+ 10, the stretch is March 2 to 9, and its return is (value at the end of+ March 9) / (value at the end of March++ 1) * .RS 2++ 1. (March 10 itself is a day with cash flows, handled as below.)++ * A day with cash flows is split in two parts:++ 1. The day's price changes: the return of the holdings carried over from+ the previous day, from their value at the previous day's prices to+ their value at this day's prices. (This part is skipped if no prices+ changed.)++ 2. The cash flows, as if all of the day's trades were made at the day's+ closing prices. Its return is (value at the end of the day - with-+ drawals) / (value after part 1 + deposits) - 1, with withdrawals nega-+ tive. That is, the day's deposits count as invested during this part,+ as if made at its start, and its withdrawals count as still invested+ during it, as if made at its end. So any difference between the+ prices you traded at and the closing prices shows up in this part's+ return.++ * Times when nothing is invested earn nothing. That includes a day on+ which something arrives in an empty investment only as profit and loss+ (eg a stock grant, booked to an account matched by --pnl): there is noth-+ ing to compute a return on, so that day's return is 0%.++ * A holding which has no market price is valued at the price of the invest-+ ment's latest purchase or sale of it, on or before that day (as --in-+ fer-market-prices would do, but only from the investment's own transac-+ tions, and only while no market price is known). If there are several on+ a day, the last one recorded is used. Like any price, it applies to the+ whole holding on that day, including what was held before the trade, so a+ trade at a new price can show up in --cashflow output as a "prices" row,+ before its cash flows. And a trade recorded at zero cost (eg a gift,+ recorded with @ $0) gives a price of 0, so such a holding is worth noth-+ ing until a market price is known; add a P directive for it.++ All these returns are then multiplied together (geometrically chained) to+ give the TWR for the full period. In multi-period reports, each period be-+ gins with the value the previous one ended with, so the periods' returns+ chain to the total.++ Use --value=then for TWR, so that each day is valued with the prices of+ that day. With --value=end, --value=now or --value=DATE, all the values in+ a period use the same prices, so its TWR only reflects recorded profit and+ loss and the differences between the prices you traded at and those prices.+ With --value=end, each period is also valued with its own end's prices, so+ the periods' returns don't chain to the total.++ TWR can only be as good as the values your journal gives for each day. If+ you record changes in value only occasionally (with --pnl transactions, or+ with sparse price directives), the growth since the previous record is at-+ tributed to the day you record it, and so is counted on whatever was in-+ vested on that day. If you made a large deposit or withdrawal in between,+ that can make TWR quite different from what it would be if the growth had+ been spread out. So record a valuation around large deposits and with-+ drawals (professional performance standards require this too), or use price+ directives, or --infer-market-prices if your transactions record their+ prices.++ In short: TWR tells you how good the investment was; IRR tells you how good+ your experience of the investment was.++ Checking the results+ --cashflow shows everything that IRR and TWR are computed from, so that you+ can check them against your journal, against other hledger reports, or in a+ spreadsheet:++ * IRR cash flows: one row per cash flow, with the transaction's descrip-+ tion, the cost of its investment postings, and its profit or loss, be-+ tween the investment's value at the start and its value at the end (dated+ the day after the period's last day, since it is the value at the end of+ that day). Amounts are from your point of view: what you put in is nega-+ tive, what you take out or still have is positive. The dates and amounts+ can be given to Excel's =XIRR as they are.++ * TWR returns: one row for each stretch without cash flows, and for each+ day with cash flows, a row for its price changes (if any) and a row for+ its cash flows. Each row's Value (begin) is the previous row's Value+ (end), and each row's return is++ (Value (end) - Withdrawals) / (Value (begin) + Deposits) - 1++ where withdrawals are negative. The Cumulative column chains the returns+ by multiplication: each row's (1 + Cumulative) is the previous row's (1 ++ Cumulative) times (1 + Return). Its last row is the period's TWR.++ The values can be checked with hledger balance: the value at the end of a+ day D is the investment's historical balance at the end of that day, valued+ then. For example, if you ran roi --value=then,$, check the value at the+ end of day D with:++ $ hledger balance --historical --value=end,$ -e D+1 INVESTMENTQUERY++ (where D+1 is the day after D; --value=end values at the end of the report+ period, which is day D). Holdings which have no market price are the ex-+ ception, as roi values them at the price of their latest purchase or sale.++ When each matters++ Use IRR when you want to know your actual personal return - what you earned+ on your money, accounting for when you chose to move it. It is the right+ measure when evaluating your own deposit and withdrawal timing decisions.++ Use TWR when you want to evaluate the investment vehicle itself, indepen-+ dent of your deposit timing. It is the right measure when comparing two+ funds or strategies, or when asking whether you would have been better off+ elsewhere. TWR is the standard that professional investment managers use+ to report fund performance, precisely because it removes the distortion+ caused by investor cash flows.++ References:++ * Explanation of rate of return++ * Explanation of IRR++ * Explanation of TWR++ * IRR vs TWR++ * Examples of computing IRR and TWR and discussion of the limitations of+ both metrics++ stats+ Show journal and performance statistics.++ Flags:+ -q --oneline show a single line of output+ -v --verbose show more detailed output+ -o --output-file=FILE write output to FILE.++ The stats command shows summary information for the whole journal, or a+ matched part of it. With a reporting interval, it shows a report for each+ report period.++ It also shows some performance statistics:++ * how long the program ran for++ * the number of transactions processed per second++ * the peak live memory in use by the program to do its work++ * the peak allocated memory as seen by the program++ By default, the output is reasonably discreet; it reveals the main file+ name, your activity level, and the speed of your machine.++ With -v/--verbose, more details are shown: the full paths of all files, and+ the names of the commodities you work with.++ With -q/--oneline, only one line of output is shown, in a machine-friendly+ tab-separated format: the program version, the main journal file name, and+ the performance stats,++ The run time of stats is similar to that of a balance report.++ Example:++ $ hledger stats -f examples/1ktxns-1kaccts.journal+ Main file : .../1ktxns-1kaccts.journal+ Included files : 0+ Txns span : 2000-01-01 to 2002-09-27 (1000 days)+ Last txn : 2002-09-26 (7827 days ago)+ Txns : 1000 (1.0 per day)+ Txns last 30 days : 0 (0.0 per day)+ Txns last 7 days : 0 (0.0 per day)+ Payees/descriptions : 1000+ Accounts : 1000 (depth 10)+ Commodities : 26+ Base currency : B+ Market prices : 1000+ Runtime stats : 0.12 s elapsed, 8266 txns/s, 4 MB live, 16 MB alloc++ $ hledger stats -q -f examples/10ktxns-1kaccts.journal+ 1.50.99-g0835a2485-20251119, mac-aarch64 10ktxns-1kaccts.journal 0.66 s elapsed 15244 txns/s 28 MB live 86 MB alloc++ This command supports the -o/--output-file option (but not -O/--output-for-+ mat).++ tags+ List the tag names used or declared in the journal, or their values.++ Flags:+ --used list tags used+ --declared list tags declared+ --undeclared list tags used but not declared+ --unused list tags declared but not used+ --find list the first tag whose name is matched by the+ first argument (a case-insensitive infix regexp)+ --values list tag values instead of tag names+ --parsed show them in the order they were parsed (mostly),+ including duplicates+ --directives show tag names as tag directives, for use in+ journals++ This command lists tag names - all of them by default, or just the ones+ which have been used on transactions/postings/accounts, or declared with+ tag directives, or used but not declared, or declared but not used, or just+ the first one matched by a pattern (with --find, returning a non-zero exit+ code if it fails).++ Note this command's non-standard first argument: it is a case-insensitive+ infix regular expression for matching tag names, which limits the tags+ shown. Any additional arguments are standard query arguments, which limit+ the transactions, postings, or accounts providing tags.++ With --values, the tags' unique non-empty values are listed instead.++ With -E/--empty, blank/empty values are also shown.++ With --parsed, tags or values are shown in the order they were parsed, with+ duplicates included. (Except, tags from account declarations are always+ shown first.)++ With --directives, tag names are shown as valid tag directives, which could+ be pasted into a journal file.++ Remember that accounts also acquire tags from their parents; postings also+ acquire tags from their account and transaction; and transactions also ac-+ quire tags from their postings.++ Examples:++ $ hledger tags+ broker+ receipt+ trip++ $ hledger tags --values+ acme+ paris++ transactions+ (tx)++ List transactions, one per line.++ Flags:+ -m --match=DESC fuzzy search for one recent transaction with+ description closest to DESC++ This command shows each transaction's first line only (the date, status,+ code, description, and any same-line comment), giving a compact overview of+ a journal, in the manner of git log --oneline. You can add a query to se-+ lect a subset of transactions. (To see full journal entries, use the print+ command.)++ Example:++ $ hledger transactions -f examples/sample.journal+ 2008-01-01 income+ 2008-06-01 gift+ 2008-06-02 save+ 2008-06-03 * eat & shop+ 2008-12-31 * pay off++Maintenance commands+ setup+ Check the status of the hledger installation.++ Flags:+ no command-specific flags++ setup tests your hledger installation and prints a list of results, some-+ times with helpful hints. This is a good first command to run after in-+ stalling hledger. Also after upgrading, or when something's not working,+ or just when you want a reminder of where things are.++ It makes one network request to detect the latest hledger release version.+ It's ok if this fails or times out. It will use ANSI color by default, un-+ less disabled by NO_COLOR or --color=n. It does not use a pager or a con-+ fig file.++ It expects that the hledger version you are running is installed in your+ PATH. If not, it will stop until you have done that (to keep things sim-+ ple).++ Example:++ $ hledger setup+ Checking your setup (and contacting hledger.org to find out the current release):+ hledger+ is running on macos 27.0 on aarch64+ is built with a supported compiler/RTS yes ghc 9.14.1, using threaded RTS+ is a native binary for this machine ? yes aarch64+ is a released version ? yes hledger 1.52.4, mac-aarch64+ is up to date ? checking latest... yes latest is 1.52.4, 1.52.4 is installed+ is installed in PATH (this version) ? yes /Users/user/.local/bin/hledger+ has a system text encoding configured ? yes UTF-8, data files must use this encoding+ has a user config file ? yes /Users/user/.hledger.conf+ has a local config file ? no+ the config file is readable ? yes+ terminal+ the TERM variable is defined ? yes xterm-256color+ the terminal supports ANSI color ? yes+ ...+ journal+ the LEDGER_FILE variable is defined ? yes /Users/user/finance/main.journal+ a default journal file is readable ? yes /Users/user/finance/main.journal+ ...++ init+ Create starter files for a new hledger setup, or add missing ones to an ex-+ isting setup.++ Flags:+ --layout=LAYOUT which file layout to write: simple, default, years+ (default: default)+ --dry-run just show the files that would be created++ With no argument, or a directory argument, init writes a set of files in+ that directory (the current directory by default), creating it if needed.+ Which files depends on the layout chosen with --layout. Note, these are+ just to help you get started; you can always change the file layout to suit+ your needs.++ simple:++ Just one file. Good if you want simplicity and manual data entry.++ * main.journal - the journal file, with optional declarations++ default (the default):++ Declarations are kept separate; subdirectories and starter scripts for+ data-fetching are provided. This is a good maintainable layout that+ hledger commands understand well.++ * main.journal - the main journal file, with a few example transactions++ * accounts.journal, commodities.journal, payees.journal - declarations++ * data/ - downloaded CSV files go here, with data/getdata, a starter script+ for get++ * prices/ - market prices go here, with prices/getprices, a starter script+ for get++ * rules/ - CSV rules files go here++ * an example CSV file and rules file++ years:++ Like default, but each year has its own journal file. This gives you a+ choice of loading all years or one year at a time (see close). It makes+ life a little more complicated, but it is worthwhile if you have enough+ data that a single file becomes slow on your machine; or if you want to+ compartmentalise the data for other reasons.++ * YEAR.journal (eg 2026.journal) - this year's journal, with a few example+ transactions.++ * all.journal - includes all the year journals, for multi-year reports++ * the same declaration files, directories and examples as default++ With a journal file argument (a path ending with .journal, .j, .hledger or+ .ledger), you'll get the simple layout, written to that file.++ Files that already exist are never changed; they are skipped, with a warn-+ ing. So you can run init again to add missing files. After writing the+ files, it suggests some next steps.++ These and other file layouts can also be seen in the hledger repo's exam-+ ples/file-layouts directory.++ Examples:++ $ hledger init --dry-run # show what would be created in the current directory+ $ hledger init ~/finance # create a standard setup in ~/finance+ $ hledger init --layout years ~/finance # create a setup with a journal per year in ~/finance+ $ hledger init 2026.journal # create a single journal file++ check+ Check that your data is valid, using hledger's built-in correctness checks.++ Flags:+ no command-specific flags++ hledger provides a number of built-in correctness checks to help validate+ your data and prevent errors. Some are run automatically, some when you+ enable --strict mode; or you can run any of them on demand by providing+ them as arguments to the check command. check produces no output and a+ zero exit code if all is well. Eg:++ hledger check # run default checks+ hledger check -s # run default and strict checks+ hledger check ordereddates payees # run default checks and two others+ hledger check 'assert none daily type:A balance:<0' # run default checks and a custom rule++ If you are an Emacs user, you can also configure flycheck-hledger to run+ these checks, providing instant feedback as you edit the journal.++ Here are the checks currently available. They are generally checked in the+ order they are shown here, and only the first failure will be reported.++ Default checks+ These important checks are performed by default, by almost all hledger com-+ mands:++ * parseable - data files are in a supported format, with no syntax errors+ and no invalid include directives. This ensures that all files exist and+ are readable.++ * autobalanced - all transactions are balanced, after automatically infer-+ ring missing amounts and conversion rates and then converting amounts to+ cost. This ensures that each transaction's journal entry is well formed.++ * assertions - all balance assertions and assert directives in the journal+ are passing. Balance assertions are a strong defense against errors,+ catching many problems; assert directives check standing rules, like "no+ asset account is ever negative". This check is on by default, but if it+ gets in your way, you can disable it temporarily with -I or --ignore-as-+ sertions, or as a default by adding that flag to your config file. If+ you put it in your config file, you can override that with -s/--strict or+ hledger check assertions. When a journal has both kinds of problem, lot+ errors are reported before assertion failures, and balance assertion+ failures before assert directive failures.++ * lots - all lot entries are valid. Checks lot posting classifications,+ lot movements, that an acquisition writing both a cost basis and a trans-+ acted cost has them agree (a mismatch would silently miscalculate gains),+ and that any user-written realised gain amount on a disposal matches the+ calculated gain. This check can be disabled by -I or --ignore-lots. If+ you put it in your config file, you can override that with -s/--strict or+ hledger check lots.++ Strict checks+ When the -s/--strict flag is used (AKA strict mode), all commands will per-+ form the following additional checks. These provide extra error-catching+ power to help you keep your data clean and correct:++ * balanced - like autobalanced, but implicit conversions between commodi-+ ties are not allowed; all conversion transactions must use cost notation+ or equity postings. This prevents wrong conversions caused by typos.++ * commodities - all commodity symbols used must be declared. This guards+ against mistyping or omitting commodity symbols.++ * accounts - all account names used must be declared. This prevents the+ use of mis-spelled or outdated account names. (Except lot subaccounts,+ like :{2026-01-15, $50}, which are automatically exempt; only their base+ account needs to be declared. And the accounts of postings generated by+ hledger, such as equity conversion, gain, and imbalance postings.)++ Also, strict mode ensures that the assertions and lots checks run (overrid-+ ing their ignore flags).++ Other checks+ These are not wanted by everyone, but can be run using the check command:++ * tags - all tags used must be declared (tags on transactions, postings,+ and account and commodity directives; except the special tags). This+ prevents mis-spelled tag names. Note hledger fairly often finds unin-+ tended tags in comments.++ * payees - all payees used in transactions must be declared. This will+ force you to declare any new payee name before using it. Most people+ will probably find this a bit too strict.++ * ordereddates - within each file, transactions must be ordered by date.+ (Forecast transactions are not checked.) This is a simple and effective+ error catcher. It's not included in strict mode, but you can add it by+ running hledger check -s ordereddates. If enabled, this check is per-+ formed before balance assertions.++ * recentassertions - all accounts with balance assertions must have one+ that's within the 7 days before their latest posting. This will encour-+ age adding balance assertions for your active asset/liability accounts,+ which in turn should encourage you to reconcile regularly with those real+ world balances - another strong defense against errors. (hledger close+ --assert >>$LEDGER_FILE is a convenient way to add new balance asser-+ tions. Later these become quite redundant, and you might choose to re-+ move them to reduce clutter.)++ * uniqueleafnames - no two accounts may have the same last account name+ part (eg the checking in assets:bank:checking). This ensures each ac-+ count can be matched by a unique short name, easier to remember and to+ type.++ Assert rules+ You can also check custom rules, written like assert directives. Give each+ one as a single quoted argument, written exactly as the directive would be+ written in the journal. Eg:++ hledger check 'assert none daily type:A balance:<0'+ hledger check 'assert some monthly income:salary' 'assert none assets:oldbank date:2025-'++ This is a convenient way to try out a rule before adding it to the journal,+ or to check rules you don't want to keep there. Unlike assert directives,+ these rules check all of the data files read, combined (not each file tree+ separately), and they are checked even with -I. They are checked after any+ other checks requested. (A plain assert argument, with nothing after it,+ is short for the assertions check.)++ Custom checks+ You can build your own custom checks with add-on command scripts. See also+ Cookbook > Scripting. Here are some examples from hledger/bin/:++ * hledger-check-tagfiles - all tag values containing / exist as file paths++ diff+ Compare a particular account's transactions in two input files. It shows+ any transactions to this account which are in one file but not in the+ other.++ Flags:+ no command-specific flags++ More precisely: for each posting affecting this account in either file,+ this command looks for a corresponding posting in the other file which+ posts the same amount to the same account (ignoring date, description,+ etc).++ Since it compares postings, not transactions, this also works when multiple+ bank transactions have been combined into a single journal entry.++ This command is useful eg if you have downloaded an account's transactions+ from your bank (eg as CSV data): when hledger and your bank disagree about+ the account balance, you can compare the bank data with your journal to+ find out the cause.++ Examples:++ $ hledger diff -f $LEDGER_FILE -f bank.csv assets:bank:giro+ These transactions are in the first file only:++ 2014/01/01 Opening Balances+ assets:bank:giro EUR ...+ ...+ equity:opening balances EUR -...++ These transactions are in the second file only:++Data generation commands+ close+ (equity)++ Print several kinds of "closing" and/or "opening" transactions, useful eg+ when migrating balances to a new journal file, retaining earnings into eq-+ uity, consolidating balances, or viewing lot costs. Like print, it prints+ valid journal entries. You can copy these into your journal file(s) when+ you are happy with how they look.++ Flags:+ --clopen[=TAGVAL] show closing and opening balances transactions,+ for AL accounts by default+ --close[=TAGVAL] show just a closing balances transaction+ --open[=TAGVAL] show just an opening balances transaction+ --assert[=TAGVAL] show a balance assertions transaction+ --assign[=TAGVAL] show a balance assignments transaction+ --retain[=TAGVAL] show a retain earnings transaction, for RX+ accounts by default+ -x --explicit show all amounts explicitly+ --show-costs show amounts with different costs separately+ --interleaved show source and destination postings together+ --assertion-type=TYPE =, ==, =* or ==*+ --close-desc=DESC set closing transaction's description+ --close-acct=ACCT set closing transaction's destination account+ --open-desc=DESC set opening transaction's description+ --open-acct=ACCT set opening transaction's source account+ --round=TYPE how much rounding or padding should be done when+ displaying amounts ?+ none - show original decimal digits,+ as in journal (default)+ soft - just add or remove decimal zeros+ to match precision+ hard - round posting amounts to precision+ (can unbalance transactions)+ all - also round cost amounts to precision+ (can unbalance transactions)+ --layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 - right-align amounts, as in hledger 1+ COL - align decimal marks at column COL+ (default: 53)++ close has six modes, selected by choosing one of the mode flags: --clopen,+ --close (default), --open, --assert, --assign, or --retain. They are all+ doing the same kind of operation, but with different defaults for different+ situations.++ The journal entries generated by close will have a clopen: tag, which is+ helpful when you want to exclude them from reports. If the main journal+ file name contains a number, the tag's value will be that base file name+ with the number incremented. Eg if the journal file is 2025.journal, the+ tag will be clopen:2026. Or you can set the tag value by providing an ar-+ gument to the mode flag. Eg --close=foo or --clopen=2025-main.++ close --clopen+ This is useful if migrating balances to a new journal file at the start of+ a new year. It prints a "closing balances" transaction that zeroes out ac-+ count balances (Asset and Liability accounts, by default), and an opposite+ "opening balances" transaction that restores them again. Typically, you+ would run++ hledger close --clopen -e NEWYEAR >> $LEDGER_FILE++ and then move the opening transaction from the old file to the new file+ (and probably also update your LEDGER_FILE environment variable).++ Why might you do this ? If your reports are fast, you may not need it.+ But at some point you will probably want to partition your data by time,+ for performance or data integrity or regulatory reasons. A new file or set+ of files per year is common. Then, having each file/fileset "bookended"+ with opening and closing balance transactions will allow you to freely pick+ and choose which files to read - just the current year, any past year, any+ sequence of years, or all of them - while showing correct account balances+ in each case. The earliest opening balances transaction sets correct+ starting balances, and any later closing/opening pairs will harmlessly can-+ cel each other out.++ The balances will be transferred to and from equity:opening/closing bal-+ ances by default. You can override this by using --close-acct and/or+ --open-acct.++ You can select a different set of accounts to close/open by providing an+ account query. Eg to add Equity accounts, provide arguments like assets+ liabilities equity or type:ALE. When migrating to a new file, you'll usu-+ ally want to bring along the AL or ALE accounts, but not the RX accounts+ (Revenue, Expense).++ Assertions will be added indicating and checking the new balances of the+ closed/opened accounts.++ close --close+ This prints just the closing balances transaction of --clopen. It is the+ default if you don't specify a mode.++ More customisation options are described below. Among other things, you+ can use close --close to generate a transaction moving the balances from+ any set of accounts, to a different account. (If you need to move just a+ portion of the balance, see hledger-move.)++ close --open+ This prints just the opening balances transaction of --clopen. (It is sim-+ ilar to Ledger's equity command.)++ close --assert+ This prints a transaction that asserts the account balances as they are on+ the end date (and adds an assert: tag). It could be useful as documention+ and to guard against changes.++ close --assign+ This prints a transaction that assigns the account balances as they are on+ the end date (and adds an "assign:" tag). Unlike balance assertions, as-+ signments will post changes to balances as needed to reach the specified+ amounts.++ This is another way to set starting balances when migrating to a new file,+ and it will set them correctly even in the presence of earlier files which+ do not have a closing balances transaction. However, it can hide errors,+ and disturb the accounting equation, so --clopen is usually recommended.++ close --retain+ This is like --close, but it closes Revenue and Expense account balances by+ default. They will be transferred to equity:retained earnings, or another+ account specified with --close-acct.++ Revenues and expenses correspond to changes in equity. They are cate-+ gorised separately for reporting purposes, but traditionally at the end of+ each accounting period, businesses consolidate them into equity, This is+ called "retaining earnings", or "closing the books".++ In personal accounting, there's not much reason to do this, and most people+ don't. (One reason to do it is to help the balancesheetequity report show+ a zero total, demonstrating that the accounting equation (A-L=E) is satis-+ fied.)++ close customisation+ In all modes, the following things can be overridden:++ * the accounts to be closed/opened, with account query arguments++ * the closing/opening dates, with -e OPENDATE++ * the balancing account, with --close-acct=ACCT and/or --open-acct=ACCT++ * the transaction descriptions, with --close-desc=DESC and --open-desc=DESC++ * the transactions' clopen tag value, with a TAGVAL argument for the mode+ flag (see above).++ By default, the closing date is yesterday, or the journal's end date,+ whichever is later; and the opening date is always one day after the clos-+ ing date. You can change these by specifying a report end date; the clos-+ ing date will be the last day of the report period. Eg -e 2024 means+ "close on 2023-12-31, open on 2024-01-01".++ With --x/--explicit, the balancing amount will be shown explicitly, and if+ it involves multiple commodities, a separate posting will be generated for+ each of them (similar to print -x).++ With --interleaved, each individual transfer is shown with source and des-+ tination postings next to each other (perhaps useful for troubleshooting).++ With --show-costs, balances' costs are also shown, with different costs+ kept separate. This may generate very large journal entries, if you have+ many currency conversions or investment transactions. close --show-costs+ is currently the best way to view investment lots with hledger. (To move+ or dispose of lots, see the more capable hledger-move script.) With+ --lots, lot subaccount balances are always shown without costs, even under+ --show-costs: their cost information is carried by the lot name itself, and+ transacted costs on lot postings would prevent the output from being read+ back. For lots using the AVERAGE or AVERAGEALL cost basis method, whose+ lot names normally leave out the cost, the pool's average cost as of the+ closing date is added to each lot name (eg {2026-01-15, $55}), so that the+ output can be read back, eg to start a new file. A non-terminating average+ is written with up to 8 decimal places, so the re-opened lots' total cost+ basis may differ from the original by a tiny amount.++ close and balance assertions+ close adds balance assertions verifying that the accounts have been reset+ to zero in a closing transaction or restored to their previous balances in+ an opening transaction. These provide useful error checking, but you can+ ignore them temporarily with -I, or remove them if you prefer.++ With --lots, balance assertions are not generated for the lot subaccount+ postings in closing transactions (assertions on lot postings get confusing,+ because they apply to the parent account).++ Single-commodity, subaccount-exclusive balance assertions (=) are generated+ by default. This can be changed with --assertion-type='==*' (eg).++ When running close you should probably avoid using -C, -R, status: (filter-+ ing by status or realness) or --auto (generating postings), since the gen-+ erated balance assertions would then require these.++ Transactions with multiple dates (eg posting dates) spanning the file+ boundary also can disrupt the balance assertions:++ 2023-12-30 a purchase made in december, cleared in january+ expenses:food 5+ assets:bank:checking -5 ; date: 2023-01-02++ To solve this you can transfer the money to and from a temporary account,+ splitting the multi-day transaction into two single-day transactions:++ ; in 2022.journal:+ 2022-12-30 a purchase made in december, cleared in january+ expenses:food 5+ equity:pending -5++ ; in 2023.journal:+ 2023-01-02 last year's transaction cleared+ equity:pending 5 = 0+ assets:bank:checking -5++ close examples+ Retain earnings+ Record 2022's revenues/expenses as retained earnings on 2022-12-31, append-+ ing the generated transaction to the journal:++ $ hledger close --retain -f 2022.journal -p 2022 >> 2022.journal++ After this, to see 2022's revenues and expenses you must exclude the retain+ earnings transaction:++ $ hledger -f 2022.journal is not:desc:'retain earnings'++ Migrate balances to a new file+ Close assets/liabilities on 2022-12-31 and re-open them on 2023-01-01:++ $ hledger close --clopen -f 2022.journal -p 2022+ # copy/paste the closing transaction to the end of 2022.journal+ # copy/paste the opening transaction to the start of 2023.journal++ After this, to see 2022's end-of-year balances you must exclude the closing+ balances transaction:++ $ hledger -f 2022.journal bs not:desc:'closing balances'++ For more flexibility, it helps to tag closing and opening transactions with+ eg clopen:NEWYEAR, then you can ensure correct balances by excluding all+ opening/closing transactions except the first, like so:++ $ hledger bs -Y -f 2021.j -f 2022.j -f 2023.j expr:'tag:clopen=2021 or not tag:clopen'+ $ hledger bs -Y -f 2021.j -f 2022.j expr:'tag:clopen=2021 or not tag:clopen'+ $ hledger bs -Y -f 2022.j -f 2023.j expr:'tag:clopen=2022 or not tag:clopen'+ $ hledger bs -Y -f 2021.j expr:'tag:clopen=2021 or not tag:clopen'+ $ hledger bs -Y -f 2022.j expr:'tag:clopen=2022 or not tag:clopen'+ $ hledger bs -Y -f 2023.j # unclosed file, no query needed++ More detailed close examples+ See examples/multi-year.++ rewrite+ Print all transactions, adding auto postings to some of them. For now the+ only rewrite available is adding new postings, like print --auto.++ Flags:+ --add-posting='ACCT AMTEXPR' add a posting to ACCT, which may be+ parenthesised. AMTEXPR is either a literal+ amount, or *N which means the transaction's+ first matched amount multiplied by N (a+ decimal number). Two spaces separate ACCT+ and AMTEXPR.+ --diff generate diff suitable as an input for+ patch tool+ --verbose-tags add tags indicating generated/modified+ data+ --layout=hledger1|COL how should posting amounts be aligned ?+ hledger1 - right-align amounts, as in+ hledger 1+ COL - align decimal marks at column+ COL (default: 53)++ This is a start at a generic rewriter of transaction entries. It reads the+ default journal and prints the transactions, like print, but adds one or+ more specified postings to any transactions matching QUERY. The posting+ amounts can be fixed, or a multiplier of the existing transaction's first+ posting amount.++ Examples:++ $ hledger-rewrite.hs ^income --add-posting '(liabilities:tax) *.33 ; income tax' --add-posting '(reserve:gifts) $100'+ $ hledger-rewrite.hs expenses:gifts --add-posting '(reserve:gifts) *-1"'+ $ hledger-rewrite.hs -f rewrites.hledger++ rewrites.hledger may consist of entries like:++ = ^income amt:<0 date:2017+ (liabilities:tax) *0.33 ; tax on income+ (reserve:grocery) *0.25 ; reserve 25% for grocery+ (reserve:) *0.25 ; reserve 25% for grocery++ Note the single quotes to protect the dollar sign from bash, and the two+ spaces between account and amount.++ More:++ $ hledger rewrite [QUERY] --add-posting "ACCT AMTEXPR" ...+ $ hledger rewrite ^income --add-posting '(liabilities:tax) *.33'+ $ hledger rewrite expenses:gifts --add-posting '(budget:gifts) *-1"'+ $ hledger rewrite ^income --add-posting '(budget:foreign currency) *0.25 JPY; diversify'++ Argument for --add-posting option is a usual posting of transaction with an+ exception for amount specification. More precisely, you can use '*' (star+ symbol) before the amount to indicate that that this is a factor for an+ amount of original matched posting. If the amount includes a commodity+ name, the new posting amount will be in the new commodity; otherwise, it+ will be in the matched posting amount's commodity.++ Re-write rules in a file+ During the run this tool will execute so called "Automated Transactions"+ found in any journal it process. I.e instead of specifying this operations+ in command line you can put them in a journal file.++ $ rewrite-rules.journal++ Make contents look like this:++ = ^income+ (liabilities:tax) *.33++ = expenses:gifts+ budget:gifts *-1+ assets:budget *1++ Note that '=' (equality symbol) that is used instead of date in transac-+ tions you usually write. It indicates the query by which you want to match+ the posting to add new ones.++ $ hledger rewrite -f input.journal -f rewrite-rules.journal > rewritten-tidy-output.journal++ This is something similar to the commands pipeline:++ $ hledger rewrite -f input.journal '^income' --add-posting '(liabilities:tax) *.33' \+ | hledger rewrite -f - expenses:gifts --add-posting 'budget:gifts *-1' \+ --add-posting 'assets:budget *1' \+ > rewritten-tidy-output.journal++ It is important to understand that relative order of such entries in jour-+ nal is important. You can re-use result of previously added postings.++ Diff output format+ To use this tool for batch modification of your journal files you may find+ useful output in form of unified diff.++ $ hledger rewrite --diff -f examples/sample.journal '^income' --add-posting '(liabilities:tax) *.33'++ Output might look like:++ --- /tmp/examples/sample.journal+ +++ /tmp/examples/sample.journal+ @@ -28,13 +28,15 @@+ ; declare commodities:+ ; commodity $++ -2008/01/01 income+ - assets:bank:checking $1+ +2008-01-01 income+ + assets:bank:checking $1+ income:salary+ + (liabilities:tax) $0++ -2008/06/01 gift+ - assets:bank:checking $1+ +2008-06-01 gift+ + assets:bank:checking $1+ income:gifts+ + (liabilities:tax) $0++ 2008/06/02 save+ assets:bank:saving $1++ If you'll pass this through patch tool you'll get transactions containing+ the posting that matches your query be updated. Note that multiple files+ might be update according to list of input files specified via --file op-+ tions and include directives inside of these files.++ Changed transactions are re-rendered in print's standard format, so the+ diff shows any reformatting as well as the postings you added: amounts are+ realigned, and dates are written with - separators. Transactions you+ didn't change are left exactly as they are. --layout selects the amount+ alignment, so choosing one which matches your journal will keep the diff+ small. Here is the example above again, with --layout=26 to match this+ journal's own alignment:++ @@ -28,13 +28,15 @@+ ; declare commodities:+ ; commodity $++ -2008/01/01 income+ +2008-01-01 income+ assets:bank:checking $1+ income:salary+ + (liabilities:tax) $0++ -2008/06/01 gift+ +2008-06-01 gift+ assets:bank:checking $1+ income:gifts+ + (liabilities:tax) $0++ 2008/06/02 save+ assets:bank:saving $1++ Only transactions which exist as journal entries in a file can be patched+ this way. Transactions read from other data formats, such as CSV or time-+ clock, and transactions generated by a periodic transaction rule, have no+ journal entry of their own; these are left out of the diff, and reported on+ stderr. To rewrite those, convert them to journal entries first, eg with+ hledger print or hledger import.++ Be careful. Whole transaction being re-formatted in a style of output from+ hledger print.++ See also:++ https://github.com/hledgerorg/hledger/issues/99++ rewrite vs. print --auto+ This command predates print --auto, and currently does much the same thing,+ but with these differences:++ * with multiple files, rewrite lets rules in any file affect all other+ files. print --auto uses standard directive scoping; rules affect only+ child files.++ * rewrite's query limits which transactions can be rewritten; all are+ printed. print --auto's query limits which transactions are printed.++ * rewrite applies rules specified on command line or in the journal. print+ --auto applies rules specified in the journal.++PART 3: DATA FORMATS+Journal+ hledger's usual data source is a plain text file containing journal entries+ in hledger journal format. If you're looking for a quick reference, jump+ ahead to the journal cheatsheet.++ This file represents an accounting General Journal. The .journal file ex-+ tension is most often used, though not strictly required. The journal file+ contains a number of transaction entries, each describing a transfer of+ money (or any commodity) between two or more named accounts, in a simple+ format readable by both hledger and humans.++ hledger's journal format is compatible with most of Ledger's journal for-+ mat, but not all of it. The differences and interoperation tips are de-+ scribed at hledger and Ledger. With some care, and by avoiding incompati-+ ble features, you can keep your hledger journal readable by Ledger and vice+ versa. This can useful eg for comparing the behaviour of one app against+ the other.++ You can use hledger without learning any more about this file; just use the+ add or web or import commands to create and update it.++ Many users, though, edit the journal file with a text editor, and track+ changes with a version control system such as git. Editor add-ons such as+ ledger-mode or hledger-mode for Emacs, vim-ledger for Vim, and hledger-vs-+ code for Visual Studio Code, make this easier, adding colour, formatting,+ tab completion, and useful commands. See Editors at hledger.org for the+ full list.++ A hledger journal file can contain three kinds of thing: comment lines,+ transactions, and/or directives (including periodic transaction rules and+ auto posting rules). Understanding the journal file format will also give+ you a good understanding of hledger's data model. Here's a quick cheat-+ sheet/overview, followed by detailed descriptions of each part.++ Journal cheatsheet+ # Here is the main syntax of hledger's journal format+ # (omitting extra Ledger compatibility syntax).++ ###############################################################################++ # 1. These are comment lines, for notes or temporarily disabling things.+ ; They begin with # or ;++ comment+ Or, lines can be enclosed within "comment" / "end comment".+ This is a block of+ commented lines.+ end comment++ # Some journal entries can have semicolon comments at end of line ; like this+ # Some of them require 2 or more spaces before the semicolon.++ ###############################################################################++ # 2. Directives customise processing or output in some way.+ # You don't need any directives to get started.+ # But they can add more error checking, or change how things are displayed.+ # They begin with a word, letter, or symbol.+ # They are most often placed at the top, before transactions.++ account assets ; Declare valid account names and display order.+ account assets:savings ; A subaccount. This one represents a bank account.+ account assets:checking ; Another. Note, 2+ spaces after the account name.+ account assets:receivable ; Accounting type is inferred from english names,+ account passifs ; or declared with a "type" tag, type:L+ account expenses ; type:X+ ; A follow-on comment line, indented.+ account expenses:rent ; Expense and revenue categories are also accounts.+ ; Subaccounts inherit their parent's type.++ commodity $0.00 ; Declare valid commodities and their display styles.+ commodity 1.000,00 EUR++ decimal-mark . ; The decimal mark used in this file (if ambiguous).++ payee Whole Foods ; Declare a valid payee name.++ tag trip ; Declare a valid tag name.++ P 2024-03-01 AAPL $179 ; Declare a market price for AAPL in $ on this date.++ include other.journal ; Include another journal file here.++ # Declare a recurring "periodic transaction", for budget/forecast reports+ ~ monthly set budget goals ; <- Note, 2+ spaces before the description.+ (expenses:rent) $1000+ (expenses:food) $500++ # Declare an auto posting rule, to modify existing transactions in reports+ = revenues:consulting+ liabilities:tax:2024:us *0.25 ; Add a tax liability & expense+ expenses:tax:2024:us *-0.25 ; for 25% of the revenue.++ ###############################################################################++ # 3. Transactions are what it's all about.+ # They are dated events, usually movements of money between 2 or more accounts.+ # They begin with a numeric date.+ # Here is their basic shape:+ #+ # DATE DESCRIPTION ; The transaction's date and optional description.+ # ACCOUNT1 AMOUNT ; A posting of an amount to/from this account, indented.+ # ACCOUNT2 AMOUNT ; A second posting, balancing the first.+ # ... ; More if needed. Amounts must sum to zero.+ # ; Note, 2+ spaces between account names and amounts.++ 2024-01-01 opening balances ; At the start, declare pre-existing balances this way.+ assets:savings $10000 ; Account names can be anything. lower case is easy to type.+ assets:checking $1000 ; assets, liabilities, equity, revenues, expenses are common.+ liabilities:credit card $-500 ; liabilities, equity, revenues balances are usually negative.+ equity:start ; One amount can be left blank. $-10500 is inferred here.+ ; Some of these accounts we didn't declare above,+ ; so -s/--strict would complain.++ 2024-01-03 ! (12345) pay rent+ ; Additional transaction comment lines, indented.+ ; There can be a ! or * after the date meaning "pending" or "cleared".+ ; There can be a parenthesised (code) after the date/status.+ ; Amounts' sign shows direction of flow.+ assets:checking $-500 ; Minus means removed from this account (credit).+ expenses:rent $500 ; Plus means added to this account (debit).++ ; Keeping transactions in date order is optional (but helps error checking).++ 2024-01-02 Gringott's Bank | withdrawal ; Description can be PAYEE | NOTE+ assets:bank:gold -10 gold+ assets:pouch 10 gold++ 2024-01-02 shopping+ expenses:clothing 1 gold+ expenses:wands 5 gold+ assets:pouch -6 gold++ 2024-01-02 receive gift+ revenues:gifts -3 "Chocolate Frogs" ; Complex commodity symbols+ assets:pouch 3 "Chocolate Frogs" ; must be in double quotes.++ 2024-01-15 buy some shares, in two lots ; Cost can be noted.+ assets:investments:2024-01-15 2.0 AAAA @ $1.50 ; @ means per-unit cost+ assets:investments:2024-01-15-02 3.0 AAAA @@ $4 ; @@ means total cost+ ; ^ Per-lot subaccounts are sometimes useful.+ assets:checking $-7++ 2024-01-15 assert some account balances on this date+ ; Balances can be asserted in any transaction, with =, for extra error checking.+ ; Assertion txns like this one can be made with hledger close --assert --show-costs+ ;+ assets:savings $0 = $10000+ assets:checking $0 = $493+ assets:bank:gold 0 gold = -10 gold+ assets:pouch 0 gold = 4 gold+ assets:pouch 0 "Chocolate Frogs" = 3 "Chocolate Frogs"+ assets:investments:2024-01-15 0.0 AAAA = 2.0 AAAA @ $1.50+ assets:investments:2024-01-15-02 0.0 AAAA = 3.0 AAAA @@ $4+ liabilities:credit card $0 = $-500++ 2024-02-01 note some event, or a transaction not yet fully entered, on this date+ ; Postings are not required.++ # Consistent YYYY-MM-DD date format is recommended,+ # but you can use . or / and omit leading zeros if you prefer.+ 2024.01.01+ 2024/1/1++ Comments+ Lines in the journal will be ignored if they begin with a hash (#) or a+ semicolon (;). (See also Other syntax.) hledger will also ignore regions+ beginning with a comment line, and ending with an end comment line or file+ end. Here's a suggestion for choosing between them:++ * # for top-level notes++ * ; for commenting out things temporarily++ * comment for quickly commenting large regions (remember it's there, or you+ might get confused)++ Eg:++ # a comment line+ ; another commentline+ comment+ A multi-line comment block,+ continuing until "end comment" directive+ or the end of the current file.+ end comment++ Some hledger entries can have same-line comments attached to them, from ;+ (semicolon) to end of line. See Transaction comments, Posting comments,+ and Account comments below.++ Comment lines immediately preceding a transaction (with no blank line in+ between) are attached to that transaction, and are shown before it, as+ written, in print output.++ Transactions+ Transactions are the main unit of information in a journal file. They rep-+ resent events, typically a movement of some quantity of commodities between+ two or more named accounts.++ Each transaction is recorded as a journal entry, beginning with a simple+ date in column 0. This can be followed by any of the following optional+ fields, separated by spaces:++ * a status character (empty, !, or *)++ * a code (any short number or text, enclosed in parentheses)++ * a description (any remaining text until end of line or a semicolon)++ * a comment (any remaining text following a semicolon until end of line,+ and any following indented lines beginning with a semicolon)++ * 0 or more indented posting lines, describing what was transferred and the+ accounts involved (indented comment lines are also allowed, but not blank+ lines or non-indented lines).++ Here's a simple journal file containing one transaction:++ 2008/01/01 income+ assets:bank:checking $1+ income:salary $-1++ Dates+ Simple dates+ Dates in the journal file use simple dates format: YYYY-MM-DD or YYYY/MM/DD+ or YYYY.MM.DD, with leading zeros optional. The year may be omitted, in+ which case it will be inferred from the context: the current transaction,+ the default year set with a Y directive, or the current date when the com-+ mand is run. Some examples: 2010-01-31, 2010/01/31, 2010.1.31, 1/31.++ (On the command line and in the UIs, you can also use the more flexible+ smart dates.)++ Posting dates+ You can give individual postings a different date from their parent trans-+ action, by adding a posting comment containing a tag (see below) like ;+ date:DATE. (There's also a Ledger-compatible syntax, ; [DATE], which can+ be convenient.)++ This is probably the best way to control posting dates precisely. Eg in+ this example the expense should appear in May reports, and the deduction+ from checking should be reported on 6/1 for easy bank reconciliation:++ 2015/5/30+ expenses:food $10 ; food purchased on saturday 5/30+ assets:checking ; bank cleared it on monday, date:6/1++ $ hledger -f t.j register food+ 2015-05-30 expenses:food $10 $10++ $ hledger -f t.j register checking+ 2015-06-01 assets:checking $-10 $-10++ DATE should be a simple date; if the year is not specified it will use the+ year of the transaction's date.+ A non-empty date: tag value must begin with a valid simple date. A date:+ tag with an empty value is allowed, and sets no date. (To disable a date+ tag temporarily, without removing the date, insert a comma before the+ date.)++ Status+ Transactions (or individual postings within a transaction) can have a sta-+ tus mark, which is a single character before the transaction description+ (or posting account name), separated from it by a space, indicating one of+ three statuses:++ mark status+ ------------------+ unmarked+ ! pending+ * cleared++ When reporting, you can filter by status with the -U/--unmarked, -P/--pend-+ ing, and -C/--cleared flags (and you can combine these, eg -UP to match all+ except cleared things). Or you can use the status:, status:!, and status:*+ queries, or the U, P, C keys in hledger-ui.++ (Note: in Ledger the "unmarked" state is called "uncleared"; in hledger we+ renamed it to "unmarked" for semantic clarity.)++ Status marks are optional, but can be helpful eg for reconciling with+ real-world accounts. Some editor modes provide highlighting and shortcuts+ for working with status. Eg in Emacs ledger-mode, you can toggle transac-+ tion status with C-c C-e, or posting status with C-c C-c.++ What "uncleared", "pending", and "cleared" actually mean is up to you.+ Here's one suggestion:++ status meaning+ --------------------------------------------------------------------------+ uncleared recorded but not yet reconciled; needs review+ pending tentatively reconciled (if needed, eg during a big reconcil-+ iation)+ cleared complete, reconciled as far as possible, and considered cor-+ rect++ With this scheme, you would use -PC to see the current balance at your+ bank, -U to see things which will probably hit your bank soon (like un-+ cashed checks), and no flags to see the most up-to-date state of your fi-+ nances.++ Code+ After the status mark, but before the description, you can optionally write+ a transaction "code", such as a check number or transaction id, enclosed in+ parentheses.++ This has a few limitations: The code must not contain a closing parenthesis+ (or it will be truncated). Codes tend to disrupt alignment of the register+ report, making it harder to scan visually. And you can't store more than+ one value there per transaction. For these reasons you might want to avoid+ the code field and use tags instead.++ Description+ After the date, status mark and/or code fields, the rest of the line (or+ until a comment is begun with ;) is the transaction's description. Here+ you can describe the transaction (called the "narration" in traditional+ bookkeeping), or you can record a payee/payer name, or you can leave it+ empty.++ Transaction descriptions show up in print output and in register reports,+ and can be listed with the descriptions command.++ You can query by description with desc:DESCREGEX, or pivot on description+ with --pivot desc.++ Payee and note+ Sometimes people want a dedicated payee/payer field that can be queried and+ checked more strictly. If you want that, you can write a | (pipe) charac-+ ter in the description. This divides it into a "payee" field on the left,+ and a "note" field on the right. (Either can be empty.)++ You can query these with payee:PAYEEREGEX and note:NOTEREGEX, list their+ values with the payees and notes commands, or pivot on payee or note.++ Note: in transactions with no | character, description, payee, and note all+ have the same value. Once a | is added, they become distinct.++ If you want more strict error checking, you can declare the valid payee+ names with payee directives, and then enforce these with hledger check pay-+ ees. (Note: because of the above, for this you'll need to ensure every+ transaction description contains a | and therefore a checkable payee name,+ even if it's empty.)++ Transaction comments+ Text following ;, after a transaction description, and/or on indented lines+ immediately below it, form comments for that transaction. They are repro-+ duced by print but otherwise ignored, except they may contain tags, which+ are not ignored.++ 2012-01-01 something ; a transaction comment+ ; a second line of transaction comment+ expenses 1+ assets++ Postings+ A posting is an addition of some amount to, or removal of some amount from,+ an account. Each posting line begins with at least one space or tab (2 or+ 4 spaces is common), followed by:++ * (optional) a status character (empty, !, or *), followed by a space++ * (required) an account name (any text, optionally including single spaces.+ If anything follows the account name on the same line, the account name+ must be ended by two or more spaces.)++ * (optional) an amount++ * (optional) a same-line posting comment, beginning with a semicolon (;).++ If the amount is positive, it is being added to the account; if negative,+ it is being removed from the account.++ The posting amounts in a transaction must sum up to zero, indicating that+ the inflows and outflows are equal. We call this a balanced transaction.+ (You can read more about the details of transaction balancing below.)++ If no amount is written, it will be calculated automatically from the other+ postings in the transaction, so as to balance the transaction. In other+ words, in any transaction you can leave one posting amountless to save typ-+ ing.++ Debits and credits+ The traditional accounting concepts of debit and credit of course exist in+ hledger, but we represent them with numeric sign. Positive and negative+ posting amounts represent debits and credits respectively.++ You don't need to remember that, but if you would like to - eg for helping+ newcomers or for talking with your accountant - here's a handy mnemonic:++ debit / plus / left / short words+ credit / minus / right / longer words++ Account names+ Accounts are the main way of categorising things in hledger. As in Double+ Entry Bookkeeping, they can represent real world accounts (such as a bank+ account), or more abstract categories such as "money spent on food" or+ "money borrowed from Frank".++ Account names are flexible. They may be capitalised or not; they may con-+ tain letters, numbers, punctuation, symbols, or single spaces; they may be+ in any language. Their parts, separated by :, can't be empty; so an ac-+ count name can't begin or end with :, or contain ::.++ Typically we use the five traditional accounting categories as the starting+ point for account names. In english they are:++ assets, liabilities, equity, revenues, expenses++ These will be discussed more in Account types below. In hledger docs you+ may see them referred to as A, L, E, R, X for short.++ Two space delimiter+ Note that hledger's account names, like Ledger's, may contain single+ spaces. Because of this, they must be separated from anything following+ them on the same line by two or more spaces. (Two or more tabs also work;+ but spaces are preferred. A single tab is not a separator, unlike in+ Ledger.)++ This lets us use expressive account names, while still keeping the syntax+ light. Here are some examples:++ assets:accounts receivable ; bad, only one space before the comment+ assets:accounts receivable ; good++ assets:accounts receivable $10 ; bad, one space before the amount+ assets:accounts receivable $10 ; good++ assets:accounts receivable = $1000 ; bad, one space before the balance assignment+ assets:accounts receivable = $1000 ; good++ The two-space delimiter is also required in periodic transaction rules, be-+ tween period expression and description:++ ~ every 5th day YouTube Premium ; bad, one space before the description+ ~ every 5th day YouTube Premium ; good++ When you are starting out, you can expect this delimiter will trip you up+ once or twice. (If it happens too much, you can check account names+ strictly to prevent it.)++ Account hierarchy+ For more precise reporting, we usually divide accounts into more detailed+ subaccounts, subsubaccounts, and so on, by writing a full colon between ac-+ count name parts. For example, instead of writing assets and expenses, we+ might write assets:bank:checking and expenses:food. From these names+ hledger will infer this hierarchy of five accounts:++ assets+ assets:bank+ assets:bank:checking+ expenses+ expenses:food++ Or as an outline:++ assets+ bank+ checking+ expenses+ food++ hledger reports can summarise the account tree to any depth, so you can+ make your subcategories as detailed as you like. But don't go overboard,+ especially when getting started; simpler categories can be less work.++ Other account name features+ Enclosing the account name in parentheses or brackets, like (ex-+ penses:food), enables a non-standard bookkeeping feature: virtual postings.++ Account names can be rewritten and restructured, temporarily or perma-+ nently, by account aliases.++ Amounts+ After the account name, there is usually an amount. (Remember: between ac-+ count name and amount, there must be two or more spaces.)++ hledger's amount format is flexible, supporting several international for-+ mats. Here are some examples. Amounts have a number (the "quantity"):++ 1++ ..and usually a currency symbol or commodity name (more on this below), to+ the left or right of the quantity, with or without a separating space:++ $1+ 4000 AAPL+ 3 "green apples"++ Amounts can be preceded by a minus sign (or a plus sign, though plus is the+ default), The sign can be written before or after a left-side commodity+ symbol:++ -$1+ $-1++ One or more spaces between the sign and the number are acceptable when+ parsing (but they won't be displayed in output):++ + $1+ $- 1++ Scientific E notation is allowed:++ 1E-6+ EUR 1E3++ Decimal marks+ A decimal mark can be written as a period or a comma:++ 1.23+ 1,23++ Both of these are common in international number formats, so hledger is not+ biased towards one or the other. Because hledger also supports digit group+ marks (eg thousands separators), this means that a number like 1,000 or+ 1.000 containing just one period or comma is ambiguous. In such cases,+ hledger by default assumes it is a decimal mark, and will parse both of+ those as 1.++ To help hledger parse such ambiguous numbers accurately, if you use digit+ group marks, we recommend declaring the decimal mark explicitly. You can+ declare it per commodity with commodity directives, or per file with a dec-+ imal-mark directive at the top of each journal file (described below).++ hledger also accepts numbers like 10. with no digits after the decimal mark+ (and will sometimes display numbers that way to disambiguate them - see+ Trailing decimal marks).++ Digit group marks+ In the integer part of the amount quantity (left of the decimal mark),+ groups of digits can optionally be separated by a digit group mark - a+ comma or period (whichever is not used as decimal mark), an underscore, an+ apostrophe, or a space (several Unicode space variants, like no-break+ space, are also accepted). So these are all valid amounts in a journal+ file:++ $1,000,000.00+ EUR 2.000.000,00+ INR 9,99,99,999.00+ CHF 1'000'000.00+ 1_000_000.00+ 1 000 000.00 ; <- ordinary space+ 1 000 000.00 ; <- no-break space++ Commodity+ Amounts in hledger have both a "quantity", which is a signed decimal num-+ ber, and a "commodity", which is a currency symbol, stock ticker, or any+ word or phrase describing something you are tracking.++ If the commodity name contains non-letters (spaces, numbers, or punctua-+ tion), you must always write it inside double quotes ("green apples",+ "ABC123"). In particular, in a posting amount, a symbol that begins with (+ before the number, or with / after it, or that contains ) inside parenthe-+ ses, must be quoted, eg "(X)" 10 or 10 "/x", or it would be read as part of+ an amount expression.++ If you write just a bare number, that too will have a commodity, with name+ ""; we call that the "no-symbol commodity".++ Actually, hledger combines these single-commodity amounts into more power-+ ful multi-commodity amounts, which are what it works with most of the time.+ A multi-commodity amount could be, eg: 1 USD, 2 EUR, 3.456 TSLA. In prac-+ tice, you will only see multi-commodity amounts in hledger's output; you+ can't write them directly in the journal file.++ By default, the format of amounts in the journal influences how hledger+ displays them in output. This is explained in Commodity display style be-+ low.++ A posting amount can also be an arithmetic expression, like $47.97 ++ $15.75; see Amount expressions.++ Costs+ When one commodity is exchanged for another - a currency conversion, or a+ purchase or sale of stock - you can record the transacted price or conver-+ sion rate by writing @ UNITCOST or @@ TOTALCOST after a posting amount.+ (hledger docs generically call this a "cost", whether buying or selling,+ though "cost" is an overloaded word. "Transacted cost" or "transacted+ price" is more precise.) Eg:++ 2026-01-01 buy euros+ assets:dollars $-123+ assets:euros a100 @ $1.23 ; unit cost (exchange rate)++ or:++ 2026-01-01 buy euros+ assets:dollars $-123+ assets:euros a100 @@ $123 ; total cost++ The cost should normally be a positive amount. Negative costs are sup-+ ported, but can be confusing, as discussed at --infer-market-prices: market+ prices from transactions.++ Costs participate in transaction balancing: amounts are converted to their+ cost before checking if the transaction is balanced. So you could also+ write the above less redundantly, like so:++ 2026-01-01 buy euros+ assets:dollars ; $-123 is inferred+ assets:euros a100 @ $1.23++ or:++ 2026-01-01 buy euros+ assets:dollars ; $-123 is inferred+ assets:euros a100 @@ $123++ or even:++ 2026-01-01 buy euros+ assets:euros a100 ; @@ $123 is inferred+ assets:dollars $-123++ This last form works for transactions involving exactly two commodities,+ with neither cost notation nor equity postings. If one of the postings is+ recognised as a lot posting, the cost will be attached to that one. Other-+ wise the cost will be attached to the first (top) posting - so it can be+ important to put the right one first. Here we had to switch the order of+ postings, to get the same meaning as above.++ This form is the easiest to make undetected errors with; so it is rejected+ by hledger check balanced, and by strict mode.++ Reports can show amounts converted to their cost when you add the -B/--cost+ flag.++ Costs can also be recorded in a more traditional double entry way, with eq-+ uity postings; or with both notations at once. See Cost reporting for a+ comparison of these styles, and how hledger can convert between them.++ Cost basis+ This section briefly describes the {} cost basis syntax, used to record the+ nominal cost of an investment being acquired, or to select lots being+ transferred or disposed. This is described in more detail later in Lots+ and capital gains. If you're not tracking investment lots and capital+ gains, you can skip this.++ hledger's cost basis annotations look like Beancount's: comma-separated+ parts enclosed in curly braces, after an amount. All parts are optional,+ but when present they must be in this order:++ 1. a date, in YYYY-MM-DD format++ 2. a text label, enclosed in double quotes++ 3. a cost, as a single-commodity hledger amount.++ Here are some valid hledger cost basis annotations:++ {2026-01-15, "12:05", $50}+ {2026-01-15, $50}+ {1.000.000,33 EUR}+ {$50}+ {}++ This means: selling 10 AAPL, originally purchased at $50 each, for $60+ each:++ -10 AAPL {$50} @ $60++ Note the preferred order is to write {} before @, as shown.++ hledger can also read Ledger's cost basis syntax. Here, the parts are+ written separately, in any order, with different enclosing characters:++ 10 AAPL {$50} [2026-01-15] (12:05)++ If a Ledger-style label annotation contains double quotes, they will be+ stripped (("foo") is read as label foo).++ Balance assertions+ hledger supports Ledger-style balance assertions in journal files. These+ look like, for example, = EXPECTEDBALANCE following a posting's amount. Eg+ here we assert the expected dollar balance in accounts a and b after each+ posting:++ 2013/1/1+ a $1 = $1+ b = $-1++ 2013/1/2+ a $1 = $2+ b $-1 = $-2++ After reading a journal file, hledger will check all balance assertions and+ report an error if any of them fail. Balance assertions can protect you+ from, eg, inadvertently disrupting reconciled balances while cleaning up+ old entries. You can disable them temporarily with the -I or --ignore-as-+ sertions flag, which can be useful for troubleshooting or for reading+ Ledger files. (Note: this flag currently does not disable balance assign-+ ments, described below).++ To check rules which should hold at all times, such as "no asset account is+ ever negative", see assert directives.++ Assertions and ordering+ hledger calculates and checks an account's balance assertions in date order+ (and when there are multiple assertions on the same day, in parse order).+ Note this is different from Ledger, which checks assertions always in parse+ order, ignoring dates.++ This means in hledger you can freely reorder transactions, postings, or+ files, and balance assertions will usually keep working. The exception is+ when you reorder multiple postings on the same day, to the same account,+ which have balance assertions; those will likely need updating.++ Assertions and multiple files+ If an account has transactions appearing in multiple files, balance asser-+ tions can still work - but only if those files are part of a hierarchy made+ by include directives.++ If the same files are specified with two -f options on the command line,+ the assertions in the second will not see the balances from the first.++ To work around this, arrange your files in a hierarchy with include. Or,+ you could concatenate the files temporarily, and process them like one big+ file.++ This is for stable, predictable reports: the file hierarchy is part of your+ data, while the order of command line arguments is not, and reordering your+ arguments should not change whether your assertions pass.++ Assertions and costs+ Balance assertions ignore costs, and should normally be written without+ one:++ 2019/1/1+ (a) $1 @ a1 = $1++ We do allow costs to be written in balance assertion amounts, however, and+ print shows them, but they don't affect whether the assertion passes or+ fails. This is for backward compatibility (hledger's close command used to+ generate balance assertions with costs), and because balance assignments do+ use costs (see below).++ Assertions and commodities+ The balance assertions described so far are "single commodity balance as-+ sertions": they assert and check the balance in one commodity, ignoring any+ others that may be present. This is how balance assertions work in Ledger+ also.++ If an account contains multiple commodities, you can assert their balances+ by writing multiple postings with balance assertions, one for each commod-+ ity:++ 2013/1/1+ usd $-1+ eur a-1+ both++ 2013/1/2+ both 0 = $1+ both 0 = a1++ In hledger you can make a stronger "sole commodity balance assertion" by+ writing two equals signs (== EXPECTEDBALANCE). This also asserts that+ there are no other commodities in the account besides the asserted one (or+ at least, that their current balance is zero):++ 2013/1/1+ usd $-1 == $-1 ; these sole commodity assertions succeed+ eur a-1 == a-1+ both ;== $1 ; this one would fail because 'both' contains $ and a++ It's less easy to make a "sole commodities balance assertion" (note the+ plural) - ie, asserting that an account contains two or more specified com-+ modities and no others. It can be done by++ 1. isolating each commodity in a subaccount, and asserting those++ 2. and also asserting there are no commodities in the parent account it-+ self:++ 2013/1/1+ usd $-1+ eur a-1+ both 0 == 0 ; nothing up my sleeve+ both:usd $1 == $1 ; a dollar here+ both:eur a1 == a1 ; a euro there++ Assertions and subaccounts+ All of the balance assertions above (both = and ==) are "subaccount-exclu-+ sive balance assertions"; they ignore any balances that exist in deeper+ subaccounts.++ In hledger you can make "subaccount-inclusive balance assertions" by adding+ a star after the equals (=* or ==*):++ 2019/1/1+ equity:start+ assets:checking $10+ assets:savings $10+ assets $0 ==* $20 ; assets + subaccounts contains $20 and nothing else++ Assertions and lot subaccounts+ Lot subaccounts (a special kind of subaccount for tracking lots, discussed+ in "Lots and capital gains" below) have only limited support for balance+ assertions: the assertions will be checked correctly only if all postings+ to that lot mention the subaccount name explicitly.++ Since it's common practice to leave lot subaccounts implicit, generally you+ should avoid writing balance assertions on individual lots. (close --lots+ also follows this rule.) If you forget, the balance assertion failure mes-+ sage will remind you. If you really need a balance assertion, you can usu-+ ally write it on the parent account instead.++ (The restriction is because transaction balancing amounts, balance assign-+ ments, and balance assertions must be calculated and checked before lot+ movements are known.) See also Lot postings and balance assertions.++ Assertions and status+ Balance assertions always consider postings of all statuses (unmarked,+ pending, or cleared); they are not affected by the -U/--unmarked /+ -P/--pending / -C/--cleared flags or the status: query.++ Assertions and virtual postings+ Balance assertions always consider both real and virtual postings; they are+ not affected by the --real/-R flag or real: query.++ Assertions and auto postings+ Balance assertions are affected by the --auto flag, which generates auto+ postings, which can alter account balances. Because auto postings are op-+ tional in hledger, accounts affected by them effectively have two balances.+ But balance assertions can only test one or the other of these. So to+ avoid making fragile assertions, either:++ * assert the balance calculated with --auto, and always use --auto with+ that file++ * or assert the balance calculated without --auto, and never use --auto+ with that file++ * or avoid balance assertions on accounts affected by auto postings (or+ avoid auto postings entirely).++ Assertions and precision+ Balance assertions compare the exactly calculated amounts, which are not+ always what is shown by reports. Eg a commodity directive may limit the+ display precision, but this will not affect balance assertions. Balance+ assertion failure messages show exact amounts.++ Assertions and hledger add+ The add command also accepts balance assertions (and assignments), and+ re-checks all of the journal's assertions as you enter amounts; see add and+ balance assertions.++ Posting comments+ Text following ;, at the end of a posting line, and/or on indented lines+ immediately below it, form comments for that posting. They are reproduced+ by print but otherwise ignored, except they may contain tags, which are not+ ignored.++ 2012-01-01+ expenses 1 ; a comment for posting 1+ assets+ ; a comment for posting 2+ ; a second comment line for posting 2++ Tags+ Tags are a way to add extra labels or data fields to transactions, post-+ ings, or accounts, which you can match with a tag: query in reports. (See+ queries below.)++ Tags are a single word or hyphenated word, immediately followed by a full+ colon, written within a comment. (Yes, storing data in comments is+ slightly weird.) Here's a transaction with a tag:++ 2025-01-01 groceries ; some-tag:+ assets:checking+ expenses:food $1++ A tag can have a value: a single line of text written after the colon (tag+ values can't contain newlines):++ 2025-01-01 groceries ; tag1: this is tag1's value++ Multiple tags can be separated by comma (so tag values can't contain com-+ mas):++ 2025-01-01 groceries ; tag1:value 1, tag2:value 2, comment text++ A tag can have multiple values:++ 2025-01-01 groceries ; tag1:value 1, tag1:value 2++ You can write each tag on its own line if you prefer (but they still can't+ contain commas):++ 2025-01-01 groceries+ ; tag1: value 1+ ; tag2: value 2++ Tags can be attached to individual postings, rather than the overall trans-+ action:++ 2025-01-01 rent+ assets:checking+ expenses:rent $1000 ; postingtag:++ Tags can be attached to accounts, in their account directive:++ account assets:checking ; acct-number: 123-45-6789++ Tag propagation+ In addition to what they are attached to, tags also affect related data in+ a few ways, allowing more powerful queries:++ 1. Accounts -> postings. Postings inherit tags from their account.++ 2. Transactions -> postings. Postings inherit tags from their transaction.++ 3. Postings -> transactions. Transactions also acquire the tags of their+ postings.++ So when you use a tag: query to match whole transactions, individual post-+ ings, or accounts, it's good to understand how tags behave. Here's an ex-+ ample showing all three kinds of propagation:++ account assets:checking+ account expenses:food ; atag:++ 2025-01-01 groceries ; ttag:+ assets:checking ; p1tag:+ expenses:food $1 ; p2tag:++ data part has tags explanation+ -----------------------------------------------------------------------------+ assets:check- no tags attached+ ing account+ expenses:food atag atag: in comment+ account+ assets:check- p1tag, ttag p1tag: in comment, ttag acquired from+ ing posting transaction+ expenses:food p2tag, atag, p2tag: in comment, atag from account, ttag+ posting ttag from transaction+ groceries ttag, p1tag, ttag: in comment, p1tag from first posting,+ transaction p2tag, atag p2tag and atag from second posting++ Displaying tags+ You can use the tags command to list tag names or values.++ The print command also shows tags.++ You can use --pivot to display tag values in other reports, in various ways+ (eg appended to account names, like pseudo subaccounts).++ When to use tags ?+ Tags provide more dimensions of categorisation, complementing accounts and+ transaction descriptions. When to use each of these is somewhat a matter+ of taste. Accounts have the most built-in support, and regex queries on+ descriptions are also quite powerful. So you may not need tags at all.+ But if you want to track multiple cross-cutting categories, they can be a+ good fit. For example, you could tag trip-related transactions with trip:+ YEAR:PLACE, without disturbing your usual account categories.++ Tag names+ What is allowed in a tag name ? Any sequence of non-whitespace non-newline+ characters. Eg : is a valid tag.++ For extra error checking, you can declare valid tag names with the tag di-+ rective, and then enforce these with the check command. But note that tags+ are detected quite loosely at present, sometimes where you didn't intend+ them. Eg a comment like ; see https://foo.com adds a https tag.++ There are several tag names which have special significance to hledger.+ They are explained elsewhere, but here's a quick reference:++ type -- declares an account's type+ alias -- declares an account's or commodity's alias+ lots -- declares an account's or commodity's lot tracking (cost basis method)+ date -- overrides a posting's date+ date2 -- overrides a posting's secondary date+ assert -- appears on txns generated by close --assert+ retain -- appears on txns generated by close --retain+ start -- appears on txns generated by close --migrate/--close/--open/--assign+ t -- appears on postings generated from timedot letters++ generated-transaction -- appears on txns generated by a periodic rule+ modified-transaction -- appears on txns which have had auto postings added+ generated-posting -- appears on generated postings+ cost-posting -- appears on postings which have (or could have) a cost,+ and which have equivalent conversion postings in the transaction+ conversion-posting -- appears on postings which are to a V/Conversion account+ and which have an equivalent cost posting in the transaction+ ptype -- appears on lot postings, with their type (acquire, dispose, etc.)+ feesplit-posting -- appears on fee parts split off a lot transfer posting+ lotsplit-posting -- appears on the parts of a posting split across several lots (with --lots)+ lot-parent-assertion -- appears on postings carrying a balance assertion moved+ from a posting that was split across several lots++ The second group above (generated-transaction, etc.) are normally hidden,+ with a _ prefix added. This means print doesn't show them by default; but+ you can still use them in queries. You can add the --verbose-tags flag to+ make them visible in print output, which can be useful for troubleshooting.++ Tag values+ What is allowed in a tag value ? Any sequence of non-comma non-newline+ characters, with surrounding whitespace removed.++ Note a tag can have multiple values, if the tag is repeated. Eg ; foo:a,+ foo:b.++ Directives+ You can add directives to a journal file, to add error checking, improve+ parsing, et cetera. Directives begin with a keyword, not a date. Some of+ them can have indented subdirectives. hledger's directives are broadly+ similar to Ledger's, though with differences.++ Directive scopes+ Directives differ in which entries they affect. Some affect only the fol-+ lowing entries, others affect both preceding and following entries; and+ some reach only the current file and its subfiles, others reach every file.+ Assuming this command and file layout:++ hledger -f main.journal -f other.journal++ main.journal ; the parent file+ include a.journal ; a child of main.journal+ include aa.journal ; a child of a.journal+ include b.journal ; a child of main.journal, and a sibling of a.journal++ other.journal ; a separate file tree++ here are the possible scopes, for a directive written in a.journal:++ scope affects+ --------------------------------------------------------------------------+ rest of file + following entries in or below a.journal (including+ subfiles aa.journal if it is included after the directive)+ rest of file as above, plus following entries in parent files+ tree (main.journal entries after the include a.journal di-+ rective, including b.journal)+ file tree all entries in main.journal, a.journal, aa.journal and+ b.journal, before and after the directive+ all files all entries in all file trees, no matter where the di-+ rective is written++ The limited scopes help keep reports stable and deterministic, independent+ of the order of -f options or include directives. This is sometimes incon-+ venient, but there are usually workarounds. In particular, to have account+ aliases affect all entries in a file tree, declare them at the start of the+ main file, before any includes. (Or to affect all file trees specified at+ runtime, use --alias options.)++ Combining file trees+ When you read several file trees (with several -f options), hledger reads+ and processes each one separately, then combines them. So one file tree+ can't change how another's entries are read: account and commodity aliases,+ decimal marks, transaction balancing, balance assertions and assert direc-+ tives, auto postings, forecast transactions and lot tracking all work+ within each file tree.++ But a few declarations reach all file trees ("all files" in the table be-+ low):++ * Account declarations, including account types and display order.++ * Commodity declarations, including display styles. If file trees declare+ a commodity's display style differently, the last one is used.++ * Payee and tag declarations.++ * P market prices, used for valuation.++ * Commodity aliases, but only for valuation, and only as a last resort:+ when market prices can't convert an amount, eg if it's in an alias de-+ clared by another file tree. If file trees declare an alias differently+ (for a different commodity, or with a different quantity), converting to+ or from it this way is an error.++ So you can combine file trees that weren't designed to work together. The+ interactions to watch for are conflicting display styles, account types,+ and market prices.++ Directives summary+ direc- what it does scope+ tive+ -----------------------------------------------------------------------------+ Affects file reading:+ include Includes entries from another file (a "subfile"), as+ if they were written inline.+ comment Ignores following entries and directives, until end rest of+ comment. file ++ subfiles+ alias Rewrites following matched account names, until end rest of+ aliases. file ++ subfiles+ account Rewrites following matched account names to this ac- rest of+ alias: count's full name, until end aliases. file ++ tag subfiles+ deci- Declares the decimal mark for parsing following rest of+ mal-mark amounts of all commodities, until the next deci- file ++ mal-mark (subfiles can override). subfiles+ commod- Declares the decimal mark for parsing following rest of+ ity sam- amounts of this commodity (decimal-mark can over- file tree+ ple ride).+ amount+ Declares data:+ account Declares an account, and its display order. all files+ account Declares the account's type. all files+ type:+ tag+ account Declares the account's cost basis method. file tree+ lots:+ tag+ commod- Declares a commodity symbol. all files+ ity+ commod- Declares the commodity's display style. all files+ ity sam-+ ple+ amount+ commod- Declares equivalent or related symbols for this com- file tree+ ity modity.+ alias:+ tag+ commod- Declares that the commodity tracks lots, and option- file tree+ ity ally their cost basis method.+ lots:+ tag+ payee Declares a payee name. all files+ tag Declares a tag name. all files+ P Declares a commodity's market price on some date, all files+ for value and gain reports.+ Generates data:+ = Generates extra postings (after matched postings), file tree+ with --auto. (Does not see sibling files: #1212.)+ ~ Generates future transactions (after latest transac- file tree+ tion in file tree, by default), with --forecast.+ ~ Generates budget goals and actual/goal percentages, all files+ with balance --budget.+ Checks data:+ assert Declares a standing rule, a query that must match no file tree+ rows or some rows, checked like balance assertions.+ File reading (legacy/deprecated):+ apply Prepends a common parent account to all following rest of+ account account names, until end apply account. file ++ subfiles+ apply Sets a default year for following yearless dates, rest of+ year until end apply year. file ++ subfiles+ D Sets a default commodity for following no-symbol rest of+ amounts. Also sets its parsing decimal mark (over- file ++ ridden by commodity or decimal-mark) and display subfiles+ style (overridden by commodity).+ Y Sets a default year for following yearless dates. rest of+ file ++ subfiles+ other These other Ledger directives are accepted but ig-+ nored.++ account directive+ account directives can be used to declare accounts (ie, the places that+ amounts are transferred from and to). Though not required, these declara-+ tions can provide several benefits:++ * They can document your intended chart of accounts, providing a reference.++ * They can store additional account information as comments, or as tags+ which can be used to filter or pivot reports.++ * They can restrict which accounts may be posted to by transactions, eg in+ strict mode, which helps prevent errors.++ * They influence account display order in reports, allowing non-alphabetic+ sorting (eg Revenues to appear above Expenses).++ * They can help hledger know your accounts' types (asset, liability, eq-+ uity, revenue, expense), enabling reports like balancesheet and incomes-+ tatement.++ * They help with account name completion (in hledger add, hledger-web,+ hledger-iadd, ledger-mode, etc.)++ They are written as the word account followed by a hledger-style account+ name. Eg:++ account assets:bank:checking++ Any indented subdirectives are ignored, except Ledger's alias subdirective+ (see Account aliases).++ Account comments+ Text following two or more spaces and ; at the end of an account directive+ line, and/or following ; on indented lines immediately below it, form com-+ ments for that account.++ Same-line account comments require two+ spaces before ; because that char-+ acter can appear in account names.++ account assets:bank:checking ; same-line comment, at least 2 spaces before the semicolon+ ; next-line comment+ ; some tags - type:A, acctnum:12345++ Account tags+ An account directive's comment may contain tags. These will be inherited+ by all postings using that account, except where the posting already has a+ value for that tag. (A posting tag overrides an account tag.) Note, these+ tags will be queryable but won't be shown in print output, even with --ver-+ bose-tags.++ Account aliases+ An alias: tag on an account directive declares an alternate, usually+ shorter, name for that account. This could make data entry quicker, and+ your journal less verbose (but also adds more names for you to remember).+ Eg:++ account assets:bank:checking ; alias: checking++ 2024-01-01+ expenses:food 5+ checking++ When hledger reads this, it rewrites checking to assets:bank:checking. Re-+ ports, queries and print output show only the full name. Subaccounts are+ rewritten too: checking:pending becomes assets:bank:checking:pending. (The+ alias must match the whole account name or its leading components, exactly+ and case sensitively; Checking, checkingfoo or old:checking would not be+ affected.)++ To declare multiple aliases, add more alias: tags. A Ledger-style alias+ subdirective, indented below the account directive, is also accepted, and+ treated as an alias: tag. To list the accounts with their aliases, run+ hledger accounts --show-aliases; to find the account(s) with a certain+ alias, run hledger accounts --show-aliases ALIAS.++ An alias affects the entries which follow it, in the current file and any+ files it includes (see directive scopes), until an end aliases directive.+ So it's best to declare accounts at the start of your main file, before any+ include directives.++ More powerful aliases, such as regular expression aliases which rewrite+ many accounts at once, can be declared with the alias directive, described+ below. An alias: tag is equivalent to a basic alias directive written just+ after the account directive:++ account assets:bank:checking ; alias: checking++ account assets:bank:checking+ alias checking = assets:bank:checking++ You can also apply aliases at runtime, without editing your files, using+ the --alias option.++ Account error checking+ By default, accounts need not be declared; they come into existence when a+ posting references them. This is convenient, but it means hledger can't+ warn you when you mis-spell an account name in the journal. Usually you'll+ find that error later, as an extra account in balance reports, or an incor-+ rect balance when reconciling.++ In strict mode, enabled with the -s/--strict flag, or when you run hledger+ check accounts, hledger will report an error if any transaction uses an ac-+ count name that has not been declared by an account directive. Some notes:++ * The declaration is case-sensitive; transactions must use the correct ac-+ count name capitalisation.++ * Account declarations affect all files (see directive scopes). The posi-+ tion of account directives within the file does not matter, though it's+ usual to put them at the top.++ * Accounts can only be declared in journal files, but will affect included+ files of all types.++ * It's currently not possible to declare "all possible subaccounts" with a+ wildcard; every account posted to must be declared.++ * As an exception: lot subaccounts (a final account name component like+ :{2026-01-15, $50}) are always ignored by check accounts, and need not be+ declared.++ * Also exempt are the accounts which hledger chooses for the postings it+ generates: equity conversion postings (from --infer-equity), gain post-+ ings (in lot disposals), and imbalance postings (from --infer-imbalance).+ Postings which you write to those accounts are checked as usual.++ Account display order+ Account directives also cause hledger to display accounts in a particular+ order, not just alphabetically. Eg, here is a conventional ordering for+ the top-level accounts:++ account assets+ account liabilities+ account equity+ account revenues+ account expenses++ Now hledger displays them in that order:++ $ hledger accounts+ assets+ liabilities+ equity+ revenues+ expenses++ If there are undeclared accounts, those will be displayed last, in alpha-+ betical order.++ Sorting is done within each group of sibling accounts, at each level of the+ account tree. Eg, a declaration like account parent:child influences+ child's position among its siblings.++ Note, it does not affect parent's position; for that, you need an account+ parent declaration.++ Sibling accounts are always displayed together; hledger won't display x:y+ in between a:b and a:c.++ An account directive both declares an account as a valid posting target,+ and declares its display order; you can't easily do one without the other.++ Account types+ hledger knows that in accounting there are three main account types:++ Asset A things you own+ Liability L things you owe+ Equity E owner's investment,+ balances the two+ above++ and two more representing changes in these:++ Revenue R inflows (also known+ as Income)+ Expense X outflows++ hledger also uses a few subtypes:++ Cash C liquid assets (subtype+ of Asset)+ Conversion V commodity conversions+ equity (subtype of Eq-+ uity)+ Gain G realised capital+ gains/losses (subtype+ of Revenue)+ UnrealisedGain U accumulated unrealised+ capital gains (subtype+ of Equity)+ Imbalance M transactions' tolerated+ imbalances, shown by+ --infer-imbalance (sub-+ type of Equity)++ As a convenience, hledger will detect these types automatically from eng-+ lish account names. But it's better to declare them explicitly by adding a+ type: tag in the account directives. The tag's value can be any of the+ types or one-letter abbreviations above.++ Here is a typical set of account type declarations. Subaccounts will in-+ herit their parent's type, or can override it:++ account assets ; type: A+ account liabilities ; type: L+ account equity ; type: E+ account revenues ; type: R+ account expenses ; type: X++ account assets:bank ; type: C+ account assets:cash ; type: C++ account equity:conversion ; type: V+ account equity:unrealised-gain ; type: U++ account revenues:gain ; type: G++ This enables the easy balancesheet, balancesheetequity, cashflow and in-+ comestatement reports, and querying by type:.++ Tips:++ * You can list accounts and their types, for troubleshooting:++ $ hledger accounts --types [ACCTPAT] [type:TYPECODES] [-DEPTH] [--locations]++ * It's a good idea to declare at least one account for each account type.+ Having some types declared and some inferred can disrupt certain reports.++ * The rules for inferring types from account names are as follows (using+ Regular expressions).+ If they don't work for you, just ignore them and declare your types with+ type: tags.++ If account's name contains this case insensitive regular expression | its type is+ --------------------------------------------------------------------|-------------+ ^assets?(:.+)?:(cash|bank|che(ck|que?)(ing)?|savings?|current)(:|$) | Cash+ ^assets?(:|$) | Asset+ ^(debts?|liabilit(y|ies))(:|$) | Liability+ ^equity:(trad(e|ing)|conversion)s?(:|$) | Conversion+ ^equity:unreali[sz]ed([- ](capital[- ])?gains?)?(:|$) | UnrealisedGain+ ^equity:imbalances?(:|$) | Imbalance+ ^equity(:|$) | Equity+ ^(income|revenue)s?:(capital[- ]?)?(gains?|loss(es)?)(:|$) | Gain+ ^(income|revenue)s?(:|$) | Revenue+ ^expenses?(:|$) | Expense++ * As mentioned above, subaccounts will inherit a type from their parent ac-+ count. To be precise, an account's type is decided by the first of these+ that exists:++ 1. A type: declaration for this account.++ 2. A type: declaration in the parent accounts above it, preferring the+ nearest.++ 3. An account type inferred from this account's name.++ 4. An account type inferred from a parent account's name, preferring the+ nearest parent.++ 5. Otherwise, it will have no type.++ * Account aliases can disrupt account types.++ alias directive+ (Note: this section is about account aliases, not commodity aliases or com-+ mand aliases.)++ alias directives are a more general and powerful form of the account+ aliases tags described above. (There is also a runtime variant, defined+ with the --alias option.)++ Account alias rules rewrite your account names, or parts of them, after+ reading the journal (affecting both directives and transactions), before+ generating reports. They do not affect account names being entered via+ hledger add or hledger-web.++ Account aliases can be useful for:++ * expanding shorthand account names to their full form, allowing easier+ data entry and a less verbose journal++ * adapting old journals to your current chart of accounts++ * experimenting with new account organisations, like a new hierarchy++ * combining two accounts into one, eg to see their sum or difference on one+ line++ * customising reports++ Basic aliases+ To set an account alias, use the alias directive in your journal file.+ This affects all subsequent journal entries in the current file or its in-+ cluded files (but note: not sibling or parent files; see directive scopes).+ The spaces around the = are optional:++ alias OLD = NEW++ Or, you can use --alias 'OLD=NEW' on the command line.++ Or, for a declared account, you can write the alias as an alias: tag on its+ account directive.++ OLD and NEW are case sensitive full account names. hledger will replace+ any occurrence of the old account name with the new one. Subaccounts are+ also affected. Eg:++ alias checking = assets:bank:wells fargo:checking+ ; rewrites "checking" to "assets:bank:wells fargo:checking", or "checking:a" to "assets:bank:wells fargo:checking:a"++ Regex aliases+ There is also a more powerful variant that uses a regular expression, indi-+ cated by wrapping the pattern in forward slashes. (This is the only place+ where hledger requires forward slashes around a regular expression.)++ Eg:++ alias /REGEX/ = REPLACEMENT++ or:++ $ hledger --alias '/REGEX/=REPLACEMENT' ...++ Any part of an account name matched by REGEX will be replaced by REPLACE-+ MENT. REGEX is case-insensitive as usual.++ If you need to match a forward slash, escape it with a backslash, eg /\/=:.++ If REGEX contains parenthesised match groups, these can be referenced by+ the usual backslash and number in REPLACEMENT:++ alias /^(.+):bank:([^:]+):(.*)/ = \1:\2 \3+ ; rewrites "assets:bank:wells fargo:checking" to "assets:wells fargo checking"++ REPLACEMENT continues to the end of line (or on command line, to end of op-+ tion argument), so it can contain trailing whitespace.++ --alias option+ The --alias command line option defines an account alias, using the same+ syntax as an alias directive (basic or regex), without editing your files.+ Eg:++ $ hledger bal --alias checking=assets:bank:checking+ $ hledger bal --alias '/^expenses:(food|dining)/=expenses:food'++ It can be repeated to define more aliases. These aliases affect all en-+ tries in all files (including CSV, timeclock and timedot files), wherever+ the option appears on the command line; and they are applied after any+ alias directives or alias: tags (see Combining aliases). They are not+ cleared by end aliases. This makes --alias useful for trying out aliases+ interactively, or for customising particular reports. You can also put+ --alias options in a config file.++ Combining aliases+ You can define as many aliases as you like, using journal directives and/or+ command line options.++ Recursive aliases - where an account name is rewritten by one alias, then+ by another alias, and so on - are allowed. Each alias sees the effect of+ previously applied aliases.++ In such cases it can be important to understand which aliases will be ap-+ plied and in which order. For (each account name in) each journal entry,+ we apply:++ 1. alias directives preceding the journal entry, most recently parsed first+ (ie, reading upward from the journal entry, bottom to top)++ 2. then any parent account from apply account directives is prepended++ 3. then --alias options, in the order they appeared on the command line+ (left to right).++ In other words, for (an account name in) a given journal entry:++ * the nearest alias declaration before/above the entry is applied first++ * the next alias before/above that will be applied next, and so on++ * aliases defined after/below the entry do not affect it.++ This gives nearby aliases precedence over distant ones, and helps provide+ semantic stability - aliases will keep working the same way independent of+ which files are being read and in which order.++ In case of trouble, adding --debug=6 to the command line will show which+ aliases are being applied when.++ Aliases and multiple files+ As explained at Directive scopes, alias directives (and alias: tags) do not+ affect parent or sibling files. Eg in this command,++ hledger -f a.aliases -f b.journal++ account aliases defined in a.aliases will not affect b.journal. Including+ the aliases doesn't work either:++ include a.aliases++ 2023-01-01 ; not affected by a.aliases+ foo 1+ bar++ This means that account aliases should usually be declared at the start of+ your top-most file, like this:++ alias foo=Foo+ alias bar=Bar++ 2023-01-01 ; affected by aliases above+ foo 1+ bar++ include c.journal ; also affected++ To affect all files read, whether they are included, or referenced by -f or+ the import command, use --alias options (which could be in a config file).+ Eg here the alias affects both a.journal and b.journal:++ hledger -f a.journal -f b.journal --alias foo=Foo++ end aliases directive+ This directive clears (forgets) all account aliases from alias directives+ and account alias: tags seen so far (but not aliases from command line+ --alias options):++ end aliases++ Aliases can generate bad account names+ Be aware that account aliases can produce malformed account names, which+ could cause confusing reports or invalid print output. For example, you+ could erase all account names:++ 2021-01-01+ a:aa 1+ b++ $ hledger print --alias '/.*/='+ 2021-01-01+ 1++ The above print output is not a valid journal. Or you could insert an il-+ legal double space, causing print output that would give a different jour-+ nal when reparsed:++ 2021-01-01+ old 1+ other++ $ hledger print --alias old="new USD" | hledger -f- print+ 2021-01-01+ new USD 1+ other++ Aliases and account types+ If an account with a type declaration (see Declaring accounts > Account+ types) is renamed by an alias, normally the account type remains in effect.++ However, renaming in a way that reshapes the account tree (eg renaming par-+ ent accounts but not their children, or vice versa) could prevent child ac-+ counts from inheriting the account type of their parents.++ Secondly, if an account's type is being inferred from its name, renaming it+ by an alias could prevent or alter that.++ If you are using account aliases and the type: query is not matching ac-+ counts as you expect, try troubleshooting with the accounts command, eg+ something like:++ $ hledger accounts --types -1 --alias assets=bassetts++ assert directive+ In addition to the point-in-time balance assertions in transaction entries,+ you can use assert directives to declare more general journal assertions.+ These are special queries asserting that certain report results do or do+ not exist at specified times. Like balance assertions, hledger checks+ these each time it reads the journal, unless you use --ignore-assertions or+ -I. You can declare conditions or goals that you want to be upheld, and+ whenever hledger reads the journal, if any rule is broken, it will report+ an error. Think "guard rails for your finances". (Note, a rule is only as+ good as its query, so test your new rules.)++ The syntax is:++ assert (none|some)[ PERIODEXPR][ QUERY]++ Ie, the assert keyword followed by none or some, then an optional period+ expression specifying when to check the assertion, then a+ two-or-more-spaces delimiter and a query specifying which postings or re-+ port rows to look for. The query is written as on the command line, with+ quotes around terms containing spaces. A ; comment can follow.++ A rule with a report interval can be followed by indented skip lines, each+ naming a date or period whose checks should be skipped, with an optional+ comment (useful for recording the reason). These skip checks, not data:+ postings in a skipped period still count in later balances. As usual, a+ range's end date is exclusive. Eg:++ assert none daily type:A balance:<0 ; no asset account is ever negative+ skip 2026-03-04..2026-03-08 ; transfer delayed by the bank holiday+ skip 2026-05 ; moving house++ A check is skipped if a date in a skip line is among the dates it examines.+ For a rule with a balance: term and no change: term, that is the period's+ last day (where its balance is tested); for other rules, it's any day in+ the period.++ Here are some examples. (Aligning is optional; just remember to put at+ least two spaces before each query.):++ assert none ; no postings exist+ assert some ; some postings exist++ ; journal maintenance+ assert some desc:'opening balances' ; the journal has an opening balances entry+ assert none assets:oldbank date:2025- ; nothing is posted to a closed account+ assert some assets:checking date:'-7 days..' ; bank data has been imported/added recently++ ; income+ assert some monthly to this month income:salary ; there's a salary transaction in each past month+ assert none monthly to this month income:salary change:<2000 ; at least this much was earned in each past month+ assert none monthly to this month income:salary change:>-2000 ; a more careful signed test, handling contrabalances & sign typos+ assert some monthly to this month desc:invoice any:'receivable amt:>0' ; an invoice was sent in each past month+ assert some monthly to this month desc:'payment for.*invoice' ; an invoice payment was received in each past month+ assert none assets:receivable balance:>15000 ; unpaid invoices are less than this, currently++ ; assets+ assert none daily type:A balance:<0 ; no asset account is ever negative (at end of day), in any commodity+ assert none daily assets:savings balance:<+10000 ; savings never drop below this much+ assert some assets:savings balance:>=+20000 ; savings hold at least this much, currently+ assert some monthly to this month not:tag:clopen assets:investments depth:2 change:>300 ; at least this much was invested in each past month (ignoring closing/opening entries)++ ; assets and liabilities+ assert some taxes type:AL depth:0 balance:>0 ; estimated tax savings exceed estimated tax due, currently++ ; liabilities+ assert some monthly to this month liabilities:card amt:>0 any:'assets amt:<0' ; a credit card payment was made in each past month+ assert none monthly liabilities:card balance:<-3000 ; no month ends with more than this much owed on the credit card+ assert none liabilities:card balance:<-500 ; current credit card balance is less than this++ ; expenses+ assert none expenses:misc amt:>+10 ; no single misc expense is larger than this (in any currency)+ assert none monthly expenses:dining change:>+$300 ; no month has more than this much $ dining expense+ assert none monthly expenses:dining depth:2 change:>+$300 ; the same, but include subaccounts like expenses:dining:fine++ Most query terms, like desc:, acct:, or amt:, select postings. balance:+ and change: terms instead test the balance or change of the accounts those+ postings are in.++ How assert rules work+ Assert rules are checked whenever the journal is read: by every command,+ and by hledger-ui and hledger-web when they reload (unless disabled with+ -I/--ignore-assertions, eg while you work on a failing rule). This happens+ after the journal is fully processed (after auto postings, transaction bal-+ ancing, balance assertions and lot calculation), so rules see generated+ postings and lot subaccounts, and forecast transactions when --forecast is+ used. Rules are checked in the order they were read, and the first rule+ that fails stops reading, with an error.++ Their scope is the file tree: an assert rule sees all entries in the main+ file and its included files, before and after it, but not entries read by+ other -f options. To check some extra rules without adding them to the+ journal, give them to the check command as quoted arguments: eg hledger+ check 'assert none daily type:A balance:<0'.++ Each rule is checked as if by a balance report, hledger bal -E QUERY, in+ four steps:++ 1. Select postings. The query's ordinary terms select and prepare postings+ as balance would: costs are ignored (amounts are summed in their origi-+ nal commodities), and depth: clips account names, merging subaccounts+ into their parent. date: terms don't select postings; they limit the+ report period, like -b/-e.++ 2. Calculate report rows. The selected postings are summed by account.+ Each row has the account's change during the period, and its balance at+ the end of the period (including all earlier postings, like bal -H).+ The rows are the accounts with selected postings in the period, plus,+ when the query has a balance: term, accounts with only earlier postings+ (their change is zero but their balance may not be).++ 3. Filter rows. change: terms test each row's change, and balance: terms+ test its end balance; a query can have both. Without these terms every+ row matches, so the rule is simply about whether any postings were se-+ lected.++ 4. Test. none passes if no row matches, and some passes if at least one+ does.++ These steps are done at one or more checkpoints, in date order:++ * With no period expression, there is one checkpoint, covering the whole+ journal (or the date: terms' span). So balance: tests the balances at+ the end of the journal, and change: tests the total change.++ * With a period expression, each of its periods is a checkpoint, and the+ rule must pass at every one. The periods are those bal would show with+ that report interval and -b START -e END. Eg daily checks each day's end+ balances or changes; monthly from 2024 checks each month from 2024 on.++ * A period with no rows passes a none rule and fails a some rule.++ * Relative dates in the period expression and query are resolved from to-+ day's date, so a rule like assert some assets:checking date:'-7 days..'+ can start failing just because time passes.++ * Daily is the smallest checking interval (assert does not check after+ every transaction).++ So you can check "no asset account is ever negative (at end of day)" with+ assert none daily type:A balance:<0. Without daily, only the final bal-+ ances would be checked.++ When a rule fails, the error shows the rule, every period in which it+ failed, and up to 10 of the rows (or postings) which matched in those peri-+ ods. Only the first failing rule is reported; others may be failing too.++ These assertions have a cost: each rule makes reading the journal slightly+ slower. Rules matching few postings cost less, and balance: rules checked+ daily across many accounts cost more.++ Tips for writing assert rules+ * none gives more useful errors. When you have a choice, prefer none, be-+ cause when it fails it shows the offending rows, whereas a failing some+ rule can only say nothing matched.++ * For more precise amount tests, add a sign and/or commodity. A plain num-+ ber, as in balance:>100, ignores sign, and matches if any commodity's+ amount does. Often that is enough, but if you want to handle contrabal-+ ances or sign typos, add a sign: balance:>+100. And to limit the test to+ one commodity, add its symbol, as in balance:<-$5000, or add a cur: term.++ * Subaccounts are not included by default. Each row's amount is the ac-+ count's own exclusive change or balance (like = in a balance assertion).+ To include subaccount balances, limit the depth: eg expenses:dining+ depth:2 folds expenses:dining's subaccounts into it. (To fold just some+ accounts, use depth:REGEX=N.)++ * depth:0 folds all matched accounts into one row. This lets you test two+ accounts of opposite sign against each other. Eg "savings always cover+ the credit card debt" is assert none daily acct:'^(assets:savings|lia-+ bilities:card)' depth:0 balance:<0.++ * date: terms combine with the period expression's span. Eg assert none+ monthly assets date:2026- balance:<0 means the same as assert none+ monthly from 2026 assets balance:<0. to thismonth is useful for "every+ past month" rules, excluding the current incomplete month.++ * Avoid not:date: in rules with a balance: term. It does not skip that+ date's check, it removes that date's postings from all later balances.+ Use skip lines instead.++ * Account names are matched after account aliases have been applied, as in+ reports.++ comment directive+ A line containing just comment causes all following lines to be ignored,+ until an end comment directive or file end.++ end comment directive+ A line containing just end comment ends the effect of a preceding comment+ directive.++ commodity directive+ commodity directives declare commodity symbols (for error checking) and+ their preferred display style (digit group marks, decimal digits, and sym-+ bol position). Eg:++ commodity $1,000.00+ commodity 1000,00 EUR+ commodity a 1,00,00,000.00+ commodity 1000. ; the no-symbol commodity++ The sample amount must include a decimal mark (even if there are no decimal+ digits after it). This tells the parser which decimal mark (period or+ comma) is used for this commodity in the journal file, which can be useful+ in case of ambiguous digit group marks. This affects subsequent entries in+ the current file, its included files, and the rest of any parent files (see+ directive scopes), and it can be overridden by a decimal-mark directive.++ Commodity directive syntax+ In more detail. A commodity directive is normally the word commodity fol-+ lowed by a sample amount (only its format is significant), and optionally a+ comment. Eg:++ commodity $1000.00+ commodity 1.000,00 EUR+ commodity 1 000 000.0000 ; the no-symbol commodity++ A commodity directive's sample amount must always include a decimal mark+ (period or comma). If you don't want to show any decimal digits, write the+ decimal mark at the end:++ commodity 1000. AAAA ; show AAAA with no decimals++ Commodity symbols containing spaces, numbers, or punctuation must be en-+ closed in double quotes, as usual:++ commodity 1.0000 "AAAA 2023"++ Commodity directives normally include a sample amount, but can declare only+ a symbol (ie, just function 1 above):++ commodity $+ commodity INR+ commodity "AAAA 2023"+ commodity "" ; the no-symbol commodity++ Commodity directives may also be written with an indented format subdirec-+ tive, as in Ledger. The symbol is repeated and must be the same in both+ places. Other subdirectives are ignored:++ ; display indian rupees with currency name on the left,+ ; thousands, lakhs and crores comma-separated,+ ; period as decimal point, and two decimal places.+ commodity INR+ format INR 1,00,00,000.00+ other subdirective ; ignored++ A commodity can be declared more than once, eg in a main file and an in-+ cluded file, or in several files read with -f. The later declaration will+ override or add to the earlier one, as follows: its display style (if it+ has one) replaces the earlier style, its tags take precedence over the ear-+ lier tags, and its aliases are added to the earlier aliases. ("Later"+ means later in the order hledger reads them: through each file and its in-+ cluded files, then the next -f file.) --debug=1 shows any commodities+ which files read with -f declare with different display styles.++ Commodity tags+ A commodity directive's comment may contain tags. These will be inherited+ by all postings using that commodity in their main amount, except where the+ posting already has a value for that tag. (A posting tag or an account tag+ overrides a commodity tag.) Note, these tags will be queryable but won't+ be shown in print output, even with --verbose-tags.++ Commodity aliases+ An alias: tag on a commodity directive declares another symbol/name for+ that commodity. You can add several (quoting any that contain spaces or+ other special characters, as usual):++ commodity USD 1.00 ; alias: $, alias: US$, alias: "us dollars"++ When hledger reads the journal, amounts written with an alias are converted+ to the canonical commodity. So they combine with it in reports, and a+ transaction can balance across them. This helps when, eg, your bank data,+ manual entries and downloaded market prices use different symbols for the+ same currency. Declare the symbol you want reports to show, and the others+ as its aliases.++ Some details:++ * print shows amounts as they were written; print -x shows them converted+ to the canonical commodity.++ * cur: queries match the canonical symbol, not the aliases (with the above+ declaration, $5 would be matched by cur:USD, and not by cur:'\$').++ * An alias can't have aliases of its own, and the same alias can't be de-+ clared on two different commodities.++ Commodity units+ A commodity alias can also specify a quantity. Amounts written with the+ alias are divided by this quantity (and their unit costs and market prices+ are multiplied by it). This is useful for expressing differently-sized+ units of a commodity. Eg:++ commodity 1.00 hrs ; alias: 60 min+ commodity $1.00 ; alias: 0.001 K, alias: 0.000001 M++ (Avoid decimal commas here, which would end the tag's value; use ., or ex-+ ponential notation, alias: 1E-6 M.)++ You can report in any of these units, eg with -X min or -X M (valuation,+ described later).++ Note, these units keep the symbol placement they were declared with, but+ inherit the canonical commodity's number format and display/transac-+ tion-balancing precisions. If you want them to have a different display+ style, eg more decimals to make small quantities visible, give them a com-+ modity directive too:++ commodity $1.00 ; alias: 0.001 K, alias: 0.000001 M+ commodity 1.000 K+ commodity 1.000000 M++ When the conversion gives a repeating decimal (like 1/60 hour per minute),+ it is stored internally at maximum precision (255 decimals, see Amount+ arithmetic). To keep costs and balance assertions exact, a unit cost on+ such an amount is replaced by the exact total cost (10 min @ $1 becomes+ 0.1666... hrs @@ $10), and balance assertions add up the alias amounts be-+ fore converting them (so three 10 min amounts satisfy a = 0.5 hrs asser-+ tion).++ Commodity aliases or market prices?+ Both let you convert between symbols. When should you use one or the other+ ?++ Use a commodity alias when the symbols mean the same thing in different+ names or units ($ and USD, min and hrs). The conversion happens always and+ automatically.++ Use a P directive when they are different things with an exchange rate,+ even a fixed one. The conversion happens only when you ask for it.++ Commodity alias scope+ Commodity aliases (with or without a quantity) work in two ways, with dif-+ ferent scopes:++ * When hledger reads the journal, they convert the amounts written with+ them, in their own file tree only (before or after the directive). A+ file read with another -f option is a separate file tree, so its amounts+ are not converted. To share aliases between journals, put the commodity+ directives in a file which they all include (or which includes them all).++ * With -X, they also act as fixed exchange rates in all file trees, as a+ last resort when market prices can't do the conversion (see Finding mar-+ ket price). Eg -X USD can convert $ amounts in another file tree that+ didn't declare that alias.++ Commodity error checking+ In strict mode (-s/--strict) (or when you run hledger check commodities),+ hledger will report an error if an undeclared commodity symbol is used+ (aliases count as declared). There's one exception: zero amounts are al-+ ways allowed to have no commodity symbol.++ decimal-mark directive+ You can use a decimal-mark directive to declare unambiguously which charac-+ ter (period or comma) represents a decimal mark, for all subsequent amounts+ in the current file and its included files (see directive scopes). This+ helps when parsing ambiguous numbers (like 1.000 or 1,000 where you mean+ one thousand, not one). It also makes hledger check that numbers use that+ decimal mark and no other, which catches some typos and misparsed numbers.+ With decimal-mark ,, a number like 1,000.00 is reported as an error; and+ with decimal-mark ., a number like 1.2.34 is reported as an error, instead+ of being read as 1234.++ Eg, at the top of each journal file:++ decimal-mark .++ or++ decimal-mark ,++ This directive only affects parsing, and it takes precedence over commodity+ directives. So you can declare preferred decimal marks for display, which+ may be different from the decimal mark(s) used in the data files. (The+ amounts in commodity and D directives are allowed to use a different deci-+ mal mark.)++ Without a decimal-mark directive, a commodity directive's decimal mark is+ used to interpret that commodity's ambiguous numbers, but it is not en-+ forced: numbers like 1.2.34 or 1.000,00 (when the format is 1,000.00) are+ accepted. So if you want these checks, use decimal-mark.++ include directive+ You can pull in the content of additional files by writing an include di-+ rective, like this:++ include SOMEFILE++ This has the same effect as if SOMEFILE's content was inlined at this+ point. (With any include directives in SOMEFILE processed similarly, re-+ cursively.)++ Only journal files can include other files. They can include journal,+ timeclock, timedot, CSV/SSV/TSV, or CSV rules files.++ When a CSV file is included, its rules file is FILE.rules alongside it, as+ usual; the --rules option is not used here. To use a different rules file,+ or a data file located elsewhere (eg in your downloads directory), include+ a rules file which has a source rule instead. Transactions generated from+ included CSV data are treated like inlined journal entries: they are placed+ at this point, any account aliases in effect are applied to them, and their+ balance assertions are checked along with the rest of the journal (unlike+ when reading a CSV file directly, where balance assertions are ignored).+ Other directives which affect journal parsing (like Y, D, decimal-mark, ap-+ ply account) do not affect CSV data. Note that if you include a CSV file+ in your main journal, you should not also import it, or its transactions+ would be duplicated.++ If the file path begins with a tilde, that means your home directory: in-+ clude ~/main.journal.++ If it begins with a slash, it is an absolute path: include+ /home/user/main.journal. Otherwise it is relative to the including file's+ folder: include ../finances/main.journal.++ Also, the path may have a file type prefix to force a specific file format,+ overriding the file extension(s) (as described in Data formats): include+ timedot:notes/2023.md.++ The path may contain glob patterns to match multiple files. hledger's+ globs are similar to zsh's: ? to match any character; [a-z] to match any+ character in a range; * to match zero or more characters that aren't a path+ separator (like /); ** to match zero or more subdirectories and/or zero or+ more characters at the start of a file name; etc. For convenience, include+ always excludes the current file. So, you can do++ * include *.journal to include all other journal files in the current di-+ rectory (excluding dot files)++ * include **.journal to include all other journal files in this directory+ and below (excluding dot files and top-level dot directories)++ * include timelogs/2???.timedot to include all timedot files named like a+ year number.++ Note * and ** usually won't match dot files or dot directories, with one+ exception: ** does search non-top-level dot directories. If this causes+ problems, make your glob pattern more specific (eg **.journal instead of+ **).++ To see all the files being read, and which file includes each one, run+ hledger files --tree.++ If you are using many, or deeply nested, include files, and have an error+ that's hard to pinpoint: a good troubleshooting command is hledger files+ --debug=6 (or 7).++ P directive+ The P directive declares a market price, which is a conversion rate between+ two commodities on a certain date. This allows value reports to convert+ amounts of one commodity to their value in another, on or after that date.+ These prices are often obtained from a stock exchange, cryptocurrency ex-+ change, or the foreign exchange market.++ The format is:++ P DATE COMMODITY1SYMBOL COMMODITY2AMOUNT++ DATE is a simple date, COMMODITY1SYMBOL is the symbol of the commodity be-+ ing priced, and COMMODITY2AMOUNT is the amount (symbol and quantity) of+ commodity 2 that one unit of commodity 1 is worth on this date. Examples:++ # one euro was worth $1.35 from 2009-01-01 onward:+ P 2009-01-01 a $1.35++ # and $1.40 from 2010-01-01 onward:+ P 2010-01-01 a $1.40++ The -V, -X and --value flags use these market prices to show amount values+ in another commodity. See Value reporting.++ payee directive+ payee PAYEE NAME++ This directive can be used to declare a limited set of payees which may ap-+ pear in transaction descriptions. The "payees" check will report an error+ if any transaction refers to a payee that has not been declared. (This is+ quite a strict check, and not often used.)++ Eg:++ payee Whole Foods ; a comment++ To declare the empty payee name, use "".++ payee ""++ Payees do not support tags. Any indented subdirectives are ignored.++ tag directive+ tag TAGNAME++ This directive can be used to declare a limited set of tag names allowed in+ tags. TAGNAME should be a valid tag name (no spaces). Eg:++ tag item-id++ Any indented subdirectives are ignored.++ The "tags" check will report an error if any undeclared tag name is used.+ It is quite easy to accidentally create a tag through normal use of colons+ in comments; if you want to prevent this, you can declare and check your+ tags.++ Periodic transactions+ The ~ directive declares a "periodic rule" which generates temporary extra+ transactions, usually recurring at some interval, when hledger is run with+ the --forecast flag. These "forecast transactions" are useful for fore-+ casting future activity. They exist only at report time, when --forecast+ is used; they are not saved in the journal file.++ Periodic rules also have a second use: with the --budget flag they set bud-+ get goals for budgeting.++ Periodic rules can be a little tricky, so before you use them, read this+ whole section, or at least the following tips:++ 1. Two spaces accidentally added or omitted in the rule will cause you+ trouble - see below.++ 2. For troubleshooting, show the generated transactions with hledger print+ --forecast tag:generated or hledger register --forecast tag:generated.++ 3. Forecasted transactions will begin only after the last non-forecasted+ transaction's date.++ 4. Forecasted transactions will end 6 months from today, by default. See+ below for the exact start/end rules.++ 5. Period expressions with report intervals can be tricky; note how they+ make start/end date adjustments.++ Periodic rule syntax+ A periodic transaction rule looks like a normal journal entry, with the+ date replaced by a tilde (~) followed by a period expression (mnemonic: ~+ looks like a recurring sine wave.):++ # every first of month+ ~ monthly+ expenses:rent $2000+ assets:bank:checking++ # every 15th of month in 2023's second quarter:+ ~ monthly from 2023-04-15 to 2023-06-16+ expenses:utilities $400+ assets:bank:checking++ The period expression is the same syntax used for specifying multi-period+ reports, just interpreted differently; there, it specifies report periods;+ here it specifies recurrence dates (the periods' start dates).++ Periodic rules and relative dates+ Partial or relative dates (like 12/31, 25, tomorrow, last week, next quar-+ ter) are usually not recommended in periodic rules, since the results will+ change as time passes. If used, they will be interpreted relative to, in+ order of preference:++ 1. the first day of the default year specified by a recent Y directive++ 2. or the date specified with --today++ 3. or the date on which you are running the report.++ They will not be affected at all by report period or forecast period dates.++ Two spaces between period expression and description!+ If the period expression is followed by a transaction description, these+ must be separated by two or more spaces. This helps hledger know where the+ period expression ends, so that descriptions can not accidentally alter+ their meaning, as in this example:++ ; 2 or more spaces needed here, so the period is not understood as "every 2 months in 2023"+ ; ||+ ; vv+ ~ every 2 months in 2023, we will review+ assets:bank:checking $1500+ income:acme inc++ So,++ * Do write two spaces between your period expression and your transaction+ description, if any.++ * Don't accidentally write two spaces in the middle of your period expres-+ sion.++ Auto postings+ The = directive declares an "auto posting rule", which adds extra postings+ to existing transactions. (Remember, postings are the account name &+ amount lines below a transaction's date & description.)++ In the journal, an auto posting rule looks quite like a transaction, but+ instead of date and description it has = (mnemonic: "match") and a query,+ like this:++ = QUERY+ ACCOUNT AMOUNT+ ...++ Queries are just like command line queries; an account name substring is+ most common. Query terms containing spaces should be enclosed in single or+ double quotes.++ Each = rule works like this: when hledger is run with the --auto flag,+ wherever the QUERY matches a posting in the journal, the rule's postings+ are added to that transaction, immediately below the matched posting. Note+ these generated postings are temporary, existing only for the duration of+ the report, and only when --auto is used; they are not saved in the journal+ file by hledger.++ The postings can contain the special string %account which will be expanded+ to the account name of the matched account.++ Generated postings' amounts can depend on the matched posting's amount. So+ auto postings can be useful for, eg, adding tax postings with a standard+ percentage. AMOUNT can be:++ * a number with no commodity symbol, like 2. The matched posting's commod-+ ity symbol will be added to this.++ * a normal amount with a commodity symbol, like $2. This will be used+ as-is.++ * an asterisk followed by a number, like *2. This will multiply the+ matched posting's amount (and total price, if any) by the number.++ * an asterisk followed by an amount with commodity symbol, like *$2. This+ multiplies and also replaces the commodity symbol with this new one.++ Some examples:++ ; every time I buy food, schedule a dollar donation+ = expenses:food+ (liabilities:charity) $-1++ ; when I buy a gift, also deduct that amount from a budget envelope subaccount+ = expenses:gifts+ assets:checking:gifts *-1+ assets:checking *1++ 2017/12/1+ expenses:food $10+ assets:checking++ 2017/12/14+ expenses:gifts $20+ assets:checking++ $ hledger print --auto+ 2017-12-01+ expenses:food $10+ assets:checking+ (liabilities:charity) $-1++ 2017-12-14+ expenses:gifts $20+ assets:checking+ assets:checking:gifts -$20+ assets:checking $20++ Note that depending fully on generated data such as this has some drawbacks+ - it's less portable, less future-proof, less auditable by others, and less+ robust (eg your balance assertions will depend on whether you use or don't+ use --auto). An alternative is to use auto postings in "one time" fashion+ - use them to help build a complex journal entry, view it with hledger+ print --auto, and then copy that output into the journal file to make it+ permanent.++ Auto postings and multiple files+ An auto posting rule can affect any transaction in the current file, or in+ any parent file or child file. Note, currently it will not affect sibling+ files (when multiple -f/--file are used - see #1212).++ Auto postings and dates+ A posting date (or secondary date) in the matched posting, or (taking+ precedence) a posting date in the auto posting rule itself, will also be+ used in the generated posting.++ Auto postings and transaction balancing / inferred amounts / balance asser-+ tions+ Currently, auto postings are added:++ * after missing amounts are inferred, and transactions are checked for bal-+ ancedness,++ * but before balance assertions are checked.++ Note this means that journal entries must be balanced both before and after+ auto postings are added.++ This also means that you cannot have more than one auto-posting with a+ missing amount applied to a given transaction, as it will be unable to in-+ fer amounts.++ Auto posting tags+ Automated postings will have some extra tags:++ * generated-posting:= QUERY - shows this was generated by an auto posting+ rule, and the query++ * _generated-posting:= QUERY - a hidden tag, which does not appear in+ hledger's output. This can be used to match postings generated "just+ now", rather than generated in the past and saved to the journal.++ Also, any transaction that has been changed by auto posting rules will have+ these tags added:++ * modified: - this transaction was modified++ * _modified: - a hidden tag not appearing in the comment; this transaction+ was modified "just now".++ Auto postings on forecast transactions only+ Tip: you can can make auto postings that will apply to forecast transac-+ tions but not recorded transactions, by adding tag:_generated-transaction+ to their QUERY. This can be useful when generating new journal entries to+ be saved in the journal.++ Other syntax+ hledger journal format supports quite a few other features, mainly to make+ interoperating with or converting from Ledger easier. Note some of the+ features below are powerful and can be useful in special cases, but in gen-+ eral, features in this section are considered less important or even not+ recommended for most users. Downsides are mentioned to help you decide if+ you want to use them.++ Amount expressions+ AKA "inline math". Since 1.99.6++ A posting amount can also be a simple arithmetic expression, which hledger+ calculates when reading the journal. This saves doing sums by hand, and+ records how an amount was arrived at:++ 2026-03-02 groceries, two receipts+ assets:checking+ expenses:food $50.20 + $16.54 ; $66.74++ 2026-03-05 laptop, plus 5% sales tax+ liabilities:card+ expenses:equipment $800.00+ expenses:tax $800.00 * 0.05 ; $40.00++ 2026-03-07 hardware store, 3 boxes of screws less a $2 coupon+ liabilities:card+ expenses:supplies 3 * $4.99 - $2 ; $12.97++ Downsides: Complicates standard bookkeeping notation; could obscure a post-+ ing's true amount. Makes it harder for other apps to read your journal.++ Amount expression syntax+ * You can use +, -, *, / and parentheses. * and / are done before + and -;+ otherwise it's left to right. A minus sign can also go before parenthe-+ ses, eg -($1 + $2).++ * Spaces around the operators are optional, except that a / right after a+ commodity symbol needs a space before it: 10 EUR / 4 works, 10 EUR/4 is+ an error.++ * + and - need amounts in the same commodity. You can write the commodity+ just once, since a plain number takes the other side's commodity: $10 + 5+ is $15.++ * * and / need a plain number on at least one side, eg $800.00 * 0.05, 3 *+ $4.99 or $100.00 / 3. The result is in the other side's commodity. So a+ plain number divided by an amount is in that amount's commodity, as in+ Ledger; this is handy for inverting an exchange rate: 1 / 1.25 EUR is+ 0.80 EUR.++ * A cost, lot annotation or balance assertion can follow an expression, and+ applies to its result: 10 EUR + 5 EUR @ $1.10 is 15 EUR, costing $1.10+ each.++ * A cost can be an expression too, eg 1 GBP @ (1 / 1.14 EUR) or 3 AAPL @@+ $450 + $5.++ * Expressions can be used only in posting amounts (in journal format, or in+ CSV rules) and transacted costs, not in cost basis annotations, balance+ assertions, directives, or auto posting rule multipliers (*AMT).++ Amount expression rounding+ The result of + or - is exact, and shows as many decimal places as the more+ precise of the two amounts.++ The result of * or / is rounded, using banker's rounding, to the entry's+ decimal places for that commodity: the most decimal places written in that+ commodity's amounts in the entry, including amounts inside expressions or+ balance assignments, but not cost amounts, or the plain numbers used with *+ or /. These are the same decimal places hledger uses to check that the en-+ try balances (see Transaction balancing). So:++ * $100/3 is $33.33 in an entry that also has $-100.00, but $33 when all of+ the entry's dollar amounts are whole numbers.++ * $10 * 0.15 on its own is $2; write $10.00 * 0.15 to get $1.50.++ * For more decimal places, write more: $100.0000 / 3 is $33.3333.++ * In periodic transaction rules and auto posting rules, a result is rounded+ to its own decimal places, eg $100/3 is $33 and $100.00/3 is $33.33.++ * A result with no commodity gets the default commodity from a D directive,+ if any, as usual. It is then like any other plain number after a D di-+ rective, whose decimal places count: after D $1,000.00, 5 / 2 is $2.50.++ A cost calculated with * or / is not rounded, since a rounded rate could be+ far off ($10 / 1.14 would be $9). hledger keeps it exact, and shows it+ with all its decimal places, or 8 if it's a repeating decimal (more if+ written), eg 1 GBP @ $10 / 1.14 prints as 1 GBP @ $8.77192982.++ The rounded amount is what hledger stores (see also Where hledger divides).+ So a split that doesn't divide evenly leaves the entry unbalanced, and the+ error message says that such amounts are rounded. To fix it, leave one+ amount blank, and hledger will give it the remainder:++ 2026-03-09 dinner with Ana and Raj, split three ways+ liabilities:card $-107.00+ assets:receivable:ana ($92.00 + $15.00) / 3 ; $35.67+ assets:receivable:raj ($92.00 + $15.00) / 3 ; $35.67+ expenses:food ; $35.66++ Amount expressions are not kept+ hledger keeps only an expression's result. print (including --export, and+ all its output formats), other reports and error messages show the result,+ eg $66.74, not $50.20 + $16.54. If you need to keep the parts visible,+ write them in a comment too.++ Balance assignments+ Ledger-style balance assignments are also supported. These are like bal-+ ance assertions, but with no posting amount on the left side of the equals+ sign; instead it is calculated automatically so as to satisfy the asser-+ tion. This can be a convenience during data entry, eg when setting opening+ balances:++ ; starting a new journal, set asset account balances+ 2016/1/1 opening balances+ assets:checking = $409.32+ assets:savings = $735.24+ assets:cash = $42+ equity:opening balances++ or when adjusting a balance to reality:++ ; no cash left; update balance, record any untracked spending as a generic expense+ 2016/1/15+ assets:cash = $0+ expenses:misc++ The calculated amount depends on the account's balance in the commodity at+ that point (which depends on the previously-dated postings of the commodity+ to that account since the last balance assertion or assignment).++ Downsides: using balance assignments makes your journal less explicit; to+ know the exact amount posted, you have to run hledger or do the calcula-+ tions yourself, instead of just reading it. Also balance assignments'+ forcing of balances can hide errors. These things make your financial data+ less portable, less future-proof, and less trustworthy in an audit.++ Balance assignments and costs+ A cost in a balance assignment will cause the calculated amount to have+ that cost attached:++ 2019/1/1+ (a) = $1 @ a2++ $ hledger print --explicit+ 2019-01-01+ (a) $1 @ a2 = $1 @ a2++ Balance assignments and subaccounts+ Subaccount-inclusive balance assignments (=* or ==*) are also supported.+ The calculated amount is posted to the account named, making its balance+ including subaccounts equal the assigned balance; the subaccounts' balances+ are not changed. =* sets the balance in just the assigned commodity, while+ ==* also clears any other commodities.++ 2026-01-01+ liabilities:card $-30+ liabilities:loan $-200+ expenses++ 2026-01-15 a windfall pays off all liabilities+ liabilities ==* $0+ income:windfall++ $ hledger print --explicit date:2026-01-15+ 2026-01-15 a windfall pays off all liabilities+ liabilities $230 ==* $0+ income:windfall $-230++ $ hledger bal liabilities+ $230 liabilities+ $-30 liabilities:card+ $-200 liabilities:loan+ --------------------+ 0++ Balance assignments and multiple files+ Balance assignments handle multiple files like balance assertions. They+ see balance from other files previously included from the current file, but+ not from previous sibling or parent files.++ Bracketed posting dates+ For setting posting dates and secondary posting dates, Ledger's bracketed+ date syntax is also supported: [DATE], [DATE=DATE2] or [=DATE2] in posting+ comments. hledger will attempt to parse any square-bracketed sequence of+ the 0123456789/-.= characters in this way. With this syntax, DATE infers+ its year from the transaction and DATE2 infers its year from DATE.++ Downsides: another syntax to learn, redundant with hledger's date:/date2:+ tags, and confusingly similar to Ledger's lot date syntax.++ D directive+ D AMOUNT++ This directive sets a default commodity, to be used for any subsequent com-+ modityless amounts (ie, plain numbers) seen while parsing the journal.+ This affects subsequent entries until the next D directive, or the end of+ the current file (including its included files; see directive scopes).++ For compatibility/historical reasons, D also acts like a commodity direc-+ tive (setting the commodity's decimal mark for parsing and display style+ for output). So its argument is not just a commodity symbol, but a full+ amount demonstrating the style. The amount must include a decimal mark+ (either period or comma). Eg:++ ; commodity-less amounts should be treated as dollars+ ; (and displayed with the dollar sign on the left, thousands separators and two decimal places)+ D $1,000.00++ 1/1+ a 5 ; <- commodity-less amount, parsed as $5 and displayed as $5.00+ b++ Interactions with other directives:++ For setting a commodity's display style, a commodity directive has highest+ priority, then a D directive.++ For detecting a commodity's decimal mark during parsing, decimal-mark has+ highest priority, then commodity, then D.++ For checking commodity symbols with the check command, a commodity direc-+ tive is required (hledger check commodities ignores D directives).++ Downsides: omitting commodity symbols makes your financial data less ex-+ plicit, less portable, and less trustworthy in an audit. It is usually an+ unsustainable shortcut; sooner or later you will want to track multiple+ commodities. D is overloaded with functions redundant with commodity and+ decimal-mark. And it works differently from Ledger's D.++ apply account directive+ This directive sets a default parent account, which will be prepended to+ all accounts in following entries, until an end apply account directive or+ end of current file. Eg:++ apply account home++ 2010/1/1+ food $10+ cash++ end apply account++ is equivalent to:++ 2010/01/01+ home:food $10+ home:cash $-10++ (If the parent account name ends with a colon (apply account home:), it is+ ignored, as in Ledger.)++ account directives are also affected, and so is any included content.++ Account names entered via hledger add or hledger-web are not affected.++ Account aliases from alias directives are applied before the parent account+ is prepended (as in Ledger), so they match the account names as written.+ This means a file's aliases keep working when it is included under apply+ account. (Before hledger 2, they were applied after.) --alias options are+ applied after the parent account is prepended, so they match the full ac-+ count names.++ Downsides: this can make your financial data less explicit, less portable,+ and less trustworthy in an audit.++ Y directive+ Y YEAR++ or (deprecated backward-compatible form):++ year YEAR++ The space is optional. This sets a default year to be used for subsequent+ dates which don't specify a year. Eg:++ Y2009 ; set default year to 2009++ 12/15 ; equivalent to 2009/12/15+ expenses 1+ assets++ year 2010 ; change default year to 2010++ 2009/1/30 ; specifies the year, not affected+ expenses 1+ assets++ 1/31 ; equivalent to 2010/1/31+ expenses 1+ assets++ Downsides: omitting the year (from primary transaction dates, at least)+ makes your financial data less explicit, less portable, and less trustwor-+ thy in an audit. Such dates can get separated from their corresponding Y+ directive, eg when evaluating a region of the journal in your editor. A+ missing Y directive makes reports dependent on today's date.++ apply year directive+ apply year YEAR sets a default year like Y, but only until a matching end+ apply year directive (or the end of the current file). end apply year re-+ stores the default year that was in effect before the matching apply year.+ These blocks can be nested, as in Ledger (which also lets a bare end or end+ apply close them; hledger requires end apply year). Eg:++ Y 2009++ apply year 2010+ 1/31 ; 2010-01-31+ expenses 1+ assets+ end apply year++ 2/28 ; 2009-02-28+ expenses 1+ assets++ An end apply year with no matching apply year is an error. (Before hledger+ 2, apply year worked like Y, and end apply year was ignored.)++ Secondary dates+ A secondary date is written after the primary date, following an equals+ sign: DATE1=DATE2. If the year is omitted, the primary date's year is as-+ sumed. When running reports, the primary (left side) date is used by de-+ fault, but with the --date2 flag (--aux-date or--effective also work, for+ Ledger users), the secondary (right side) date will be used instead.++ The meaning of secondary dates is up to you. Eg it could be "primary is+ the bank's clearing date, secondary is the date the transaction was initi-+ ated, if different".++ In practice, this feature usually adds confusion:++ * You have to remember the primary and secondary dates' meaning, and follow+ that consistently.++ * It splits your bookkeeping into two modes, and you have to remember which+ mode is appropriate for a given report.++ * Usually your balance assertions will work with only one of these modes.++ * It makes your financial data more complicated, less portable, and less+ clear in an audit.++ * It interacts with every feature, creating an ongoing cost for implemen-+ tors.++ * It distracts new users and supporters.++ * Posting dates are simpler and work better.++ So secondary dates are officially deprecated in hledger, remaining only as+ a Ledger compatibility aid; we recommend using posting dates instead.++ Star comments+ Lines beginning with * (star/asterisk) are also comment lines, for Ledger+ compatibility. Emacs users can use these as foldable org headings. (But+ it's usually better to use ledger-mode, and add outshine minor mode for+ org-like folding.)++ Valuation expressions+ Ledger allows a valuation function or value to be written in double paren-+ theses after an amount. hledger ignores these.++ Virtual postings+ A posting with parentheses around the account name, like (some:account)+ 10, is called an unbalanced virtual posting. These postings do not partic-+ ipate in transaction balancing. (And if you write them without an amount,+ a zero amount is always inferred.) These can occasionally be convenient+ for special circumstances, but they violate double entry bookkeeping and+ make your data less portable across applications, so many people avoid us-+ ing them at all.++ A posting with brackets around the account name ([some:account]) is called+ a balanced virtual posting. The balanced virtual postings in a transaction+ must add up to zero, just like ordinary postings, but separately from them.+ These are not part of double entry bookkeeping either, but they are at+ least balanced. An example:++ 2022-01-01 buy food with cash, update budget envelope subaccounts, & something else+ assets:cash $-10 ; <- these balance each other+ expenses:food $7 ; <-+ expenses:food $3 ; <-+ [assets:checking:budget:food] $-10 ; <- and these balance each other+ [assets:checking:available] $10 ; <-+ (something:else) $5 ; <- this is not required to balance++ Ordinary postings, whose account names are neither parenthesised nor brack-+ eted, are called real postings. You can exclude virtual postings from re-+ ports with the -R/--real flag or a real:1 query.++ Other Ledger directives+ These other Ledger directives are currently accepted but ignored. This al-+ lows hledger to read more Ledger files, but be aware that hledger's reports+ may differ from Ledger's if you use these.++ apply fixed COMM AMT+ apply tag TAG+ bucket / A ACCT+ capture ACCT REGEX+ check EXPR+ define VAR=EXPR+ end apply fixed+ end apply tag+ end tag+ eval / expr EXPR+ python+ PYTHONCODE+ tag NAME+ value EXPR+ --command-line-flags++ Ledger's assert EXPR directive is not supported: assert is hledger's assert+ directive, which has a different syntax, so a Ledger-style assert line is+ an error.++ See also https://hledger.org/ledger.html for a detailed hledger/Ledger syn-+ tax comparison.++ Ledger virtual costs+ In Ledger, (@) UNITCOST and (@@) TOTALCOST are virtual costs, which do not+ generate market prices. In hledger, these are equivalent to @ and @@.++ Ledger cost basis+ In Ledger, these annotations after an amount help specify or select a lot's+ cost basis: {LOTUNITCOST} or {{LOTTOTALCOST}}, [LOTDATE], and/or (LOTNOTE).+ hledger will read these, as an alternative to its own cost basis syntax.++ We also read Ledger's fixed price syntax, {=LOTUNITCOST} or {{=LOTTOTAL-+ COST}}, treating it as equivalent to {LOTUNITCOST} or {{LOTTOTALCOST}}.++CSV+ hledger can read transactions from CSV (comma-separated values) files.+ More precisely, it can read DSV (delimiter-separated values), from a file+ or standard input. Comma-separated, semicolon-separated and tab-separated+ are the most common variants, and hledger recognises these three automati-+ cally from the file extension.++ (To learn about producing CSV or TSV output, see Output format.)++ Each CSV file must be described by a corresponding rules file. This con-+ tains rules describing the CSV data (header line, fields layout, date for-+ mat etc.), how to construct hledger transactions from it, and how to cate-+ gorise transactions based on description or other attributes.++ By default, hledger expects this rules file to be named like the CSV file,+ with an extra .rules extension added, in the same directory. Eg when asked+ to read foo/FILE.csv, hledger looks for foo/FILE.csv.rules. You can spec-+ ify a different rules file with the --rules option (for CSV files specified+ on the command line; not for ones included by a journal file).++ At minimum, the rules file must identify the date and amount fields, and+ often it also specifies the date format and how many header lines there+ are. Here's a simple CSV file and a rules file for it:++ Date, Description, Id, Amount+ 12/11/2019, Foo, 123, 10.23++ # basic.csv.rules+ skip 1+ fields date, description, , amount+ date-format %d/%m/%Y++ $ hledger print -f basic.csv+ 2019-11-12 Foo+ expenses:unknown 10.23+ income:unknown -10.23++ Or you can read the rules file itself, if it has a source rule saying where+ the data is (eg source ./basic.csv): hledger print -f basic.csv.rules.+ This is the usual setup for regular importing; see Finding the data.++ There's an introductory Tutorial: Import CSV data on hledger.org, and more+ CSV rules examples below, and a larger collection at+ https://github.com/hledgerorg/hledger/tree/main/examples/csv.++ CSV rules cheatsheet+ The following kinds of rule can appear in the rules file, in any order.+ (Blank lines and lines beginning with # or ; are ignored.)++ source optionally declare which file to read data+ from+ archive optionally enable an archive of imported+ files+ separator declare the field separator, instead of rely-+ ing on file extension+ encoding optionally declare which text encoding the+ data has+ skip skip header line(s) at start of file, or (in-+ side an if rule) the current record(s)+ date-format declare how to parse CSV dates/date-times+ timezone declare the time zone of ambiguous CSV+ date-times+ decimal-mark declare the decimal mark used in CSV amounts,+ when ambiguous+ newest-first improve txn order when: there are multiple+ records, newest first, all with the same date+ intra-day-reversed improve txn order when: same-day txns are in+ opposite order to the overall file+ fields name CSV fields for easy reference, and op-+ tionally assign their values to hledger+ fields+ Field assignment assign a CSV value or interpolated text value+ to a hledger field+ balance-type select which type of balance assertions/as-+ signments to generate+ if conditionally assign values to hledger+ fields, or skip one or more records+ ifs declare multiple if rules in a compact table+ format+ end (inside an if rule) skip the current and all+ remaining records+ merge combine this record with the next one(s), to+ be converted to a single transaction+ include inline another CSV rules file++ Working with CSV tips and How CSV rules are evaluated can be found below.++ Finding the data+ You can name a CSV file on the command line, as in hledger -f foo.csv CMD,+ and hledger will use the rules file named like it (foo.csv.rules).++ Or you can name the rules file, as in hledger -f foo.csv.rules CMD. The+ rules file must then have a source rule (described below), saying which+ data file to read (perhaps in your web browser's download directory), or+ which command to run to get the data.++ The second way is more powerful. This and the archive rule below, and the+ default behaviour of the get and import commands, help remove the busywork+ of managing CSV downloads. Ideally, you can periodically++ 1. Download new CSVs from your banks (perhaps by just running hledger get).++ 2. Import new transactions from all the CSVs specified by rules files in+ rules/, by just running hledger import.++ Or, do both with one command: hledger import -g++ After import, you can discard the CSV immediately, or leave it where it is+ for a while, or archive it automatically (to data/archive/) with the+ archive rule.++ It's also possible to include a CSV file or rules file in your journal, in+ which case there's no import step at all; instead, the whole CSV is recon-+ verted on each run.++ source+ When hledger reads a rules file (-f foo.csv.rules), the source rule says+ which data file to read (it is ignored if you name the data file instead,+ as in -f foo.csv):++ source ./Checking1.csv++ If the file does not exist, it is just considered empty, without raising an+ error.++ A rules file (and any included rules file) can have only one source rule.+ To read several data files, use a rules file for each; they can include+ their common rules.++ The file path is resolved this way:++ * Absolute paths and ~-prefixed paths are used as-is.++ * A path beginning with ./ or ../ (source ./Checking1.csv) is anchored rel-+ ative to the rules file's directory (as in hledger 1).++ * Any other relative path (source bank/Checking1.csv), or a bare file name+ (source Checking1.csv), is searched for first in a data/ directory next+ to the main journal file (also used by the archive rule and the get com-+ mand), then in your ~/Downloads folder.++ You can use a glob pattern, to avoid specifying the file name exactly:++ source Checking1*.csv++ A glob pattern has another benefit: if it matches multiple files, hledger+ reads just one of them: the newest, so stale copies are ignored; or when+ importing with archive, the oldest, which is then archived, so that succes-+ sive imports process the copies in order.++ Data cleaning / data generating commands+ After source's file pattern, you can write | (pipe) and a data cleaning+ command (or command pipeline) (since hledger 1.50). If hledger's CSV rules+ aren't enough, you can pre-process the downloaded data here with a shell+ command or script, to make it more suitable for conversion. The command+ will be executed by your default shell, in the directory of the rules file,+ will receive the data file's content as standard input, and should output+ zero or more lines of character-separated-values, suitable for conversion+ by the CSV rules.++ Examples:++ source ./paypal.json | paypalcsv+ source data/simplefin.json | simplefincsv - 'chase.*card'+ source OfxDownload*.csv | grep -vE '^(([^,]*,){6}[^,]*|)$' | sort -t, -n +2+ source History_for_Account_Z20144832*.csv # | grep -E '^([^,]*,){12}[^,]*$' | sed -E -e 's/^ //' -e 's/\.([0-9]),/.\10,/g' -e 's/,([0-9]+),/,\1.00,/g'++ Or, after source you can write | and a data generating command (with no+ file pattern before the |). This command receives no input, and should+ output zero or more lines of character-separated values, suitable for con-+ version by the CSV rules.++ Examples:++ source | paypaljson | paypalcsv+ source | paypalcsv data/paypal.json+ source | simplefinjson >data/simplefin.json && simplefincsv data/simplefin.json 'chase.*card'+ source | simplefincsv data/simplefin.json 'unify.*checking'++ (paypal* and simplefin* scripts are in bin/)++ Whenever hledger runs one of these commands, it will echo the command on+ stderr, prefixed by the rules file's name. If the command produces error+ output, but exits successfully, hledger will show the error output as a+ warning. If a data cleaning command fails, hledger will fail and show the+ error output in the error message. If a data generating command fails,+ hledger will show the error as a warning and continue, treating this as if+ no data was found.++ These commands run in an import --dry-run too, since their output is needed+ to preview the data. So they should be safe to run repeatedly: a data+ cleaning command should be a pure filter, and a data generating command+ should not consume or change anything that the real import will need. A+ fetch that isn't safe to repeat belongs in the get command's getdata script+ instead (which get --dry-run and import --dry-run -g don't run), with a+ file pattern to read its output.++ archive+ With archive added to a rules file, the import command will archive each+ successfully processed data file or data command output in an archive/ sub-+ directory of the data/ directory next to the main journal file. The+ archive file name will be based on the rules file and the data file's modi-+ fication date and extension (or for a data-generating command, the current+ date and the ".csv" extension). The original data file, once archived,+ will be removed.++ Also, in this mode import will prefer the oldest file matched by the source+ rule's glob pattern, not the newest. (So if there are multiple downloads,+ they will be imported and archived oldest first.)++ Archiving is optional, but it can be useful for troubleshooting your CSV+ rules, regenerating entries with improved rules, checking for variations in+ your bank's CSV, etc.++ File Extension+ To help hledger choose the CSV file reader and show the right error mes-+ sages (and choose the right field separator character by default), it's+ best if CSV/SSV/TSV files are named with a .csv, .ssv or .tsv filename ex-+ tension. (More about this at Data formats.)++ When reading files with the "wrong" extension, you can ensure the CSV+ reader (and the default field separator) by prefixing the file path with+ csv:, ssv: or tsv:: Eg:++ $ hledger -f ssv:foo.dat print++ You can also override the default field separator with a separator rule if+ needed.++ Reading CSV from standard input+ You'll need the file format prefix when reading CSV from stdin also, since+ hledger assumes journal format by default. Eg:++ $ cat foo.dat | hledger -f ssv:- print++ Reading multiple CSV files+ If you use multiple -f options to read multiple CSV files at once, hledger+ will look for a correspondingly-named rules file for each CSV file. But if+ you specify a rules file with --rules, that rules file will be used for all+ the CSV files.++ Alternatively, a journal file can include CSV files (or rules files). In+ this case each CSV file always uses its correspondingly-named rules file;+ --rules has no effect.++ Reading the data+ These tips and rules help hledger read the CSV data correctly: check that+ it's valid, choose its separator, decode its text, skip any header lines,+ parse its dates and numbers, and put its records in the right order.++ Valid CSV+ Note that hledger will only accept valid CSV conforming to RFC 4180, and+ equivalent SSV and TSV formats (like RFC 4180 but with semicolon or tab as+ separators). This means, eg:++ * Values may be enclosed in double quotes, or not. Enclosing in single+ quotes is not allowed. (Eg 'A','B' is rejected.)++ * When values are enclosed in double quotes, spaces outside the quotes are+ not allowed. (Eg "A", "B" is rejected.)++ * When values are not enclosed in quotes, they may not contain double+ quotes. (Eg A"A, B is rejected.)++ If your CSV/SSV/TSV is not valid in this sense, you'll need to transform it+ before reading with hledger. Try using sed, or a more permissive CSV+ parser like python's csv lib.++ separator+ You can use the separator rule to read other kinds of character-separated+ data. The argument is any single separator character, or the words tab or+ space (case insensitive). Eg, for comma-separated values (CSV):++ separator ,++ or for semicolon-separated values (SSV):++ separator ;++ or for tab-separated values (TSV):++ separator TAB++ If the input file has a .csv, .ssv or .tsv file extension (or a csv:, ssv:,+ tsv: prefix), the appropriate separator will be inferred automatically, and+ you won't need this rule.++ encoding+ encoding ENCODING++ hledger normally expects non-ascii text to be using the system locale's+ text encoding. If you need to read CSV files which have some other encod-+ ing, you can do it by adding encoding ENCODING to your CSV rules. Eg: en-+ coding iso-8859-1.++ The supported encodings are: ascii, utf-8, utf-16, utf-32, iso-8859-1 to+ iso-8859-11 and iso-8859-13 to iso-8859-16, cp1250 to cp1258, koi8-r,+ koi8-u, gb18030, macintosh, jis-x-0201, jis-x-0208, iso-2022-jp, shift-jis,+ cp437, cp737, cp775, cp850, cp852, cp855, cp857, cp860 to cp866, cp869,+ cp874, and cp932.++ skip+ skip N++ The word skip followed by a number (or no number, meaning 1) tells hledger+ to ignore this many non-empty lines at the start of the input data. You'll+ need this whenever your CSV data contains header lines. Note, empty and+ blank lines are skipped automatically, so you don't need to count those.++ skip has a second meaning: it can be used inside an if rule (described be-+ low), to skip one or more records whenever the condition is true. Records+ skipped in this way are ignored, except they are still required to be valid+ CSV.++ date-format+ date-format DATEFMT++ This is a helper for the date (and date2) fields. If your CSV dates are+ not formatted like YYYY-MM-DD, YYYY/MM/DD or YYYY.MM.DD, you'll need to add+ a date-format rule describing them with a strptime-style date parsing pat-+ tern - see https://hackage.haskell.org/package/time/docs/Data-Time-For-+ mat.html#v:formatTime. The pattern must parse the CSV date value com-+ pletely. Some examples:++ # MM/DD/YY+ date-format %m/%d/%y++ # D/M/YYYY+ # The - makes leading zeros optional.+ date-format %-d/%-m/%Y++ # YYYY-Mmm-DD+ date-format %Y-%h-%d++ # M/D/YYYY HH:MM AM some other junk+ # Note the time and junk must be fully parsed, though only the date is used.+ date-format %-m/%-d/%Y %l:%M %p some other junk++ Note currently there is no locale awareness for things like %b, and setting+ LC_TIME won't help.++ timezone+ timezone TIMEZONE++ When CSV contains date-times that are implicitly in some time zone other+ than yours, but containing no explicit time zone information, you can use+ this rule to declare the CSV's native time zone, which helps prevent+ off-by-one dates.++ When the CSV date-times do contain time zone information, you don't need+ this rule; instead, use %Z in date-format (or %z, %EZ, %Ez; see the format-+ Time link above).++ In either of these cases, hledger will do a time-zone-aware conversion, lo-+ calising the CSV date-times to your current system time zone. If you pre-+ fer to localise to some other time zone, eg for reproducibility, you can+ (on unix at least) set the output timezone with the TZ environment vari-+ able, eg:++ $ TZ=-1000 hledger print -f foo.csv # or TZ=-1000 hledger import foo.csv++ timezone currently does not understand timezone names, except "UTC", "GMT",+ "EST", "EDT", "CST", "CDT", "MST", "MDT", "PST", or "PDT". For others, use+ numeric format: +HHMM or -HHMM.++ decimal-mark+ decimal-mark .++ or:++ decimal-mark ,++ hledger automatically accepts either period or comma as a decimal mark when+ parsing numbers (cf Amounts). However if any numbers in the CSV contain+ digit group marks, such as thousand-separating commas, you should declare+ the decimal mark explicitly with this rule, to avoid misparsed numbers.+ Like the decimal-mark directive, this also makes hledger report numbers us-+ ing a different decimal mark, or repeating the declared one (like 1.2.34),+ as errors. This applies to amounts from the CSV fields and to amounts+ written in the rules.++ newest-first+ hledger tries to ensure that the generated transactions will be ordered+ chronologically, including same-day transactions. Usually it can auto-de-+ tect how the CSV records are ordered. But if it encounters CSV where all+ records are on the same date, it assumes that the records are oldest first.+ If in fact the CSV's records are normally newest first, like:++ 2022-10-01, txn 3...+ 2022-10-01, txn 2...+ 2022-10-01, txn 1...++ you can add the newest-first rule to help hledger generate the transactions+ in correct order.++ # same-day CSV records are newest first+ newest-first++ intra-day-reversed+ If CSV records within a single day are ordered opposite to the overall+ record order, you can add the intra-day-reversed rule to improve the order+ of journal entries. Eg, here the overall record order is newest first, but+ same-day records are oldest first:++ 2022-10-02, txn 3...+ 2022-10-02, txn 4...+ 2022-10-01, txn 1...+ 2022-10-01, txn 2...++ # transactions within each day are reversed with respect to the overall date order+ intra-day-reversed++ CSV fields and hledger fields+ The main task of CSV rules is to convert CSV fields to hledger fields.+ It's important to know which is which, when you are creating rules:++ 1. CSV fields++ * are the parts of the records (lines) in your CSV data++ * are referenced by their position or assigned name, with a % prefix+ (eg %1 or %date)++ * are read-only.++ 2. hledger fields++ * are the parts of a hledger journal entry (see hledger fields) (eg+ date, description, account1, amount1)++ * are assigned to by rules, to construct a journal entry++ * can be referenced by their name, without a % prefix, inside a %{...}+ expression (eg %{description}; see Referencing other fields).++ CSV rules can't make new fields; you can't define your own variables in a+ rules file. (But you could add new CSV fields to the data before running+ rules, with a preprocessing script.)++ It's ok for a CSV field and a hledger field to have the same name; in a+ fields list, this causes the CSV field's value to be assigned to the+ hledger field ("field name punning"). hledger knows which kind of field is+ meant from the context: in field values and matchers, %NAME is a CSV field,+ and a bare HLEDGERFIELDNAME inside %{...} is a hledger field. Some exam-+ ples:++ # set the journal entry's date to the value of CSV field 1+ date %1++ # name the CSV fields, and use the first as the entry's date+ fields date, bankamt++ # test the value of the CSV date field+ if %date 2026+ ...++ # add a tag to the hledger comment field, keeping any comment assigned before+ comment %{join(", ", comment, "imported:")}++ fields+ fields FIELDNAME1, FIELDNAME2, ...++ A fields list (the word fields followed by comma-separated field names) is+ optional, but convenient. It does two things:++ 1. It names the CSV field in each column. This can be convenient if you+ are referencing them in other rules, so you can say %SomeField instead+ of remembering %13.++ 2. Whenever you use one of the special hledger field names (described be-+ low), it assigns the CSV value in this position to that hledger field.+ This is the quickest way to populate hledger's fields and build a trans-+ action.++ Here's an example that says "use the 1st, 2nd and 4th fields as the trans-+ action's date, description and amount; name the last two fields for later+ reference; and ignore the others":++ fields date, description, , amount, , , somefield, anotherfield++ In fields, the names are always separated by commas; this is unrelated to+ the CSV file's separator. Also:++ * There must be least two items in the list (at least one comma).++ * Field names may not contain spaces. Spaces before/after field names are+ optional.++ * Field names may contain _ (underscore) or - (hyphen).++ * Fields you don't care about can be given a dummy name or an empty name.++ If the CSV contains column headings, it's convenient to use these for your+ field names, suitably modified (eg lower-cased with spaces replaced by un-+ derscores).++ Sometimes you may want to alter a CSV field name to avoid assigning to a+ hledger field with the same name. Eg you could call the CSV's "balance"+ field balance_ to avoid directly setting hledger's balance field (and gen-+ erating a balance assertion).++ Field assignment+ HLEDGERFIELD FIELDVALUE++ Field assignments are the more flexible way to assign CSV values to hledger+ fields. They can be used instead of or in addition to a fields list (see+ above).++ To assign a value to a hledger field, write the field name (any of the+ standard hledger field/pseudo-field names, defined below), a space, fol-+ lowed by a text value on the same line. This text value may interpolate+ CSV fields, referenced either by their 1-based position in the CSV record+ (%N) or by the name they were given by fields (%CSVFIELD), and regular ex-+ pression match groups (\N), and can transform them with functions (%{up-+ per(%CSVFIELD)}) or use other hledger fields' values (%{description}; see+ Referencing other fields). You can also write %(CSVFIELD) to delimit the+ field name from adjacent text (eg %(field)suffix). When CSV records have+ been combined by a merge rule, a _ROWNUM suffix (eg %amt_2, %4_2) refer-+ ences the later rows' fields. Interpolation strips outer whitespace (so a+ CSV value like " 1 " becomes 1 when interpolated) (#1051).++ Some examples:++ # set the amount to the 4th CSV field, with " USD" appended+ amount %4 USD++ # combine three fields to make a comment, containing note: and date: tags+ comment note: %somefield - %anotherfield, date: %1++ # use parenthesised form when the field name would run into adjacent text+ account1 assets:%(type)checking++ Functions+ Since 1.99.6; experimental++ To transform a value while interpolating it, write a %{...} expression+ calling one of the built-in functions below. Eg:++ # upper-case the description+ description %{upper(%desc)}++ # use the category in lower case, or "misc" if it's empty+ account2 expenses:%{lower(default(%category, "misc"))}++ # remove a reference number from the description+ description %{replace(%desc, " *ref#[0-9]+", "")}++ # put the date's year and month in a tag+ comment month:%{substr(%date, 1, 7)}++ # show the last four digits of the card number+ comment card:%{substr(%card, -4)}++ Function arguments can be CSV field references (%summary or %3), hledger+ field names (comment), match group references (\1), double-quoted text+ ("misc"), numbers, or other function calls. Use \" for a double quote in-+ side double-quoted text. Each expression's result has outer whitespace re-+ moved, like other interpolated values.++ function result+ --------------------------------------------------------------------------+ upper(TEXT) TEXT in upper case+ lower(TEXT) TEXT in lower case+ capitalize(TEXT) TEXT with each word's first letter in upper case+ and the rest in lower case (capitalise also works)+ trim(TEXT) TEXT without outer whitespace+ negate(AMOUNT) AMOUNT with its sign flipped, eg 5 -> -5, -5 or (5)+ -> 5+ abs(AMOUNT) AMOUNT without a minus sign, eg -5 or (5) -> 5+ concat(TEXT, ...) all the arguments joined together+ join(SEP, TEXT, the TEXTs that aren't empty, joined with SEP be-+ ...) tween them+ default(TEXT, ...) the first argument that's not empty+ replace(TEXT, TEXT with each match of REGEX replaced by REPL+ REGEX, REPL)+ substr(TEXT, START, LENGTH characters of TEXT, starting at position+ LENGTH) START (1 is the first, -1 the last); LENGTH is op-+ tional++ For replace, REGEX must be double-quoted text, and is a case-insensitive+ regular expression. REPL can use \1, \2 etc. to insert REGEX's match+ groups. (Unquoted \1 etc. outside double quotes refer to the match groups+ of an enclosing if rule instead.) For substr, START and LENGTH must be+ numbers. A negative START counts from the end, so eg substr(%card, -4)+ gives the last four characters. Positions before the start or after the+ end of TEXT are treated as the start or end.++ For negate and abs, AMOUNT is a number, optionally with a commodity symbol+ before or after it, and optionally with a sign: - or + before it, or paren-+ theses meaning negative around it. The sign can be before or after a com-+ modity symbol written in front of the number. Eg these are all negative+ amounts: -5, (5), -$5, $-5, $(5), USD -5, -5 USD, (5 USD). The number it-+ self isn't parsed, so its decimal mark and digit group marks don't matter.+ negate converts 5 to -5 and $-1,000.50 to $1,000.50, and abs converts any+ of the above to the unsigned form. A sign after the number (5-), or paren-+ theses around just the number when the symbol comes after it ((5) USD), are+ not supported.++ join is useful for combining parts which may be empty, without stray sepa-+ rators. Eg comment %{join(", ", %note, %ref)}.++ Mistakes in an expression, like an unknown function or the wrong number of+ arguments, are reported when the rules file is read. Text beginning with+ %{ is always taken as an expression.++ Referencing other fields+ To use a hledger field's value, write its name (without %) inside a %{...}+ expression. %NAME always means a CSV field, even when a hledger field has+ the same name:++ # name the third CSV field "amount1"+ fields date, description, amount1+ # set hledger's amount1 to the CSV amount1 field, followed by USD+ amount1 %amount1 USD+ # the CSV amount1 field, eg "5"+ comment %amount1+ # hledger's amount1 field, eg "5 USD"+ comment1 %{amount1}++ When there are multiple field assignments to the same hledger field, only+ the last one takes effect (though it can include the earlier value, see be-+ low). Here, comment's value will be B, or C if "something" is matched, but+ never A:++ comment A+ comment B+ if something+ comment C++ In an assignment to the same field, a hledger field's name gives the+ field's value from its previous assignment, so you can add to it. This is+ handy for appending to a comment:++ fields date, description, comment, amount+ if refund+ # add a refund tag+ comment %{comment}, refund:+ # or, avoiding a redundant separator when comment is empty:+ #comment %{join(", ", comment, "refund:")}++ "Previous assignment" here means the one before this one, in this order:+ top-level assignments (including those made by fields), then assignments in+ matched if rules, each in the order written. (So a top-level assignment+ comes before any if rule's, even if written after it.)++ In an assignment to a different field, a hledger field's name gives that+ field's final value, wherever it is assigned. Eg here, comment is set to+ the final value of the hledger description:++ comment %{description}++ When interpolating a hledger field, the value is the text assigned to the+ field by these rules, before further processing by hledger. Eg %{amount1}+ is the amount text before any sign simplification, and %{account2} is empty+ if account2 isn't assigned (not expenses:unknown).++ hledger fields+ Here are all the hledger fields you can assign to. They correspond to+ parts of a journal entry, or in some cases they are pseudo-fields which+ have a special effect. You can also interpolate their values in %{...} ex-+ pressions, except for the -in/-out amount fields.++ date field+ Assigning to date sets the transaction date. This is required. If the CSV+ dates aren't like YYYY-MM-DD, see date-format (and timezone).++ date2 field+ date2 sets the transaction's secondary date, if any.++ status field+ status sets the transaction's status, if any.++ code field+ code sets the transaction's code, if any.++ Journal format can't represent a right parenthesis in a code (when+ reparsed, it would end the code early). So any right parentheses here will+ be replaced with ], with a warning.++ description field+ description sets the transaction's description, if any.++ Journal format can't represent a semicolon in a description (when reparsed,+ it would start a comment, truncating the description). So any semicolons+ here will be replaced with ., (a semicolon on its side), and a warning is+ printed.++ comment field+ comment sets the transaction's comment, if any.++ commentN, where N is a number, sets the Nth posting's comment.++ You can assign multi-line comments by writing literal \n in the code. A+ comment starting with \n will begin on a new line.++ Comments can contain tags, as usual.++ Posting comments can also contain a posting date. A secondary date, or a+ year-less date, will be ignored.++ account field+ Assigning to accountN, where N is 1 to 99, sets the account name of the Nth+ posting, and causes that posting to be generated.++ Most often there are two postings, so you'll want to set account1 and ac-+ count2. Typically account1 is associated with the CSV file, and is set+ once with a top-level assignment, while account2 is set based on each+ transaction's description, in if rules.++ If a posting's account name is left unset but its amount is set, the ac-+ count name will be set to expenses:unknown or income:unknown (depending on+ the amount's sign).++ amount field+ There are several ways to set posting amounts from CSV, useful in different+ situations.++ 1. amount is the oldest and simplest. Assigning to this sets the amount of+ the first and second postings. In the second posting, the amount will+ be negated; also, if it has a cost attached, it will be converted to+ cost.++ 2. amount-in and amount-out work exactly like the above, but should be used+ when the CSV has two amount fields (such as "Debit" and "Credit", or+ "Inflow" and "Outflow"). Whichever field has a non-zero value will be+ used as the amount of the first and second postings. Here are some tips+ to avoid confusion:++ * It's not "amount-in for posting 1 and amount-out for posting 2", it+ is "extract a single amount from the amount-in or amount-out field,+ and use that for posting 1 and (negated) for posting 2".++ * Don't use both amount and amount-in/amount-out in the same rules+ file; choose based on whether the amount is in a single CSV field or+ spread across two fields.++ * In each record, at most one of the two CSV fields should contain a+ non-zero amount; the other field must contain a zero or nothing.++ * hledger assumes both CSV fields contain unsigned numbers, and it au-+ tomatically negates the amount-out values.++ * If the data doesn't fit these requirements, you'll probably need an+ if rule (see Setting amounts).++ 3. amountN (where N is a number from 1 to 99) sets the amount of only a+ single posting: the Nth posting in the transaction. You'll usually need+ at least two such assignments to make a balanced transaction. You can+ also generate more than two postings, to represent more complex transac-+ tions. The posting numbers don't have to be consecutive; with if rules,+ higher posting numbers can be useful to ensure a certain order of post-+ ings.++ 4. amountN-in and amountN-out work exactly like the above, but should be+ used when the CSV has two amount fields. This is analogous to amount-in+ and amount-out, and those tips also apply here.++ 5. Remember that fields can also do assignments. So if you name a CSV+ field "amount" in fields, that counts as assigning to amount. (If you+ don't want that, call it something else there, like "amount_".)++ 6. The above don't handle every situation; if you need more flexibility,+ use an if rule to set amounts conditionally. See Setting amounts below+ for more on this and on amount-setting generally.++ If the CSV numbers have digit group marks (like 1,000.00), see deci-+ mal-mark.++ An amount value can be an amount expression, eg amount1 %price + %fee (see+ Amount signs for how this interacts with sign handling).++ Setting amounts+ Which amount fields to use depends on how the CSV shows amounts:++ 1. If the amount is in a single CSV field:++ a. If its sign indicates direction of flow:+ Assign it to amountN, to set the Nth posting's amount. N is usually 1+ or 2 but can go up to 99.++ b. If another field indicates direction of flow:+ Use one or more if rules to set the appropriate amount sign. Eg:++ # assume a withdrawal unless Type contains "deposit":+ amount1 -%Amount+ if %Type deposit+ amount1 %Amount++ 2. If the amount is in two CSV fields (such as Debit and Credit, or In and+ Out):++ a. If both fields are unsigned:+ Assign one field to amountN-in and the other to amountN-out. hledger+ will automatically negate the "out" field, and will use whichever field+ value is non-zero as posting N's amount.++ b. If either field is signed:+ You will probably need to override hledger's sign for one or the other+ field, as in the following example:++ # Negate the -out value, but only if it is not empty:+ fields date, description, amount1-in, amount1-out+ if %amount1-out [1-9]+ amount1-out -%amount1-out++ c. If both fields can contain a non-zero value (or both can be empty):+ The -in/-out rules normally choose the value which is+ non-zero/non-empty. Some value pairs can be ambiguous, such as 1 and+ none. For such cases, use if rules to help select the amount. Eg, to+ handle the above you could select the value containing non-zero digits:+ rules fields date, description, in, out if %in [1-9] amount1 %in+ if %out [1-9] amount1 %out++ 3. If you want posting 2's amount converted to cost:+ Use the unnumbered amount (or amount-in and amount-out) syntax.++ 4. If the CSV has only balance amounts, not transaction amounts:+ Assign to balanceN, to set a balance assignment on the Nth posting, causing+ the posting's amount to be calculated automatically. balance with no num-+ ber is equivalent to balance1. In this situation hledger is more likely to+ guess the wrong default account name, so you may need to set that explic-+ itly.++ Amount signs+ There is some special handling making it easier to parse and to reverse+ amount signs. (This only works for whole amounts, not for cost amounts+ such as COST in amount1 AMT @ COST):++ * If an amount value begins with a plus sign:+ that will be removed: +AMT becomes AMT++ * If an amount value is parenthesised:+ it will be de-parenthesised and sign-flipped: (AMT) becomes -AMT++ * If an amount value has two minus signs (or two sets of parentheses, or a+ minus sign and parentheses):+ they cancel out and will be removed: --AMT or -(AMT) becomes AMT++ * If an amount value contains just a sign (or just a set of parentheses):+ that is removed, making it an empty value. "+" or "-" or "()" becomes "".++ These rules don't apply to a value containing an arithmetic operator (*, /,+ or a + or - which is not a leading sign or an exponent sign as in 1e-5),+ which is read as an amount expression instead. In an expression, parenthe-+ ses group rather than negate: -(%price + %fee) is minus the sum.++ To set an amount to its absolute value, ie discard its sign, use the abs+ function, eg amount1 %{abs(%amt)}.++ Amount decimal places+ When you are reading CSV data, eg with a command like hledger -f foo.csv+ print, hledger will infer each commodity's decimal precision (and other+ commodity display styles) from the amounts - much as when reading a journal+ file without commodity directives (see the link).++ Note, the commodity styles are not inferred from the numbers in the origi-+ nal CSV data; rather, they are inferred from the amounts generated by the+ CSV rules.++ When you are importing CSV data with the import command, eg hledger import+ foo.csv, there's another step: import tries to make the new entries conform+ to the journal's existing styles. So for each commodity - let's say it's+ EUR - import will choose:++ 1. the style declared for EUR by a commodity directive in the journal++ 2. otherwise, the style inferred from EUR amounts in the journal++ 3. otherwise, the style inferred from EUR amounts generated by the CSV+ rules.++ TLDR: if import is not generating the precisions or styles you want, add a+ commodity directive to specify them.++ currency field+ currency sets a default commodity symbol, to be used for any posting (or+ balance) amounts which don't have one. You can use this if the CSV amounts+ do not have a currency symbol, eg if it is in a separate column. (You can+ also set the symbol within an amount assignment, like amount %amt USD, but+ sometimes it's more convenient to set it this way.) The value can be:++ * a commodity symbol, like USD or $ or "Some Fund"; this is placed on the+ left of the number, with no space (USD5).++ * or a dummy amount with that symbol, like 1 USD or USD 1 or 1USD, showing+ the symbol's position and spacing to use. (The amount's number style, if+ any, like 1.000,00 EUR, is also used as a default display style for that+ commodity.)++ Note the symbol's placement and display style don't matter much when using+ import, since that command applies the journal's existing commodity styles+ to the new entries (see Amount decimal places).++ currencyN does the same for just the Nth posting's amount.++ Setting currency/commodity+ If the currency/commodity symbol is included in the CSV's amount field(s):++ 2023-01-01,foo,$123.00++ you don't have to do anything special for the commodity symbol, it will be+ assigned as part of the amount. Eg:++ fields date,description,amount++ 2023-01-01 foo+ expenses:unknown $123.00+ income:unknown $-123.00++ If the currency is provided as a separate CSV field:++ 2023-01-01,foo,USD,123.00++ You can name that field currency; this is a special rule, which sets the+ commodity of every amount in the transaction which doesn't have one (plac-+ ing the symbol on the left, with no separating space):++ fields date,description,currency,amount++ 2023-01-01 foo+ expenses:unknown USD123.00+ income:unknown USD-123.00++ To put the symbol on the right, separated by a space, give the currency+ rule a dummy amount showing that:++ fields date,description,cur,amt+ currency 1 %cur+ amount %amt++ 2023-01-01 foo+ expenses:unknown 123.00 USD+ income:unknown -123.00 USD++ Or, you can use a field assignment to construct the amount yourself: amount+ %amt %cur.++ balance field+ balanceN sets a balance assertion amount (or if the posting amount is left+ empty, a balance assignment) on posting N.++ balance is a compatibility spelling for hledger <1.17; it is equivalent to+ balance1.++ You can adjust the type of assertion/assignment with the balance-type rule+ (see below). If the CSV has only balances, not transaction amounts, see+ Setting amounts.++ balance-type+ Balance assertions generated by assigning to balanceN are of the simple =+ type by default, which is a single-commodity, subaccount-excluding asser-+ tion. You may find the subaccount-including variants more useful, eg if+ you have created some virtual subaccounts of checking to help with budget-+ ing. You can select a different type of assertion with the balance-type+ rule:++ # balance assertions will consider all commodities and all subaccounts+ balance-type ==*++ Here are the balance assertion types for quick reference:++ = single commodity, exclude subaccounts+ =* single commodity, include subaccounts+ == multi commodity, exclude subaccounts+ ==* multi commodity, include subaccounts++ if+ Rules can be applied conditionally, depending on patterns in the CSV data.+ This is how you can categorise transactions, selecting an appropriate ac-+ count based on their description (eg).++ An if rule is the word if, followed by one or more "matcher" expressions+ starting on the same line or the next line, followed by one or more in-+ dented rules. Eg,++ if MATCHER+ RULE++ or++ if+ MATCHER+ MATCHER+ MATCHER+ RULE+ RULE++ Comment lines can appear anywhere within an if rule, and blank lines can+ also appear among the indented rules; these do not end the rule. (One ex-+ ception: a matcher on the same line as if can begin with a comment charac-+ ter (eg if #groceries matches records containing "#groceries"); but on the+ lines below if, such a line would be read as a comment. There, escape the+ comment character with a backslash, eg \#groceries.)++ If any of the matchers succeeds, all of the indented rules will be applied.+ The rules are usually field assignments, but the following special rules+ may also be used within an if rule:++ * skip - skips the matched CSV record (generating no transaction from it)+ (described above).++ * end - skips the rest of the current CSV file (described below).++ * merge - combines the matched CSV record and the next record(s) into one+ record (described below).++ Some examples:++ # if the record contains "groceries", set account2 to "expenses:groceries"+ if groceries+ account2 expenses:groceries++ # if the record contains any of these phrases, set account2 and a transaction comment as shown+ if+ monthly service fee+ atm transaction fee+ banking thru software+ account2 expenses:business:banking+ comment XXX deductible ? check it++ Matchers+ There are two kinds of matcher:++ 1. A whole record matcher is simplest: it is just a word, single-line text+ fragment, or other regular expression, which hledger will try to match+ case-insensitively anywhere within the CSV record.+ Eg: whole foods.++ 2. A field matcher has a percent-prefixed CSV field number or name before+ the pattern.+ Eg: %3 whole foods or %description whole foods.+ hledger will try to match the pattern just within the named CSV field. (In+ records combined by a merge rule, a _ROWNUM suffix selects a later row's+ field, eg %description_2.)++ When using these, there's two things to be aware of:++ 1. Whole record matchers don't see the exact original record; they see a+ reconstruction of it, in which values are comma-separated, and quotes+ enclosing values and whitespace outside those quotes are removed.+ Eg when reading an SSV record like: 2023-01-01 ; "Acme, Inc. " ; 1,000+ the whole record matcher sees instead: 2023-01-01,Acme, Inc. ,1,000++ 2. Field matchers expect either a CSV field number, or a CSV field name de-+ clared with fields. Anything else will cause it to match against the+ empty string, and probably fail silently (this makes it easier to reuse+ common rules with different CSV files). Don't use a hledger field name+ here (see CSV fields and hledger fields).++ You can also prefix a matcher line with ! to negate it (at the start of the+ line; you can't negate individual terms within the line). Eg ! whole+ foods, ! %3 whole foods, !%description whole foods will match if "whole+ foods" is NOT present.++ The pattern is, as usual in hledger, a POSIX extended regular expression+ that also supports GNU word boundaries (\b, \B, \<, \>) and nothing else.+ For more details and tips, see Regular expressions in CSV rules below.++ Multiple matchers+ When an if rule has multiple matchers, each on its own line,++ * By default they are OR'd (any of them can match).++ * Matcher lines beginning with & (or &&) are AND'ed with the matcher above+ (all in the AND'ed group must match).++ * Matcher lines beginning with & ! (or && !) are first negated and then+ AND'ed with the matcher above.++ You can also combine multiple matchers on the same line separated by &&+ (AND) or && ! (AND NOT). Eg %description amazon && %date 2025-01-01 will+ match only when the description field contains "amazon" and the date field+ contains "2025-01-01".++ Match groups+ Matchers can define match groups: parenthesised portions of the regular ex-+ pression which are available for reference in field assignments. Groups+ are enclosed in regular parentheses (( and )) and can be nested. Each+ group is available in field assignments using the token \N, where N is an+ index into the match groups for this if rule (e.g. \1, \2, etc.).++ Example: Warp credit card payment postings to the beginning of the billing+ period (Month start), to match how they are presented in statements, using+ posting dates:++ if %date (....-..)-..+ comment2 date:\1-01++ Another example: Read the expense account from the CSV field, but throw+ away a prefix:++ if %account1 liabilities:family:(expenses:.*)+ account1 \1++ Regular expressions in CSV rules+ Regular expressions in if conditions (AKA matchers) are POSIX extended reg-+ ular expressions, that also support GNU word boundaries (\b, \B, \<, \>),+ and nothing else. (For more detail, see Regular expressions.)++ Here are some examples that might be useful in CSV rules:++ * Is field "foo" truly empty ? if %foo ^$++ * Is it empty or containing only whitespace ? if %foo ^ *$++ * Is it non-empty ? if %foo .++ * Does it contain non-whitespace ? if %foo [^ ]++ Testing the value of numeric fields is a little harder. You can't use+ hledger queries like amt:0 or amt:>10 in CSV rules. But you can often+ achieve the same thing with a regular expression.++ Note the content and layout of number fields in CSV varies, and can change+ over time (eg if you switch data providers). So numeric regexps are always+ somewhat specific to your particular CSV data; and it's a good idea to make+ them defensive and robust if you can.++ Here are some examples:++ * Does foo contain a non-zero number ? if %foo [1-9]++ * Is it negative ? if %foo -++ * Is it non-negative ? if ! %foo -++ * Is it >= 10 ? if %foo [1-9][0-9]+\. (assuming a decimal period and no+ leading zeros)++ * Is it >= 10 and < 20 ? if %foo \b1[0-9]\.++ ifs+ An "ifs table" is a more compact way to write many if rules.++ * The first line begins with ifs, then one or more hledger field names, all+ separated by a delimiter character (any punctuation character, your+ choice) plus optional whitespace. (An older form is also supported for+ backward compatibility: if followed by the delimiter with no space be-+ tween them.)++ * The following lines begin with a matcher, then values to assign to each+ of those hledger fields.++ * Comment lines, beginning with ; or # (optionally indented), are also al-+ lowed.++ * A blank line (or the end of the file) ends the table.++ Eg:++ ifs | HLEDGERFIELD1 | HLEDGERFIELD2 | ...+ MATCHER | VALUE | VALUE | ...+ MATCHER | VALUE | VALUE | ...+ MATCHER | VALUE | VALUE | ...+ <empty line>++ This means: for each line in turn, if the matcher matches the current CSV+ record, assign all of the non-blank values on that line, without their sur-+ rounding whitespace, to the corresponding hledger fields. All of the lines+ are processed, so later lines may override earlier ones. Except for the+ blank/whitespace handling, it's equivalent to writing these if rules:++ if MATCHER+ HLEDGERFIELD1 VALUE+ HLEDGERFIELD2 VALUE+ ...++ if MATCHER+ HLEDGERFIELD1 VALUE+ HLEDGERFIELD2 VALUE+ ...++ if MATCHER+ HLEDGERFIELD1 VALUE+ HLEDGERFIELD2 VALUE+ ...++ Because every matching row is applied in order, the last one that matches+ wins. To supply a default, set the field before the table (or put a+ catch-all matcher such as .* as the first row); later, more-specific rows+ will override it when they match.++ account2 expenses:unknown++ ifs | account2+ WHOLE FOODS | expenses:food+ WHOLE FOODS.*organic | expenses:food:organic++ In this example a transaction whose description contains "WHOLE FOODS or-+ ganic" matches both WHOLE FOODS rows; the last assignment is the one that+ remains.++ The skip, end and merge actions can also be table columns. Write a number+ in the cell on lines where the action should happen, and leave it blank on+ other lines. For skip and merge the number is how many records to skip or+ merge (1 or more); for end, write 1 (any non-blank value will end). Eg:++ ifs | account2 | skip+ atm withdrawal fee | expenses:banking |+ transfer to savings | | 1++ The delimiter must appear the same number of times in each line of the ta-+ ble, and it must not appear in the field names, matchers, or values used in+ the table (though inside %{...} expressions is ok). You cannot escape it+ with a backslash.++ Note, the delimiter in an ifs table is unrelated to the one used in the+ data file (consider avoiding , or ;, because they look confusing).++ In fact, it's hard to find a delimiter character that never clashes with+ anything, so the flexibility can be useful. Some examples:++ # | as delimiter; can use a leading !, can't use regex | operator+ ifs | account2 | comment+ ! %amount [0-9][0-9]+\. | expenses:misc |+ %desc amazon | expenses:shopping |+ %desc amzn | expenses:shopping |+ %amount [0-9]{4,} | | TODO: large amount, check it++ # ! as delimiter; can't use leading !, can use regex |+ ifs ! account2+ %desc amazon|amzn ! expenses:shopping++ # ` as delimiter; can use both leading ! and regex |+ ifs ` account2+ ! %amount [0-9][0-9]+\. ` expenses:misc+ %desc amazon|amzn ` expenses:shopping++ end+ The word end, used inside an if or ifs rule, tells hledger to skip the cur-+ rent record and remaining records in the current CSV file, whenever the+ condition is true. Eg:++ # if an empty record is seen (assuming five fields), ignore the rest of the CSV file+ if ,,,,+ end++ merge+ if MATCHER+ merge N++ Some banks and brokers export a single transaction as multiple CSV records+ - eg a currency conversion or stock trade, with each side of the trade on+ its own row. The merge rule combines such related records, so that they+ can generate a single journal transaction.++ When a record matches an if rule containing merge N (the word merge fol-+ lowed by a number, or no number, meaning 1), the next N records are joined+ onto the matched record, forming a group of rows. Conversion then proceeds+ as usual, with the whole group generating one transaction.++ Fields of the later rows are referenced by adding a _ROWNUM suffix (row+ number 2 or greater) to the usual field name or number: %amt_2 or %4_2 is+ row 2's amt/fourth field. Unsuffixed references (%amt, %4) always mean the+ first row, so the same fields list describes every row. A reference to a+ row that isn't there (eg in an unmerged record) just has an empty value.+ And if you have declared a field name that looks like NAME_ROWNUM, it keeps+ its declared meaning; the suffix interpretation is only a fallback.++ For example, to convert this two-row currency conversion:++ 2026-09-01,PAYMENT,coffee,-3.50,USD+ 2026-09-02,CONVERT,converted USD to EUR,-100.00,USD+ 2026-09-02,CONVERT,converted USD to EUR,90.00,EUR++ fields date, type, desc, amt, cur+ description %desc+ account1 assets:bank:%cur+ amount1 %amt %cur++ # a conversion's second row holds the amount received; make it posting 2+ if %type CONVERT+ merge+ account2 assets:bank:%cur_2+ amount2 %amt_2 %cur_2++ if %type PAYMENT+ account2 expenses:unknown++ $ hledger print -f conversion.csv+ 2026-09-01 coffee+ assets:bank:USD -3.50 USD+ expenses:unknown++ 2026-09-02 converted USD to EUR+ assets:bank:USD -100.00 USD+ assets:bank:EUR 90.00 EUR++ Things to note:++ * merge can also be used as a top-level rule (unconditionally), useful for+ files where every transaction is exactly N+1 rows.++ * skip and end rules are applied before row merging - skipped records don't+ count toward a merge group.++ * The rows of a group must be consecutive in the file (ignoring skipped+ records), and the merging record must be the first of them.++ * Matchers which (if successful) will trigger a merge rule, can only use-+ fully reference the first row's fields - the other row fields will be+ empty at this stage.++ * But once a merge rule has been evaluated, later if rules can see the+ whole group; eg a whole-record matcher will see all of its rows combined+ as one, and field matchers can use %FIELD_ROWNUM references.++ * If fewer than N records remain in the file, just those are merged.++ include+ include RULESFILE++ This includes the contents of another CSV rules file at this point. RULES-+ FILE is an absolute file path or a path relative to the current file's di-+ rectory. This can be useful for sharing common rules between several rules+ files, eg:++ # someaccount.csv.rules++ ## someaccount-specific rules+ fields date,description,amount+ account1 assets:someaccount+ account2 expenses:misc++ ## common rules+ include categorisation.rules++ Since included rules are effectively inlined, and since for most rules the+ last declaration wins, you can override an included file's rules by writing+ rules after the include line.++ Working with CSV+ Some tips for creating rules and importing CSV data regularly:++ CSV rules examples+ For real-world rules files for many banks, brokers, exchanges and apps, see+ the hledger CSV rules library in the hledger repo. These aren't necessar-+ ily maintained, and may need adapting, but they are a good source of ideas+ and examples.++ Rapid feedback+ It's a good idea to get rapid feedback while creating/troubleshooting CSV+ rules. Here's a good way, using entr from eradman.com/entrproject:++ $ ls foo.csv* | entr bash -c 'echo ----; hledger -f foo.csv print desc:SOMEDESC'++ A desc: query (eg) is used to select just one, or a few, transactions of+ interest. "bash -c" is used to run multiple commands, so we can echo a+ separator each time the command re-runs, making it easier to read the out-+ put.++ Well factored rules+ Some things that can help reduce duplication and complexity in rules files:++ * Extracting common rules usable with multiple CSV files into a com-+ mon.rules, and adding include common.rules to each CSV's rules file.++ * Splitting if rules into smaller if rules, extracting the frequently used+ parts.++ Deduplicating, importing+ When you download a CSV file periodically, eg to get your latest bank+ transactions, the new file may overlap with the old one, containing some of+ the same records.++ The import command will (a) detect the new transactions, and (b) append+ just those transactions to your main journal. It is idempotent, so you+ don't have to remember how many times you ran it or with which version of+ the CSV. (It keeps state in a hidden .latest.FILE.csv file.) This is the+ easiest way to import CSV data. Eg:++ # download the latest CSV files, then run this command.+ # Note, no -f flags needed here.+ $ hledger import *.csv [--dry]++ This method works for most CSV files. (Where records have a stable chrono-+ logical order, and new records appear only at the new end.)++ A number of other tools and workflows, hledger-specific and otherwise, ex-+ ist for converting, deduplicating, classifying and managing CSV data. See:++ * https://hledger.org/workflows.html#comparing-csv-workflows++ * https://hledger.org/doc.html#setups-and-workflows++ * https://plaintextaccounting.org -> data import/conversion++ Valid transactions+ After reading a CSV file, hledger post-processes and validates the gener-+ ated journal entries as it would for a journal file - balancing them, ap-+ plying balance assignments, and canonicalising amount styles. Any errors+ at this stage will be reported in the usual way, displaying the problem en-+ try.++ There is one exception: balance assertions, if you have generated them,+ will not be checked, since normally these will work only when the CSV data+ is part of the main journal. If you do need to check balance assertions+ generated from CSV right away, pipe into another hledger:++ $ hledger -f file.csv print | hledger -f- print++ How CSV rules are evaluated+ Here's how to think of CSV rules being evaluated. If you get a confusing+ error while reading a CSV file, it may help to try to understand which of+ these steps is failing:++ 1. Any included rules files are inlined, from top to bottom, depth first+ (scanning each included file for further includes, recursively, before+ proceeding).++ 2. Top level rules (date-format, fields, newest-first, skip etc) are read,+ top to bottom. "Top level rules" means non-conditional rules. If a+ rule occurs more than once, the last one wins; except for the skip rule,+ where the first one wins, and the source rule, which may occur only+ once. A rule written after an include would override the same rule in+ the included file.++ 3. The CSV file is read as text. Any non-ascii characters will be decoded+ using the text encoding specified by the encoding rule, otherwise the+ system locale's text encoding.++ 4. Any top-level skip or end rule is applied. skip [N] immediately skips+ the current or next N CSV records; end immediately skips all remaining+ CSV records (not normally used at top level).++ 5. Now any remaining CSV records are processed. For each CSV record, in+ file order:++ * Is there a conditional skip/end rule that applies for this record ?+ Search the if rules, from top to bottom, for a succeeding one con-+ taining a skip or end rule. If found, skip the specified number of+ CSV records, then continue at 5.+ Otherwise...++ * Is there a merge rule that applies for this record (top level or con-+ ditional) ? If so, join the next N CSV records onto this record,+ making one combined record.++ * Do some basic validation on this CSV record (eg, check that it has at+ least two fields).++ * For each hledger field (date, description, account1, etc.):++ 1. Get the field's assigned value, first searching top level assign-+ ments, made directly or by the fields rule, then assignments made+ inside succeeding if rules. If there are more than one, the last+ one wins (though it can include the previous one's value with+ %{FIELDNAME}).++ 2. Compute the field's actual value (as text), by interpolating any+ %CSVFIELD references and %{...} expressions within the assigned+ value (which may use other hledger fields' values, computing them+ first); or by choosing a default value if there was no assignment.++ * Generate a hledger transaction from the hledger field values, parsing+ them if needed (eg from text to an amount).++ This is all done by the CSV reader, one of several readers hledger can use+ to read transactions from an input file. When all input files have been+ read successfully, their transactions are passed to whichever hledger com-+ mand the user specified.++Timeclock+ hledger can read time logs in the timeclock time logging format of time-+ clock.el. As with Ledger, hledger's timeclock format is a subset/variant+ of timeclock.el's.++ hledger's timeclock format was updated in hledger 1.43 and 1.50. If your+ old time logs are rejected, you should adapt them to modern hledger; for+ now, you can restore the pre-1.43 behaviour with the --old-timeclock flag.++ Here is the timeclock format (in hledger 1.50+):++ # Comment lines like these, and blank lines, are ignored:+ # comment line+ ; comment line+ * comment line++ # Lines beginning with b, h, or capital O are also ignored, for compatibility:+ b SIMPLEDATE HH:MM[:SS][+-ZZZZ][ TEXT]+ h SIMPLEDATE HH:MM[:SS][+-ZZZZ][ TEXT]+ O SIMPLEDATE HH:MM[:SS][+-ZZZZ][ TEXT]++ # Lines beginning with i or o are are clock-in / clock-out entries:+ i SIMPLEDATE HH:MM[:SS][+-ZZZZ] ACCOUNT[ DESCRIPTION][;COMMENT]]+ o SIMPLEDATE HH:MM[:SS][+-ZZZZ][ ACCOUNT][;COMMENT]++ The date is a hledger simple date (YYYY-MM-DD or similar). The time parts+ must use two digits. The seconds are optional. A + or - four-digit time+ zone is accepted for compatibility, but currently ignored; times are always+ interpreted as a local time.++ In clock-in entries (i), the account name is required. A transaction de-+ scription, separated from the account name by 2+ spaces, is optional. A+ transaction comment, beginning with ;, is also optional. (Indented follow-+ ing comment lines are also allowed, as in journal format.)++ Clock-out entries (o) have no description, but can have a comment if you+ wish. A clock-in and clock-out pair form a "transaction" posting some num-+ ber of hours to an account - also known as a session. Eg:++ i 2015/03/30 09:00:00 session1+ o 2015/03/30 10:00:00++ $ hledger -f a.timeclock print+ 2015-03-30 * 09:00-10:00+ (session1) 1.00h++ Clock-ins and clock-outs are matched by their account/session name. If a+ clock-out does not specify a name, the most recent unclosed clock-in is+ closed. You can have multiple sessions active simultaneously. Entries are+ processed in the order they are parsed. Sessions spanning more than one+ day are automatically split at day boundaries.++ Eg, the following time log:++ i 2015/03/30 09:00:00 some account optional description after 2 spaces ; optional comment, tags:+ o 2015/03/30 09:20:00+ i 2015/03/31 22:21:45 another:account+ o 2015/04/01 02:00:34+ i 2015/04/02 12:00:00 another:account ; this demonstrates multiple sessions being clocked in+ i 2015/04/02 13:00:00 some account+ o 2015/04/02 14:00:00+ o 2015/04/02 15:00:00 another:account++ generates these transactions:++ $ hledger -f t.timeclock print+ 2015-03-30 * optional description after 2 spaces ; optional comment, tags:+ (some account) 0.33333333h++ 2015-03-31 * 22:21-23:59+ (another:account) 1.6375h++ 2015-04-01 * 00:00-02:00+ (another:account) 2.00944444h++ 2015-04-02 * 12:00-15:00 ; this demonstrates multiple sessions being clocked in+ (another:account) 3.00h++ 2015-04-02 * 13:00-14:00+ (some account) 1.00h++ Here is a sample.timeclock to download and some queries to try:++ $ hledger -f sample.timeclock balance # current time balances+ $ hledger -f sample.timeclock register -p 2009/3 # sessions in march 2009+ $ hledger -f sample.timeclock register -p weekly --depth 1 --empty # time summary by week++ To generate time logs, ie to clock in and clock out, you could:++ * use these shell aliases at the command line:++ alias ti='echo i `date "+%Y-%m-%d %H:%M:%S"` $* >>$TIMELOG'+ alias to='echo o `date "+%Y-%m-%d %H:%M:%S"` >>$TIMELOG'++ * or Emacs's built-in timeclock.el, or the extended timeclock-x.el, and+ perhaps the extras in ledgerutils.el++ * or use the old ti and to scripts in the ledger 2.x repository. These+ rely on a "timeclock" executable which I think is just the ledger 2 exe-+ cutable renamed.++Timedot+ timedot format is hledger's human-friendly time logging format. Compared+ to timeclock format, it is more convenient for quick, approximate, and+ retroactive time logging, and more human-readable (you can see at a glance+ where time was spent). A quick example:++ 2023-05-01+ hom:errands .... .... ; two hours; the space is ignored+ fos:hledger:timedot .. ; half an hour+ per:admin:finance ; no time spent yet++ hledger reads this as a transaction on this day with three (unbalanced)+ postings, where each dot represents 0.25 (of an hour, we usually assume).++ $ hledger -f a.timedot print # .timedot file extension (or timedot: prefix) is required+ 2023-05-01 *+ (hom:errands) 2.00 ; two hours; the space is ignored+ (fos:hledger:timedot) 0.50 ; half an hour+ (per:admin:finance) 0.00 ; no time spent yet++ A timedot file specifies a series of transactions, usually one per day.+ (Unlike in a journal file, these "transactions" don't need to balance; time+ logs use "single entry accounting".)++ Each transaction begins with a date line: a line whose first word looks+ like a simple date, ie three groups of digits separated by -, /, or . (if+ these cannot be parsed as a valid date, an error is raised). After the+ date, on the same line, there can optionally be a transaction description,+ and after ;, a transaction comment (possibly containing tags).++ After the date line are zero or more posting lines. A timedot posting line+ begins with a hledger-style account name, optionally indented. After the+ account name there are two or more spaces and then a timedot amount. (Or+ nothing, which is equivalent to a zero amount.)++ Timedot amounts can be written in several ways:++ * One or more dots (.)+ Each dot represents a quarter hour. (There's no commodity symbol, but usu-+ ally we assume hours.) Spaces can optionally be used for aligning or+ grouping dots, eg .... .... .. is easy to read as 2.5 hours.++ * A bare number (integer or decimal)+ This can be more precise or more convenient, eg for large durations.++ * A number followed by a time unit (s, m, h, d, w, mo, or y)+ representing seconds, minutes, hours, days, weeks, months or years, which+ will be converted to hours using these ratios: 60s = 1m, 60m = 1h, 24h =+ 1d, 7d = 1w, 30d = 1mo, 365d = 1y. This allows use of more convenient time+ units.++ * One or more timedot letters+ These work like dots, except they also generate a posting tag t: (short for+ "type") with the letter as its value, and a separate posting for each of+ the letter values. This adds a second dimension of categorisation - in ad-+ dition to account name, you'll have the t tag's value, which can be shown+ in reports with --pivot t, --pivot acct:t, etc.++ Posting lines can end with a hledger-style posting comment (text after ;),+ optionally containing tags.++ Lines beginning with # or ; are comment lines, and ignored. Blank lines+ are also ignored.++ There is some additional support for users of Emacs org mode:++ * Before the first date line, lines beginning with * are also treated as+ comments, and ignored. This allows top-level org headings in a timedot+ file.++ * From the first date line onward, org heading prefixes (one or more *'s+ followed by a space) are ignored, with the rest of the line being parsed+ normally. This allows timedot date or posting lines to also be org head-+ ings.++ Timedot files don't support directives like journal files. So a common+ pattern is to have a main journal file that contains any needed directives,+ and then includes the timedot file (include time.timedot).++ Timedot examples+ Numbers:++ 2016/2/3+ inc:client1 4+ fos:hledger 3h+ biz:research 60m++ Dots:++ # on this day, 6h was spent on client work, 1.5h on haskell FOSS work, etc.+ 2016/2/1+ inc:client1 .... .... .... .... .... ....+ fos:haskell .... ..+ biz:research .++ 2016/2/2+ inc:client1 .... ....+ biz:research .++ $ hledger -f a.timedot print date:2016/2/2+ 2016-02-02 *+ (inc:client1) 2.00+ (biz:research) 0.25++ $ hledger -f a.timedot bal --daily+ Balance changes in 2016-02-01..2016-02-02:++ || 2016-02-01 2016-02-02+ ==============++========================+ biz:research || 0.25 0.25+ fos:haskell || 1.50 0+ inc:client1 || 6.00 2.00+ --------------++------------------------+ || 7.75 2.25++ Letters:++ # Activity types:+ # c cleanup/catchup/repair+ # e enhancement+ # s support+ # l learning/research++ 2023-11-01+ work:adm ccecces++ $ hledger -f a.timedot print+ 2023-11-01 *+ (work:adm) 1.00 ; t:c+ (work:adm) 0.50 ; t:e+ (work:adm) 0.25 ; t:s++ $ hledger -f a.timedot bal+ 1.75 work:adm+ --------------------+ 1.75++ $ hledger -f a.timedot bal --pivot t+ 1.00 c+ 0.50 e+ 0.25 s+ --------------------+ 1.75++ Org:++ * 2023 Work Diary+ ** Q1+ *** 2023-02-28+ **** DONE+ yoga ....+ **** BEGUN+ hom:chores+ cleaning ...+ water plants+ outdoor - one full watering can+ indoor - light watering+ **** TODO+ adm:planning:trip+ *** LATER++ Using . as account name separator:++ 2016/2/4+ fos.hledger.timedot 4h+ fos.ledger ..++ $ hledger -f a.timedot --alias '/\./=:' bal -t+ 4.50 fos+ 4.00 hledger:timedot+ 0.50 ledger+ --------------------+ 4.50++PART 4: CONCEPTS+Time periods+ Report start & end date+ Most hledger reports will by default show the full time period represented+ by the journal. The report start date will be the earliest transaction or+ posting date, and the report end date will be the latest transaction, post-+ ing, or market price date.++ Often you will want to see a shorter period, such as the current month.+ You can specify a start and/or end date with the -b/--begin, -e/--end, or+ -p/--period options, or a date: query argument, described below. All of+ these accept the smart date syntax, also described below.++ End dates are exclusive; specify the day after the last day you want to see+ in the report.++ When dates are specified by multiple options, the last (right-most) option+ wins. And when date: queries and date options are combined, the report pe-+ riod will be their intersection.++ Examples:++ -b 2016/3/17+ beginning on St. Patrick's day 2016++ -e 12/1+ ending at the start of December 1st in the current year++ -p 'this month'+ during the current month++ -p thismonth+ same as above, spaces are optional++ -b 2023+ beginning on the first day of 2023++ date:2023.. or date:2023-+ same as above++ -b 2024 -e 2025 -p '2000 to 2030' date:2020-01 date:2020 :+ during January 2020 (the smallest common period, with the -p overriding -b+ and -e)++ Smart dates+ In hledger's user interfaces (though not in the journal file), you can op-+ tionally use "smart date" syntax. Smart dates can be written with english+ words, can be relative, and can have parts omitted. Missing parts are in-+ ferred as 1, when needed. Smart dates can be interpreted as dates or peri-+ ods depending on the context.++ Examples:++ 2004-01-01, 2004/10/1, 2004.9.1, 20240504, 2024Q1 :+ Exact dates. The year must have at least four digits, the month must be+ 1-12, the day must be 1-31, the separator can be - or / or . or nothing.+ The q can be upper or lower case and the quarter number must be 1-4.++ 2004-10+ start of month++ 2004q3+ start of third quarter of 2004++ q3 start of third quarter of current year++ 2004 start of year++ 10/1 or oct or october+ October 1st in current year++ 21 21st day in current month++ yesterday, today, tomorrow+ -1, 0, 1 days from today++ last/this/next day/week/month/quarter/year+ -1, 0, 1 periods from the current period++ last/this/next tuesday+ the previous occurrence of the named day, or the next occurrence af-+ ter today++ last/this/next february+ the previous occurrence of 1st of the named month, or the next oc-+ currence after the current month++ in n days/weeks/months/quarters/years+ n periods from the current period++ n days/weeks/months/quarters/years ahead+ n periods from the current period++ n days/weeks/months/quarters/years ago+ -n periods from the current period++ 20181201+ 8 digit YYYYMMDD with valid year month and day++ 201812+ 6 digit YYYYMM with valid year and month++ Dates with no separators are allowed but might give surprising results if+ mistyped:++ * 20181301 (YYYYMMDD with an invalid month) is parsed as an eight-digit+ year++ * 20181232 (YYYYMMDD with an invalid day) gives a parse error++ * 201801012 (a valid YYYYMMDD followed by additional digits) gives a parse+ error++ The meaning of relative dates depends on today's date. If you need to test+ or reproduce old reports, you can use the --today option to override that.+ (Except for periodic transaction rules, which are not affected by --today.)++ Report intervals+ A report interval can be specified so that reports like register, balance+ or activity become multi-period, showing each subperiod as a separate row+ or column.++ The following standard intervals can be enabled with command-line flags:++ * -D/--daily++ * -W/--weekly++ * -M/--monthly++ * -Q/--quarterly++ * -Y/--yearly++ More complex intervals can be specified using -p/--period, described below.++ Date adjustments+ Start date adjustment+ If you let hledger infer a report's start date, it will adjust the date to+ the previous natural boundary of the report interval, for convenient peri-+ odic reports. (If you don't want that, specify a start date.)++ For example, if the journal's first transaction is on january 10th,++ * hledger register (no report interval) will start the report on january+ 10th.++ * hledger register --monthly will start the report on the previous month+ boundary, january 1st.++ * hledger register --monthly --begin 1/5 will start the report on january+ 5th [1].++ The start date of transactions generated by periodic transaction rules is+ chosen separately; see Forecast period, in detail.++ End date adjustment+ A report's end date is always adjusted to include a whole number of inter-+ vals, so that the last subperiod has the same length as the others.++ For example, if the journal's last transaction is on february 20th,++ * hledger register will end the report on february 20th.++ * hledger register --monthly will end the report at the end of february.++ * hledger register --monthly --end 2/14 also will end the report at the end+ of february (overriding the requested end date).++ * hledger register --monthly --begin 1/5 --end 2/14 will end the report on+ march 4th.++ Period expressions+ The -p/--period option specifies a period expression, which is a compact+ way of expressing a start date, end date, and/or report interval.++ Here's a period expression with a start and end date (specifying the first+ quarter of 2009):++ -p "from 2009/1/1 to 2009/4/1"++ Several keywords like "from" and "to" are supported for readability; these+ are optional. "to" can also be written as ".." or "-". (Except that a+ lone day number, directly after a "-" with no spaces, is not accepted; eg+ 2026-13 is more likely a mistyped date than "2026 to the 13th of this+ month", so it's an error. To mean the latter, write 2026..13.) The spaces+ are also optional, as long as you don't run two dates together. So the+ following are equivalent to the above:++ -p "2009/1/1 2009/4/1"+ -p2009/1/1to2009/4/1+ -p2009/1/1..2009/4/1++ Dates are smart dates, so if the current year is 2009, these are also+ equivalent to the above:++ -p "1/1 4/1"+ -p "jan-apr"+ -p "this year to 4/1"++ If you specify only one date, the missing start or end date will be the+ earliest or latest transaction date in the journal:++ -p "from 2009/1/1" everything after january 1,+ 2009+ -p "since 2009/1" the same, since is a syn-+ onym+ -p "from 2009" the same+ -p "to 2009" everything before january+ 1, 2009++ You can also specify a period by writing a single partial or full date:++ -p "2009" the year 2009; equivalent to "2009/1/1 to 2010/1/1"+ -p "2009/1" the month of january 2009; equivalent to "2009/1/1 to+ 2009/2/1"+ -p "2009/1/1" the first day of 2009; equivalent to "2009/1/1 to+ 2009/1/2"++ or by using the "Q" quarter-year syntax (case insensitive):++ -p "2009Q1" first quarter of 2009, equivalent to "2009/1/1 to+ 2009/4/1"+ -p "q4" fourth quarter of the current year++ Period expressions with a report interval+ A period expression can also begin with a report interval, separated from+ the start/end dates (if any) by a space or the word in:++ -p "weekly from 2009/1/1 to 2009/4/1"+ -p "monthly in 2008"+ -p "quarterly"++ More complex report intervals+ Some more complex intervals can be specified within period expressions,+ such as:++ * biweekly (every two weeks)++ * fortnightly++ * bimonthly (every two months)++ * every day|week|month|quarter|year++ * every N days|weeks|months|quarters|years++ Weekly on a custom day:++ * every Nth day of week (th, nd, rd, or st are all accepted after the num-+ ber)++ * every WEEKDAYNAME (full or three-letter english weekday name, case insen-+ sitive)++ Monthly on a custom day:++ * every Nth day [of month] (31st day will be adjusted to each month's last+ day)++ * every Nth WEEKDAYNAME [of month]++ Yearly on a custom month and day:++ * every MM/DD [of year] (month number and day of month number)++ * every MONTHNAME DDth [of year] (full or three-letter english month name,+ case insensitive, and day of month number)++ * every DDth MONTHNAME [of year] (equivalent to the above)++ Examples:++ -p "bimonthly from 2008"+ -p "every 2 weeks"+ -p "every 5 months from+ 2009/03"+ -p "every 2nd day of week" periods will go from Tue to Tue+ -p "every Tue" same+ -p "every 15th day" period boundaries will be on 15th of each+ month+ -p "every 2nd Monday" period boundaries will be on second Monday+ of each month+ -p "every 11/05" yearly periods with boundaries on 5th of+ November+ -p "every 5th November" same+ -p "every Nov 5th" same++ Show historical balances at end of the 15th day of each month (N is an end+ date, exclusive as always):++ $ hledger balance -H -p "every 16th day"++ Group postings from the start of wednesday to end of the following tuesday+ (N is both (inclusive) start date and (exclusive) end date):++ $ hledger register checking -p "every 3rd day of week"++ Multiple weekday intervals+ This special form is also supported:++ * every WEEKDAYNAME,WEEKDAYNAME,... (full or three-letter english weekday+ names, case insensitive)++ Also, weekday and weekendday are shorthand for mon,tue,wed,thu,fri and+ sat,sun.++ This is mainly intended for use with --forecast, to generate periodic+ transactions on arbitrary days of the week. It may be less useful with -p,+ since it divides each week into subperiods of unequal length, which is un-+ usual. (Related: #1632)++ Examples:++ -p "every dates will be Mon, Wed, Fri; periods will be+ mon,wed,fri" Mon-Tue, Wed-Thu, Fri-Sun+ -p "every weekday" dates will be Mon, Tue, Wed, Thu, Fri; periods will+ be Mon, Tue, Wed, Thu, Fri-Sun+ -p "every weekend- dates will be Sat, Sun; periods will be Sat, Sun-Fri+ day"++Queries+ Many hledger commands accept query arguments, which restrict their scope+ and let you report on a precise subset of your data. Here's a quick+ overview of hledger's queries:++ * By default, a query argument is treated as a case-insensitive substring+ pattern for matching account names. Eg:++ dining groceries+ car:fuel++ * Patterns containing spaces or other special characters must be enclosed+ in single or double quotes:++ 'personal care'++ * Patterns are actually regular expressions, so you can add regexp+ metacharacters for more precision (or you may need to backslash-escape+ certain characters; see "Regular expressions" above):++ '^expenses\b'+ 'food$'+ 'fuel|repair'+ 'accounts (payable|receivable)'++ * To match something other than the account name, you can add a query type+ prefix, such as:++ date:202312-+ status:+ desc:amazon+ cur:USD+ cur:\\$+ amt:'>0'+ change:'>100', balance:'<0' (match report rows or entries by their change+ or balance, see below)+ acct:groceries (but acct: is the default, so we usually don't bother+ writing it)++ * To match in any field, or by date, use the find: query type, or :: for+ short:++ ::amazon+ ::2024+ ::amazon ::2024 (both must match)++ * To negate a query, add a not: prefix:++ not:status:'*'+ not:desc:'opening|closing'+ not:cur:USD++ * Multiple query terms can be combined, as space-separated queries Eg:+ hledger print date:2022 desc:amazon desc:amzn (show transactions dated in+ 2022 whose description contains "amazon" or "amzn").++ * Or more flexibly as boolean queries. Eg: hledger print expr:'date:2022+ and (desc:amazon or desc:amzn) and not date:202210'++ All hledger commands use the same query language, but different commands+ may interpret the query in different ways. Here's the gist of it (see PART+ 2: COMMANDS above for the commands):++ * Transaction-oriented commands (print, aregister, close, import, descrip-+ tions..) try to match transactions (including the transaction's post-+ ings).++ * Posting-oriented commands (register, balance, balancesheet, incomestate-+ ment, accounts..) try to match postings. Postings inherit their trans-+ action's attributes for querying purposes, so transaction fields like+ date or description can still be referenced in a posting query.++ * A few commands match in more specific ways. (Eg aregister, which has a+ special first argument.)++ Query types+ Here are the query types available.++ In the ones which take a regular expression, an empty one (eg desc: or ::)+ matches anything. (Except in cur:, which must match the whole symbol, so+ an empty cur: matches amounts with no commodity symbol.)++ acct: query+ acct:REGEX, or just REGEX+ Match account names containing this case insensitive regular expression.+ This is the default query type, so we usually don't bother writing the+ "acct:" prefix.++ amt: query+ amt:N, amt:'<N', amt:'<=N', amt:'>N', amt:'>=N', optionally with a commod-+ ity symbol, eg amt:'>$100' or amt:'>100 EUR'+ Match postings with an amount equal to, less than, or greater than N. amt:+ needs quotes to hide the less than/greater than sign from the command line+ shell.++ The comparison has two modes: if N is preceded by a + or - sign (or is 0),+ the two signed numbers are compared. Otherwise, the absolute magnitudes+ are compared, ignoring sign.++ If N has a commodity symbol (before or after the number, quoted with " if+ needed), only amounts in that commodity are compared; a posting with none+ doesn't match. Otherwise, amounts in any commodity are compared. A post-+ ing whose amount has several commodities matches if any one of them does.++ Keep in mind that amt: matches posting amounts, not account balances. To+ match accounts, or periods, by their change or balance, use change: or bal-+ ance:.++ balance: and change: queries+ change:N, change:'<N', change:'<=N', change:'>N', change:'>=N', balance:N,+ balance:'<N', balance:'<=N', balance:'>N', balance:'>=N', optionally with a+ commodity symbol, eg change:'>$100' or balance:'<0 EUR'+ Match report rows (or entries) by their summed amounts: change: by the+ row's change, the sum of its postings; balance: by the row's balance, the+ sum of all its postings up to the end of its period. Unlike amt:, which+ tests each posting before postings are added up, these test the amounts a+ report shows after adding them up. Eg:++ $ hledger bal expenses change:'>100' # expense accounts which changed by more than 100+ $ hledger bal assets balance:'<0' # asset accounts with a negative balance+ $ hledger reg gifts -M change:'>100' # months with more than 100 in gift expenses+ $ hledger areg checking balance:'<0' # the transactions after which checking was overdrawn+ $ hledger print not:change:0 # entries with a tolerated imbalance or unbalanced virtual postings++ The comparison works as with amt:: signed if N has a + or - sign (or is 0),+ otherwise by absolute magnitude. Like amt:, these test amounts' real+ signs, not the signs they are displayed with (after --invert, or the sign+ normalisation in balancesheet, incomestatement etc.); so incomestatement+ change:'<-1000' finds the large revenues. If N has a commodity symbol,+ only that commodity's part of the amount is compared, and an amount with+ none of it doesn't match. An amount with several commodities matches if+ any one of them does.++ balance: always means the actual balance, from the start of the journal (or+ of the postings matched by the other query terms), whether or not the re-+ port is a historical (-H) one. So the amounts a report shows are not al-+ ways the ones tested; -H shows balances. A date span (date:2026, -p,+ -b/-e) sets the report period and does not limit the balance, as with -H.+ But query terms which exclude postings also exclude them from the balance;+ this includes not:date: and date terms combined with OR.++ What is tested depends on the kind of item being matched:++ * In balance reports (balance, balancesheet, incomestatement, etc.), each+ account's own change over the report period, or its own balance at the+ end of the report period, as shown in list mode (without or with -H). In+ a multi-period report, the change is the row's Total column, and the bal-+ ance is the last column's (with -H). Accounts which don't match are left+ out, as if excluded by an account query. So in tree mode, a parent ac-+ count is shown if it has matching subaccounts, with a balance including+ just those; and the report's totals and percentages include just the+ matching accounts. To test parent accounts' subaccount-inclusive amounts+ instead, limit the depth, eg bal -1 change:'>100'. An account matched by+ balance: is shown even if it had no postings in the report period.++ * In budget reports (balance --budget), rows are hidden if their actual+ change or balance (including subaccounts) doesn't match. The other rows,+ and the totals, are unchanged, since budget goals are often set on parent+ accounts.++ * In register, change: tests each posting's amount, or with a report inter-+ val, each period's amount; balance: tests the running total after it (the+ actual balance, even without -H).++ * In aregister, change: tests each transaction's change to the account;+ balance: tests the account's balance after it.++ * In print (and descriptions, notes and codes), both test each entry's sum+ of postings (an entry has no balance), converted to cost as in transac-+ tion balancing, including any unbalanced virtual postings. Since an en-+ try's real postings must balance, this will be zero, or a small tolerated+ imbalance, plus the amount of any unbalanced virtual postings. (To find+ large transactions, use amt: instead, eg print amt:'>1000'.)++ * In holdings, each line (one commodity in one account) has two amounts,+ its units and its market value. balance: tests the units, or with a com-+ modity symbol, whichever of them is in that commodity (so bal-+ ance:'>$1000' tests the value). change: likewise tests the change in+ units during the report period, or its value. Unlike in other reports,+ -V/-X don't change which amount is tested; to test the value, write its+ commodity symbol. With -B, the cost is tested instead of the value (eg+ holdings -B balance:'>$1000'). The totals cover just the lines shown,+ but Weight is still relative to all the holdings.++ * Other commands ignore these terms.++ In registers, hidden rows still count in the running total or balance,+ which is the account's real one. (Unlike amt:, which excludes the postings+ themselves, so they don't count.)++ change: and balance: can be combined with other query terms only by AND,+ and negated with not:. They can't be used inside OR, a negated group, any:+ or all:. As with other query terms which aren't OR'd, multiple terms must+ all match, so change:'>100' change:'<500' selects a range, and+ change:'>100' balance:'<0' requires both.++ code: query+ code:REGEX+ Match by transaction code (eg check number).++ cur: query+ cur:FULLREGEX+ Match postings or transactions including any amounts whose currency/commod-+ ity symbol is fully matched by REGEX. (Contrary to hledger's usual infix+ matching. To do infix matching, write .*REGEX.*.)++ To match special characters which are regex-significant, escape them with+ \. And at the command line, characters which are shell-significant need+ one more level of escaping - eg to match the dollar sign, write cur:\\$ or+ cur:'\$'.++ Amounts written with a commodity alias have been converted to the commod-+ ity, so cur: matches them by the commodity's symbol, not the alias.++ desc: query+ desc:REGEX+ Match transaction descriptions.++ date: query+ date:PERIODEXPR+ Match dates (or with the --date2 flag, secondary dates) within the speci-+ fied period. PERIODEXPR is a period expression. Examples:+ date:2016, date:thismonth, date:2/1-2/15, date:2021-07-27..nextquarter.++ PERIODEXPR may include a report interval (since 1.52). On the command+ line, this is equivalent to specifying a report interval with a command+ line option. In other contexts (hledger-ui, hledger-web), the report in-+ terval may be ignored.++ date2: query+ date2:PERIODEXPR+ If you use secondary dates: this matches secondary dates within the speci-+ fied period. It is not affected by the --date2 flag. A report interval in+ PERIODEXPR will be ignored.++ depth: query+ depth:[REGEXP=]N+ Match (or display, depending on command) accounts at or above this depth,+ optionally only for accounts matching a provided regular expression. See+ Depth for detailed rules.++ find: query+ find:REGEX, or ::REGEX+ Match if any text field contains this case insensitive regular expression:+ the account name, the amount (as it would be displayed), the comment, the+ transaction's description, code and comment, or the name or value of any+ tag. Tags include hidden tags and tags inherited from account and commod-+ ity declarations, so a match may come from a tag not shown in print output.+ Eg ::dispose finds lot disposals, which have a hidden ptype: dispose tag.+ To see why something matched, print --verbose-tags shows the hidden tags;+ for inherited tags, check the account or commodity directive. Or, if REGEX+ is also a valid period expression, match if the date is within that period.+ So ::amazon finds "amazon" anywhere, and ::2024 finds "2024" in any field+ or a date in 2024. Unlike date:, this does not set the report period.++ Multiple find: terms must all match, like the words of a search. Eg ::ama-+ zon ::2024 shows things matching both. (In a transaction-oriented command+ like print, the terms may be matched by different postings.) To match al-+ ternatives, use a regular expression: ::'amazon|amzn'.++ note: query+ note:REGEX+ Match transaction notes (the part of the description right of |, or the+ whole description if there's no |).++ payee: query+ payee:REGEX+ Match transaction payee/payer names (the part of the description left of |,+ or the whole description if there's no |).++ real: query+ real:, real:0+ Match real or virtual postings respectively.++ status: query+ status:, status:!, status:*+ Match unmarked, pending, or cleared transactions respectively.++ type: query+ type:TYPECODES+ Match by account type (see Declaring accounts > Account types). TYPECODES+ is one or more of the single-letter account type codes ALERXCVGUM, case in-+ sensitive. Note type:A, type:E, and type:R will also match their respec-+ tive subtypes C (Cash), V (Conversion), U (UnrealisedGain) and M (Imbal-+ ance), and G (Gain). Certain kinds of account alias can disrupt account+ types, see Rewriting accounts > Aliases and account types.++ tag: query+ tag:NAMEREGEX[=VALREGEX]+ Match by tag name, and optionally also by tag value. Note:++ * Both regular expressions do infix matching. If you need a complete+ match, use ^ and $.+ Eg: tag:'^fullname$', tag:'^fullname$=^fullvalue$++ * To match values, ignoring names, do tag:=VALREGEX++ * With an empty NAMEREGEX, tag: matches anything which has a tag, and+ not:tag: matches anything which has none.++ * With an empty VALREGEX, tag:NAMEREGEX= matches that tag with any value.++ * Accounts also inherit the tags of their parent accounts.++ * Postings also inherit the tags of their account and their transaction .++ * Transactions also acquire the tags of their postings.++ Negative queries+ not: query+ not:QUERY+ You can prepend not: to a query to negate the match.+ Eg: not:equity, not:desc:apple+ (Also, a trick: not:not:... can sometimes solve query problems conve-+ niently.)++ Space-separated queries+ When given multiple space-separated query terms, most commands select+ things which match:++ * any of the description terms AND++ * any of the account terms AND++ * any of the status terms AND++ * all the other terms.++ The print command is a little different, showing transactions which:++ * match any of the description terms AND++ * have any postings matching any of the positive account terms AND++ * have no postings matching any of the negative account terms AND++ * match all the other terms.++ Boolean queries+ For more complex needs, you can combine query terms with NOT, AND, OR oper-+ ators (case insensitive) and parentheses, writing the whole expression in+ quotes with one of three prefixes: expr:, any: or all:. Eg, to show trans-+ actions involving both cash and expense accounts:++ hledger print expr:'cash AND expenses'++ The prefix and the quotes are required. Two more things to know:++ * date: queries may not be used inside an OR expression (it could produce a+ report with disjoint or unclear report periods).++ * Space-separated terms can also appear inside a boolean query, combining+ as described in space-separated queries; but it's probably clearer to+ avoid mixing the two styles.++ expr: query+ expr:'QUERYEXPR'+ The general purpose boolean query. It can match transactions, postings,+ accounts, etc. depending on context. Eg, expr:'date:lastmonth AND NOT+ (food OR rent)' matches things dated in the last month, without food or+ rent in the account name.++ With transaction-oriented commands like print, posting-oriented terms like+ acct: and amt: match a transaction if they match any of its postings. So,+ hledger print expr:'cash AND amt:>0' shows transactions which have at least+ one cash posting and at least one positive-amount posting (these are not+ necessarily the same posting).++ any: query+ any:'QUERYEXPR'+ Matches a transaction, if at least one of its postings is matched by QUERY-+ EXPR. So, hledger print any:'cash AND amt:>0' shows transactions which+ have at least one posting that both involves a cash account and has a posi-+ tive amount.++ Unlike expr:, any: always considers whole transactions. So, hledger bal-+ ance expenses any:cash shows expenses from transactions involving cash, and+ hledger balance expenses not:any:cash shows expenses from transactions not+ involving cash.++ A query containing only any: (or all:) terms selects entire transactions,+ so its balance report will be zero-balanced, showing where the money in+ those transactions came from and went to. For the same reason, such a+ query combined with register's --related flag shows nothing: every posting+ is matched, so there are no unmatched related postings left to show.++ all: query+ all:'QUERYEXPR'+ Matches a transaction, if it has at least one posting and all of its post-+ ings are matched by QUERYEXPR. So, hledger print all:'cash OR checking'+ shows transactions touching only cash and/or checking accounts.++ Like any:, all: always considers whole transactions. So, hledger register+ all:'cash OR checking' shows the postings of transactions touching only+ cash and/or checking accounts - eg, transfers between those two. By con-+ trast, hledger register expr:'cash OR checking' tests each posting on its+ own, so it could also show, say, the cash posting of a grocery purchase.++ Queries and command options+ Some queries can also be expressed as command-line options: depth:2 is+ equivalent to --depth 2, date:2023 is equivalent to -p 2023, etc. When you+ mix command options and query arguments, generally the resulting query is+ their intersection.++ Queries and account aliases+ When account names are rewritten by account aliases, queries see only the+ new account names. Eg with alias checking = assets:bank:checking,+ acct:bank matches the rewritten postings, but acct:^checking does not.++ Queries and valuation+ When amounts are converted to other commodities in cost or value reports,+ cur: and amt: match the old commodity symbol and the old amount quantity,+ not the new ones. change: and balance: match the converted amounts, except+ in print (see balance: and change: queries). (With -B and no --lots, a+ sale from several lots may be left out by cur: or amt:, since it is matched+ as converted to cost; add --lots to match it as written.)++Depth+ With the --depth NUM option (short form, usually preferred: -NUM), reports+ will show accounts only to the specified depth, hiding deeper subaccounts.+ Use this when you want a summary with less detail. This flag has the same+ effect as a depth: query argument. So all of these are equivalent:+ depth:2, --depth=2, -2.++ You can also provide custom depths for specific accounts, by providing a+ REGEX=NUM argument instead of just NUM. For example, --depth assets=2 (or+ depth:assets=2) will collapse accounts matching the regular expression "as-+ sets" to depth 2. So assets:bank:savings would be collapsed to as-+ sets:bank, but liabilities:bank:credit card would not be affected.++ If REGEX contains spaces or other special characters, enclose it in quotes+ in the usual way. Eg: --depth 'credit card=2'++ Combining depth options+ If a command line contains multiple general depth options, the last one+ wins. (Useful for overriding a depth specified by scripts.)++ Or a command may contain a combination of general and custom depth options.+ In this case, the most specifically (deepest) matching option wins. Some+ examples:++ * --depth assets=3 --depth expenses=2 --depth 1 would collapse accounts+ containing "assets" to depth 3, accounts containing "expenses" to depth+ 2, and all other accounts to depth 1.++ * --depth assets=1 --depth savings=2 would collapse assets:bank:savings to+ depth 2 (not depth 1; because "savings" matches a deeper part of the ac-+ count name than "assets").++ Note currently, to override a custom depth option --depth REGEX=NUM with a+ later option, the later option must use the same REGEX.++Pivoting+ Normally, hledger groups amounts and displays their totals by account+ (name). With --pivot PIVOTEXPR, some other field's (or multiple fields')+ value is used as a synthetic account name, causing different grouping and+ display. PIVOTEXPR can be++ * any of these standard transaction or posting fields (their value is sub-+ stituted): status, code, desc/description, payee, note, acct/account,+ comm/cur, amt, cost++ * or a tag name++ * or any combination of these, colon-separated.++ Some special cases:++ * Colons appearing in PIVOTEXPR or in a pivoted tag value will generate ac-+ count hierarchy.++ * When pivoting a posting that has multiple values for a tag, the tag's+ first value will be used as the pivoted value.++ * When a posting has multiple commodities, the pivoted value of+ "comm"/"cur" will be "". Also when an unrecognised tag name or field is+ provided, its pivoted value will be "". (If this causes confusing out-+ put, consider excluding those postings from the report.)++ Examples:++ 2016/02/16 Yearly Dues Payment+ assets:bank account 2 EUR+ income:dues -2 EUR ; member: John Doe, kind: Lifetime++ Normal balance report showing account names:++ $ hledger balance+ 2 EUR assets:bank account+ -2 EUR income:dues+ --------------------+ 0++ Pivoted balance report, using member: tag values instead:++ $ hledger balance --pivot member+ 2 EUR+ -2 EUR John Doe+ --------------------+ 0++ One way to show only amounts with a member: value (using a query):++ $ hledger balance --pivot member tag:member=.+ -2 EUR John Doe+ --------------------+ -2 EUR++ Another way (the acct: query matches against the pivoted "account name"):++ $ hledger balance --pivot member acct:.+ -2 EUR John Doe+ --------------------+ -2 EUR++ Hierarchical reports can be generated with multiple pivot values:++ $ hledger balance Income:Dues --pivot kind:member+ -2 EUR Lifetime:John Doe+ --------------------+ -2 EUR++Report titles+ Some reports (aregister, balance (multi-period), balancesheet, bal-+ ancesheetequity, cashflow, holdings, incomestatement) are displayed with a+ title by default, and others are not. For most reports you can set a title+ with --title='Some Text', or suppress the title with --title=. Titles are+ shown in text and HTML output (and in some commands' CSV/TSV output). In+ HTML output the title is an <h3 class="report-title"> element, which you+ can style with a hledger.css file.++ Compound reports, like those just mentioned, also have subreport headings,+ like Assets and Liabilities in the balance sheet. You can customise these+ with --subreport-titles=HEADING1|HEADING2.., or suppress them with --subre-+ port-titles=.++ In both --title and --subreport-titles, you can use \n to generate a new-+ line.++ In multi-period reports each period has a heading describing its date range+ or end date. When date ranges correspond to natural period boundaries,+ they are described compactly by default. Eg: 2026, Q1, Jan, W02. (Month+ names follow the --lang option.) You can disable these compact descrip-+ tions by using --period-titles=dates; then periods will always be described+ as STARTDATE..ENDDATE.++Languages+ hledger's output is in English by default. Report titles, section head-+ ings, column headings, month names and similar structural text can be shown+ in another language with the --lang option (which can also be set in a con-+ fig file), when a translation catalog for that language is available.+ (This is hledger's localization support; it covers the language of+ hledger's own text, not number or date formats, which come from the jour-+ nal, as described below.)++ * --lang=LANG selects a language by its tag, like de or pt-BR. An unavail-+ able language is an error.++ * --lang=auto selects the language from the environment (the LANGUAGE,+ LC_ALL, LC_MESSAGES and LANG variables, see Environment), falling back to+ English.++ * --lang=en, or no --lang option, selects English.++ To always get German output, for example, put it in your config file's gen-+ eral options:++ # ~/.config/hledger/hledger.conf+ --lang de++ Currently Brazilian Portuguese (pt-BR), French (fr), German (de), Hawaiian+ (haw), Irish (ga), Italian (it), Japanese (ja), Russian (ru), Simplified+ Chinese (zh, also selected by zh_CN or zh-Hans), Spanish (es) and Ukrainian+ (uk) catalogs are built in. Catalogs are gettext PO files, which the usual+ translation tools can edit. hledger also looks for catalogs in the locale+ subdirectory of its config directory (~/.config/hledger/locale/LANG.po on+ unix, %APPDATA%\hledger\locale\LANG.po on windows), and merges a catalog+ found there over the built-in catalog for the same language, if any. So a+ translator can work on a new language with a released hledger, and a user+ can adjust terminology to taste. hledger --write-lang=LANG puts a catalog+ there to start from: a copy of the built-in catalog for that language, or+ for a new language, an untranslated one. (It won't overwrite a catalog+ that is already there.) Contributed catalogs are welcome, and no program-+ ming is needed: see Translating hledger in the developer docs.++ Only hledger's own structural text is translated. Your data (account+ names, descriptions, amounts) is never changed; dates keep their ISO for-+ mat, and numbers keep the display styles declared for each commodity. Er-+ ror messages, journal-format output, and the column headings of CSV, TSV+ and JSON output stay in English, since they are commonly read by other pro-+ grams. Report titles, however, are translated wherever they appear, as+ they would be with --title; and an explicit --title or --subreport-titles+ is always used as given, untranslated.++Amount arithmetic+ hledger uses decimal (Decimal) numbers for accounting arithmetic: amounts,+ balances, costs, prices, valuation and gains. Floating point (Double) num-+ bers are used for inherently approximate statistics like stats txns/s,+ prices --summary coverage, roi and holdings rates of return, and debug tim-+ ings, where they are a better fit.++ Unlike the usual floating point numbers, which are binary and fixed-size,+ and so frequently rounded, decimal numbers are base ten, so amounts like+ 0.1 are stored exactly, and they can have up to 255 decimal places (and any+ number of digits in the integer part). Addition, subtraction and multipli-+ cation are exact (as long as the result needs no more than 255 decimal+ places). Division can produce a non-terminating decimal (like 1/3 =+ 0.333...); hledger rounds these to 255 decimal places. The error is less+ than 10^-250, too small to affect transaction balancing or reports at nor-+ mal display precisions. When hledger shows such a rounded amount in full,+ eg in print output, it shows 8 decimal places.++ Where hledger divides+ Non-terminating decimals can arise only where hledger divides. (Journal+ amounts are written as finite decimals, and amount expressions round their+ results, except in costs.) Here's when that happens:++ When What is di- Visible effect+ vided+ -----------------------------------------------------------------------------+ Dividing in an amount ex- amount / None: the result is rounded to+ pression ($100.00 / 3) number the entry's decimal places for+ that commodity when the journal+ is read, so it is exactly what+ print shows. A split that+ doesn't divide evenly makes the+ transaction unbalanced, unless+ one amount is left blank.+ Dividing in a cost expres- amount / None in calculations: the cost+ sion (@ 1 / 1.14 EUR) number, or is kept exact. print shows a+ number / repeating decimal with 8 deci-+ amount mal places (more if written),+ so text copied from it is+ slightly rounded.+ Converting a lot's total total cost / None in calculations: gains use+ cost (@@) or total cost quantity the unrounded unit cost. Lot+ basis ({{ }}) to a unit names and print show it with up+ cost to 8 decimal places (more if+ the cost commodity's display+ style has more), so text copied+ from them is slightly rounded;+ see Cost basis precision.+ Inferring market prices total cost / None+ from costs, with --in- quantity+ fer-market-prices+ Using a reverse market 1 / price None+ price+ Averaging lot costs, with total cost / None+ the AVERAGE cost basis total quan-+ methods or in holdings tity+ Inferring costs from eq- one amount / None+ uity conversion postings the other+ Inferring a unit cost for total / None in calculations. print -x+ several postings in one quantity shows it with 8 decimal places+ commodity, in an implicit (more if the commodities' deci-+ conversion mal places add up to more), so+ text copied from it is slightly+ rounded.+ Converting amounts written amount / None in calculations: unit+ with a commodity alias alias quan- costs are replaced by exact to-+ that has a quantity tity tal costs, and balance asser-+ tions convert the alias+ amounts' total (so three 10 min+ amounts satisfy a = 0.5 h as-+ sertion). print -x shows con-+ verted amounts with all their+ decimal places (8 for a repeat-+ ing decimal).+ Calculating averages (eg total / None: these are displayed+ -A) and percentages (eg count, part rounded+ -%) in reports / total+ Converting times to hours time / hour Negligible: each is rounded at+ in timeclock entries, and length the 255th decimal place, so eg+ timedot durations written three 10m timedot entries total+ in minutes or seconds 0.50 hours, as displayed. But+ (10m) that total isn't exactly 0.5,+ so a balance assertion of 0.5+ hours on it would fail. Re-+ ports show durations with 2+ decimal places; print shows a+ repeating decimal with 8+ (0.16666667).+ Calculating rates of re- various Rates are approximate (calcu-+ turn: roi's IRR and TWR, lated with floating point num-+ and holdings' XIRR column bers; IRR and XIRR by itera-+ tion)++Transaction balancing+ A transaction's postings must add up to zero. When they are all in one+ commodity, this is simple: the sum must be exactly zero. But when a trans-+ action converts between commodities using a cost, the cost is often rounded+ (by you, or by your bank or broker), and requiring an exact zero would re-+ ject many correct-looking entries. So, like Ledger and Beancount, hledger+ allows a small tolerance.++ How balancing is checked+ For each commodity in a journal entry, hledger:++ 1. adds up the posting amounts in that commodity, after converting any+ amounts that have a cost to the cost's commodity (exactly; see Amount+ arithmetic)++ 2. finds the entry's balancing precision for that commodity: the most deci-+ mal places used by that commodity's amounts in the entry, not counting+ cost amounts++ 3. considers the entry balanced if the sum rounds to zero at that preci-+ sion. In other words, the imbalance can be at most half a unit in the+ last decimal place: 0.005 for amounts with 2 decimal places, 0.5 for+ amounts with no decimal places.++ Eg:++ 2024-01-30 currency exchange+ assets:usd -19110.17 USD @ 0.869050 CHF+ assets:chf 16607.69 CHF++ The first posting converts to -16607.6932385 CHF, so the sum in CHF is+ -0.0032385 CHF. The balancing precision for CHF is 2 (from 16607.69 CHF;+ the cost amount 0.869050 CHF doesn't count). -0.0032385 rounded to 2 deci-+ mal places is zero, so this entry is accepted.++ To make hledger check an entry more strictly, write its amounts with more+ decimal places. Eg if the second amount above is written as 16607.690 CHF,+ the balancing precision becomes 3 and the entry is rejected.++ Where imbalances come from+ * Rounded unit costs (@). The exact rate may have infinitely many decimal+ places (above, the exact rate is 16607.69 / 19110.17 = 0.86904983053...),+ or just more than your bank or broker shows you. This is the most common+ cause.++ * Total costs (@@) that don't quite match the other amounts. Eg this entry+ is accepted, because the balancing precision for $ is 0 (because $100 was+ written with no decimals):++ 2026-01-01+ assets:stock -3 AAPL @@ $100.40+ assets:cash $100++ Accumulated imbalances+ Accepted imbalances are not corrected; they stay in the data, and add up.+ So reports which convert amounts at cost, like balance -B or balancesheete-+ quity -B, may show a small non-zero total where you would expect zero. Eg+ after three of the currency exchange entries above, hledger bal -B shows a+ total of -0.01 CHF. Typically this is a few cents, but each entry can con-+ tribute up to half a unit in its last decimal place.++ (Without cost conversion, these imbalances aren't directly visible. And+ with --infer-equity, each commodity balances exactly, and the imbalances+ become part of the conversion rates.)++ To see an accumulated imbalance more precisely, increase the display preci-+ sion with -c. Eg:++ $ hledger bal -B -c 'CHF 1.000000000'++ And to see which entries contribute to it, use a register report: hledger+ reg -B -c 'CHF 1.000000000'. Or, show the imbalances explicitly, as de-+ scribed next.++ Showing imbalances+ With the --infer-imbalance flag, hledger shows entry imbalances explicitly,+ by generating postings to an imbalance account (equity:imbalance by de-+ fault) which make the entry balance exactly (as if you had added an amount-+ less posting to that account). Eg:++ $ hledger print --infer-imbalance+ 2024-01-30 currency exchange+ assets:usd -19110.17 USD @ 0.869050 CHF+ assets:chf 16607.69 CHF+ equity:imbalance 0.0032385 CHF++ This doesn't change which entries are accepted. But totals at cost are now+ exactly zero, and the accumulated imbalance appears as the balance of eq-+ uity:imbalance. Eg after three of the currency exchange entries:++ $ hledger bal -B --infer-imbalance+ 49823.07 CHF assets:chf+ -49823.08 CHF assets:usd+ 0.01 CHF equity:imbalance+ --------------------+ 0++ The imbalance postings' amounts are usually smaller than the display preci-+ sion, so to see them individually, increase the display precision. Eg:++ $ hledger areg equity:imbalance --infer-imbalance -c 'CHF 1.0000000'+ Transactions in equity:imbalance and subaccounts:+ 2024-01-30 currency exchange as:usd, as:chf CHF 0.0032385 CHF 0.0032385+ 2024-01-30 currency exchange as:usd, as:chf CHF 0.0032385 CHF 0.0064770+ 2024-01-30 currency exchange as:usd, as:chf CHF 0.0032385 CHF 0.0097155++ Some notes:++ * The imbalance postings have a hidden _imbalance-posting tag (shown by+ --verbose-tags), so they can also be matched with tag:imbalance-posting.++ * To use a different account, declare it with the M/Imbalance account type+ (the first one declared is used, if there are several). Imbalance ac-+ counts, including equity:imbalance, can be matched with type:M.++ * With --infer-equity as well, the generated equity conversion postings use+ the exact cost amounts, so every commodity balances exactly.++ * No imbalance posting is generated if its amount would display as zero (at+ 8 decimal places, for a repeating decimal). This ignores the tiny left-+ overs of hledger's own division (see Amount arithmetic).++ * The imbalance account need not be declared, even in strict mode.++ * To list the entries with an imbalance, without generating postings, you+ can use hledger print not:change:0 (see change: query). (This also lists+ entries with unbalanced virtual postings; not:change:0 change:'<1' would+ list only the small imbalances.)++ * If you use this flag with import, the imbalance postings will be added to+ your journal too.++ Avoiding imbalances+ You can avoid imbalances by writing exact entries. Any of these will do:++ * Use a total cost (@@) instead of a unit cost (@) when the unit cost would+ be rounded. Total costs are converted exactly. Eg -19110.17 USD @@+ 16607.69 CHF.++ * Write the unit cost with enough decimal places to be exact, when possi-+ ble.++ * Add a posting to absorb the imbalance, eg to an expenses:rounding ac-+ count. If you leave its amount blank, hledger will calculate it exactly.++ Transaction balancing before 1.50+ hledger versions before 1.50 used the commodity's display precision as the+ balancing precision, instead of the precision in the entry. This masked+ larger imbalances, and made balancing depend on display settings (see issue+ #2402). So some journal entries (or CSV rules) that worked with hledger+ <1.50 are now rejected with an "unbalanced transaction" error. If you hit+ this, you can:++ * restore the old behaviour, by adding --txn-tolerance=display (formerly+ --txn-balancing=old) to the command or to your ~/.hledger.conf file.+ This lets you keep using old journals unchanged.++ * or fix the problem entries (recommended), in one of these ways:++ 1. make cost amounts more precise (add more or better decimal digits)++ 2. or make non-cost amounts less precise (remove unnecessary decimal dig-+ its that are raising the precision)++ 3. or add a posting to absorb the imbalance, as described above.++Amount formatting+ Commodity display style+ For the amounts in each commodity, hledger chooses a consistent display+ style (symbol placement, decimal mark and digit group marks, number of dec-+ imal digits) to use in most reports. This is inferred as follows:++ First, if there's a D directive declaring a default commodity, that commod-+ ity symbol and amount format is applied to all no-symbol amounts in the+ journal.++ Then each commodity's display style is determined from its commodity direc-+ tive. We recommend always declaring commodities with commodity directives,+ since they help ensure consistent display styles and precisions, and bring+ other benefits such as error checking for commodity symbols. Here's an ex-+ ample:++ # Set display styles (and decimal marks, for parsing, if there is no decimal-mark directive)+ # for the $, EUR, INR and no-symbol commodities:+ commodity $1,000.00+ commodity EUR 1.000,00+ commodity INR 9,99,99,999.00+ commodity 1 000 000.9455++ But for convenience, if a commodity directive is not present, hledger in-+ fers a commodity's display styles from its amounts as they are written in+ the journal (excluding cost amounts and amounts in periodic transaction+ rules or auto posting rules). It uses++ * the symbol placement and decimal mark of the first amount seen++ * the digit group marks of the first amount with digit group marks++ * and the maximum number of decimal digits seen across all amounts.++ And as fallback if no applicable amounts are found, it would use a default+ style, like $1000.00 (symbol on the left with no space, period as decimal+ mark, and two decimal digits).++ Finally, commodity styles can be overridden by the -c/--commodity-style+ command line option, described next.++ Commodity style override+ The -c/--commodity-style option overrides a commodity's declared or in-+ ferred display style, for the current command. Its argument is a sample+ amount, as in the commodity directive. Eg, to show dollar amounts with pe-+ riod digit group marks, comma decimal mark, and one decimal digit:++ $ hledger print -c '$1.000,0'++ Some things to note:++ * The option can be repeated, to set the display style of several commodi-+ ties.++ * Omitting the commodity symbol sets the style of just the no-symbol com-+ modity, not of all commodities.++ * For cost amounts, and amounts displayed by the print command, it affects+ only the symbol placement and digit group/decimal marks; those amounts+ are always displayed with all of their decimal digits.++ * In some cases hledger will adjust number formatting to improve parseabil-+ ity, eg by adding trailing decimal marks when needed.++ Display rounding+ Amounts are stored internally as decimal numbers with up to 255 decimal+ places (see Amount arithmetic). They are displayed with their original+ journal precisions by print and print-like reports, and rounded to their+ display precision (the number of decimal digits specified by the commodity+ display style) by other reports. When rounding, hledger uses banker's+ rounding (it rounds to the nearest even digit). So eg 0.5 displayed with+ zero decimal digits appears as "0".++ Trailing decimal marks+ If you're wondering why your print report sometimes shows trailing decimal+ marks, with no decimal digits; it does this when showing amounts that have+ digit group marks but no decimal digits, to disambiguate them and allow+ them to be re-parsed reliably (see Decimal marks). Eg:++ commodity $1,000.00++ 2023-01-02+ (a) $1000++ $ hledger print+ 2023-01-02+ (a) $1,000.++ You can avoid this by disabling digit group marks, eg temporarily with+ -c/--commodity:++ $ hledger print -c '$1000.00'+ 2023-01-02+ (a) $1000++ or by forcing print to show some decimal digits, with --round:++ $ hledger print -c '$1,000.00' --round=soft+ 2023-01-02+ (a) $1,000.00++ Amount parseability+ More generally, hledger output falls into three rough categories, which+ format amounts a little bit differently to suit different consumers:++ 1. "hledger-readable output" - should be readable by hledger (and by hu-+ mans)++ * This is produced by reports that show full journal entries: print, im-+ port, close, rewrite etc.++ * It shows amounts with their original journal precisions, which may not be+ consistent from one amount to the next.++ * It adds a trailing decimal mark when needed to avoid showing ambiguous+ amounts.++ * It can be parsed reliably (by hledger and ledger2beancount at least, but+ perhaps not by Ledger..)++ 2. "human-readable output" - usually for humans++ * This is produced by all other reports.++ * It shows amounts with standard display precisions, which will be consis-+ tent within each commodity.++ * It shows ambiguous amounts unmodified.++ * It can be parsed reliably in the context of a known report (when you know+ decimals are consistently not being shown, you can assume a single mark+ is a digit group mark).++ 3. "machine-readable output" - usually for other software++ * This is produced by all reports when an output format like csv, tsv,+ json, or sql is selected.++ * It shows amounts as 1 or 2 do, but without digit group marks.++ * It can be parsed reliably (if needed, the decimal mark can be changed+ with -c/--commodity-style).++Cost reporting+ In some transactions - for example a currency conversion, or a purchase or+ sale of stock - one commodity is exchanged for another. In these transac-+ tions there is a conversion rate, also called the cost (when buying) or+ selling price (when selling). (In hledger docs we just say "cost" generi-+ cally for convenience.) With the -B/--cost flag, hledger can show amounts+ "at cost", converted to the cost's commodity.++ Recording costs+ We'll explore several ways of recording transactions involving costs.+ These are also compared at Currency conversion > Four ways to record a con-+ version, compared.++ Costs can be recorded explicitly in the journal, using the @ UNITCOST or @@+ TOTALCOST notation described in Journal > Costs:++ Variant 1++ 2022-01-01+ assets:dollars $-135+ assets:euros a100 @ $1.35 ; $1.35 per euro (unit cost)++ Variant 2++ 2022-01-01+ assets:dollars $-135+ assets:euros a100 @@ $135 ; $135 total cost++ Typically, writing the unit cost (variant 1) is preferable; it can be more+ effort, requiring more attention to decimal digits; but it reveals the+ per-unit cost basis, and makes stock sales easier.++ Costs can also be left implicit, and hledger will infer the cost that is+ consistent with a balanced transaction:++ Variant 3++ 2022-01-01+ assets:dollars $-135+ assets:euros a100++ Here, hledger will attach a @@ a100 cost to the first amount (you can see+ it with hledger print -x). This form looks convenient, but there are down-+ sides:++ * It sacrifices some error checking. For example, if you accidentally+ wrote a10 instead of a100, hledger would not be able to detect the mis-+ take.++ * It is sensitive to the order of postings - if they were reversed, a dif-+ ferent entry would be inferred and reports would be different.++ * The per-unit cost basis is not easy to read.++ So generally this kind of entry is not recommended. You can make sure you+ have none of these by using -s (strict mode), or by running hledger check+ balanced.++ Reporting at cost+ Now when you add the -B/--cost flag to reports ("B" is from Ledger's+ -B/--basis/--cost flag), any amounts which have been annotated with costs+ will be converted to their cost's commodity (in the report output). Ie+ they will be displayed "at cost" or "at sale price".++ For lot postings, which carry a cost basis, -B converts to the cost basis+ instead: a disposal shows what the disposed units cost, not what they sold+ for, consistent with how such entries balance, so eg a lot account's cost+ balance is the cost of the units still held (and zero once they are all+ sold), and bse -B balances. To see transacted amounts (proceeds) instead,+ use --value=transacted.++ Some things to note:++ * Costs are attached to specific posting amounts in specific transactions,+ and once recorded they do not change. This contrasts with market prices,+ which are ambient and fluctuating.++ * Conversion to cost is performed before conversion to market value (de-+ scribed below).++ * A total at cost can be slightly off zero where you might expect zero (eg+ a few cents in bse -B), because hledger accepts entries whose costs were+ rounded; see Accumulated imbalances.++ Equity conversion postings+ There is a problem with the entries above - they are not conventional Dou-+ ble Entry Bookkeeping (DEB) notation, and because of the "magical" trans-+ formation of one commodity into another, they cause an imbalance in the Ac-+ counting Equation. This shows up as a non-zero grand total in balance re-+ ports like hledger bse.++ Most hledger users use cost notation and don't use equity postings; for+ them this imbalance doesn't matter in practice and can safely be ignored.+ But if you'd like to learn more, keep reading.++ Conventional DEB uses an extra pair of equity postings to balance the+ transaction. Of course you can do this in hledger as well:++ Variant 4++ 2022-01-01+ assets:dollars $-135+ assets:euros a100+ equity:conversion $135+ equity:conversion a-100++ Now the transaction is perfectly balanced according to standard DEB, and+ hledger bse's total will not be disrupted. It also translates easily to+ any other double entry accounting system.++ And, hledger can still infer the cost for cost reporting, but it's not done+ by default - you must add the --infer-costs flag like so:++ $ hledger print --infer-costs+ 2022-01-01 one hundred euros purchased at $1.35 each+ assets:dollars $-135 @@ a100+ assets:euros a100+ equity:conversion $135+ equity:conversion a-100++ $ hledger bal --infer-costs -B+ a-100 assets:dollars+ a100 assets:euros+ --------------------+ 0++ Here are some downsides of this kind of entry:++ * The per-unit cost basis is not easy to read.++ * Instead of -B you must remember to type -B --infer-costs.++ * --infer-costs works only where hledger can identify the two equity:con-+ version postings and match them up with the two non-equity postings. So+ writing the journal entry in a particular format becomes more important.+ More on this below.++ Inferring equity conversion postings+ Can we go in the other direction ? Yes, if you have transactions written+ with the @/@@ cost notation, hledger can infer the missing equity postings,+ if you add the --infer-equity flag. Eg:++ 2022-01-01+ assets:dollars -$135+ assets:euros a100 @ $1.35++ $ hledger print --infer-equity+ 2022-01-01+ assets:dollars $-135+ assets:euros a100 @ $1.35+ equity:conversion:$-a:a a-100+ equity:conversion:$-a:$ $135.00++ The equity account names will be "equity:conversion:A-B:A" and "equity:con-+ version:A-B:B" where A is the alphabetically first commodity symbol. You+ can customise the "equity:conversion" part by declaring an account with the+ V/Conversion account type (the first-declared one, if there are several; or+ if none is declared, the alphabetically first account whose type is in-+ ferred as V, such as equity:trading, is used).++ For a lot disposal, the conversion postings record the units sold at their+ cost basis, not at the sale price, so that the entry (and your balance+ sheet) still sums to zero; the difference between the two is the gain post-+ ing. Eg:++ commodity AAPL ; lots:++ 2026-01-02 buy+ assets:stock 10 AAPL @@ $1000+ assets:cash++ 2026-01-03 sell+ assets:stock -4 AAPL @@ $600+ assets:cash $600++ $ hledger print --infer-equity desc:sell+ 2026-01-03 sell+ assets:stock -4 AAPL {2026-01-02, $100} @@ $600+ equity:conversion:$-AAPL:AAPL 4 AAPL+ equity:conversion:$-AAPL:$ $-400+ assets:cash $600+ revenues:gain $-200++ If you write such an entry yourself, write the conversion postings at cost+ basis like this, and keep the transacted cost (@/@@) on the disposal post-+ ing, since the gain is calculated from it.++ The generated equity conversion accounts need not be declared, even in+ strict mode. (And unlike normal postings, generated equity postings do not+ inherit tags from account declarations.)++ Combining costs and equity conversion postings+ Finally, you can use both the @/@@ cost notation and equity postings at the+ same time. This in theory gives the best of all worlds - preserving the+ accounting equation, revealing the per-unit cost basis, and providing more+ flexibility in how you write the entry:++ Variant 5++ 2022-01-01 one hundred euros purchased at $1.35 each+ assets:dollars $-135+ equity:conversion $135+ equity:conversion a-100+ assets:euros a100 @ $1.35++ All the other variants above can (usually) be rewritten to this final form+ with:++ $ hledger print -x --infer-costs --infer-equity++ Or you can enable both flags always, eg in your config file, and your re-+ ports will have the advantages of both.++ Downsides:++ * The precise format of the journal entry becomes more important. If+ hledger can't detect and match up the cost and equity postings, it will+ give a transaction balancing error.++ * The add command does not yet accept this kind of entry (#2056).++ * This is the most verbose form.++ Requirements for detecting equity conversion postings+ --infer-costs has certain requirements (unlike --infer-equity, which always+ works). It will infer costs only in transactions with:++ * Two non-equity postings, in different commodities. If one of them is+ lotful, the cost will be added to that one; otherwise it will be added to+ the first (top) one.++ * Two postings to equity conversion accounts, next to one another, which+ balance the two non-equity postings. This balancing is checked to the+ same precision (number of decimal places) used in the conversion post-+ ing's amount. Equity conversion accounts are:++ * any accounts declared with account type V/Conversion, or their subac-+ counts++ * otherwise, accounts named equity:conversion, equity:trade, or eq-+ uity:trading, or their subaccounts.++ And multiple such four-posting groups can coexist within a single transac-+ tion. When --infer-costs fails, it does not infer a cost in that transac-+ tion, and does not raise an error (ie, it infers costs where it can).++ Reading variant 5 journal entries, combining cost notation and equity post-+ ings, has all the same requirements. When reading such an entry fails,+ hledger raises an "unbalanced transaction" error. For a lot disposal, the+ conversion postings may balance the disposal's cost basis instead of its+ transacted cost, as described above.++Value reporting+ hledger can also show amounts "at market value", converted to some other+ commodity using the market price or conversion rate on a certain date.++ This is controlled by the --value=TYPE[,COMMODITY] option. We also provide+ simpler -V and -X COMMODITY aliases for this, which are often sufficient.+ The market prices are declared with a special P directive, and/or they can+ be inferred from the costs recorded in transactions, by using the --in-+ fer-market-prices flag.++ -X: Value in specified commodity+ The -X COMM (or --exchange=COMM) option converts amounts to their market+ value in the specified commodity, using the market prices in effect on the+ valuation date(s), if any. (More on these in a minute.)++ Use this when you want to (eg) show everything in your base currency as far+ as possible. (Commodities for which no conversion rate can be found, will+ not be converted.)++ COMM should be the commodity symbol exactly as written in the journal's+ amounts or market prices (eg $, not USD, if the journal uses $); ISO cur-+ rency codes are not matched to symbols. If no conversion price to COMM can+ be found, a warning is printed, suggesting an equivalent journal commodity+ if one exists. Remember to quote special shell characters, if needed.+ Some examples:++ * -Xa++ * -X$ (nothing after $, no quoting needed)++ * -X CNY (the space after -X is optional)++ * -X 'red apples'++ * -X 'r&r'++ -V: Value in default commodity(s)+ The -V/--market flag is a variant of -X where you don't have to specify+ COMM. Instead it tries to guess a default valuation commodity for each+ original commodity, based on the market prices in effect on the valuation+ date(s).++ -V can often be a convenient shortcut for -X MYCURRENCY, but not always;+ depending on your data it could guess multiple valuation commodities. Usu-+ ally you want to convert to a single commodity, so it's better to use -X,+ unless you're sure -V is doing what you want.++ Valuation date+ Market prices can change from day to day. hledger will use the prices on a+ particular valuation date (or on more than one date). By default hledger+ uses "end" dates for valuation. More specifically:++ * For single period reports (including normal print and register reports):++ * If an explicit report end date is specified, that is used.++ * Otherwise the latest transaction date or non-future P directive date is+ used.++ * For multiperiod reports, each period is valued on its last day.++ This can be customised with the --value option described below, which can+ select either "then", "end", "now", or "custom" dates.++ Finding market price+ To convert a commodity A to its market value in another commodity B,+ hledger looks for a suitable market price (exchange rate) as follows, in+ this order of preference:++ 1. A declared market price or inferred market price: A's latest market+ price in B on or before the valuation date as declared by a P directive,+ or (with the --infer-market-prices flag) inferred from costs.++ 2. A reverse market price: the inverse of a declared or inferred market+ price from B to A.++ 3. A forward chain of market prices: a synthetic price formed by combining+ the shortest chain of "forward" (only 1 above) market prices, leading+ from A to B.++ 4. Any chain of market prices: a chain of any market prices, including both+ forward and reverse prices (1 and 2 above), leading from A to B.++ 5. Commodity alias rates: if none of the above is found, the same search is+ repeated, also using commodity aliases as fixed exchange rates (between+ a commodity and its alias, when there are no market prices between+ them). This lets you value amounts in an alias declared by another+ file, or show amounts in an alias with -X, but aliases never change a+ conversion that market prices can provide. To see these rates and where+ their aliases were declared, use prices --show-aliases --locations;+ --debug=2 output shows when they are tried.++ There is a limit to the length of these price chains; if hledger reaches+ that length without finding a complete chain or exhausting all possibili-+ ties, it will give up (with a "gave up" message visible in --debug=2 out-+ put). That limit is currently 1000.++ Amounts for which no suitable market price can be found, are not converted.++ Commodity alias rates are used only for converting, never as a default val-+ uation commodity for -V.++ --infer-market-prices: market prices from transactions+ Normally, market value in hledger is fully controlled by, and requires, P+ directives in your journal. Since adding and updating those can be a+ chore, and since transactions usually take place at close to market value,+ why not use the recorded costs as additional market prices (as Ledger does)+ ? Adding the --infer-market-prices flag to -V, -X or --value enables this.++ So for example, hledger bs -V --infer-market-prices will get market prices+ both from P directives and from transactions. If both occur on the same+ day, the P directive takes precedence.++ There is a downside: value reports can sometimes be affected in confus-+ ing/undesired ways by your journal entries. If this happens to you, read+ all of this Value reporting section carefully, and try adding --debug or+ --debug=2 to troubleshoot.++ --infer-market-prices can infer market prices from:++ * multicommodity transactions with explicit prices (@/@@)++ * multicommodity transactions with implicit prices (no @, two commodities,+ unbalanced). (With these, the order of postings matters. hledger print+ -x can be useful for troubleshooting.)++ * multicommodity transactions with equity postings, if cost is inferred+ with --infer-costs.++ There is a limitation (bug) currently: when a valuation commodity is not+ specified, prices inferred with --infer-market-prices do not help select a+ default valuation commodity, as P prices would. So conversion might not+ happen because no valuation commodity was detected (--debug=2 will show+ this). To be safe, specify the valuation commmodity, eg:++ * -X EUR --infer-market-prices, not -V --infer-market-prices++ * --value=then,EUR --infer-market-prices, not --value=then --infer-mar-+ ket-prices++ Signed costs and market prices can be confusing. For reference, here is+ the current behaviour. (If you think it should work differently, see+ #1870.)++ 2022-01-01 Positive Unit prices+ a A 1+ b B -1 @ A 1++ 2022-01-01 Positive Total prices+ a A 1+ b B -1 @@ A 1+++ 2022-01-02 Negative unit prices+ a A 1+ b B 1 @ A -1++ 2022-01-02 Negative total prices+ a A 1+ b B 1 @@ A -1+++ 2022-01-03 Double Negative unit prices+ a A -1+ b B -1 @ A -1++ 2022-01-03 Double Negative total prices+ a A -1+ b B -1 @@ A -1++ All of the transactions above are considered balanced (and on each day, the+ two transactions are considered equivalent). Here are the market prices+ inferred for B:++ $ hledger -f- --infer-market-prices prices+ P 2022-01-01 B A 1+ P 2022-01-01 B A 1.0+ P 2022-01-02 B A -1+ P 2022-01-02 B A -1.0+ P 2022-01-03 B A -1+ P 2022-01-03 B A -1.0++ Valuation commodity+ When you specify a valuation commodity (-X COMM or --value TYPE,COMM):+ hledger will convert all amounts to COMM, wherever it can find a suitable+ market price (including by reversing or chaining prices).++ When you leave the valuation commodity unspecified (-V or --value TYPE):+ For each commodity A, hledger picks a default valuation commodity as fol-+ lows, in this order of preference:++ 1. The price commodity from the latest P-declared market price for A on or+ before valuation date.++ 2. The price commodity from the latest P-declared market price for A on any+ date. (Allows conversion to proceed when there are inferred prices be-+ fore the valuation date.)++ 3. If there are no P directives at all (any commodity or date) and the+ --infer-market-prices flag is used: the price commodity from the latest+ transaction-inferred price for A on or before valuation date.++ This means:++ * If you have P directives, they determine which commodities -V will con-+ vert, and to what.++ * If you have no P directives, and use the --infer-market-prices flag,+ costs determine it.++ Amounts for which no valuation commodity can be found are not converted.++ --value: Flexible valuation+ -V and -X are special cases of the more general --value option:++ --value=TYPE[,COMM] TYPE is then, end, now, YYYY-MM-DD, cost or transacted.+ COMM is an optional commodity symbol.+ Shows amounts converted to:+ - default valuation commodity (or COMM) using market prices at posting dates+ - default valuation commodity (or COMM) using market prices at period end(s)+ - default valuation commodity (or COMM) using current market prices+ - default valuation commodity (or COMM) using market prices at some date+ - cost basis, or else transacted cost (like -B)+ - transacted cost only++ The TYPE part selects cost or value and valuation date:++ --value=then+ Convert amounts to their value in the default valuation commodity,+ using market prices on each posting's date.++ --value=end+ Convert amounts to their value in the default valuation commodity,+ using market prices on the last day of the report period (or if un-+ specified, the journal's end date); or in multiperiod reports, mar-+ ket prices on the last day of each subperiod.++ --value=now+ Convert amounts to their value in the default valuation commodity+ using current market prices (as of when report is generated).++ --value=YYYY-MM-DD+ Convert amounts to their value in the default valuation commodity+ using market prices on this date.++ --value=cost+ Convert amounts to their cost basis where they have one (lot post-+ ings), otherwise to their transacted cost. Same as -B/--cost; see+ Reporting at cost.++ --value=transacted+ Convert amounts to their transacted cost or sale amount (@/@@), ig-+ noring any cost basis. This is -B's behaviour for non-lot postings,+ and shows proceeds rather than cost for lot disposals.++ To select a different valuation commodity, add the optional ,COMM part: a+ comma, then the target commodity's symbol. Eg: --value=now,EUR. hledger+ will do its best to convert amounts to this commodity, deducing market+ prices as described above.++ The symbol may be written in double quotes, as in a journal. To select the+ no-symbol commodity, write it as "", or leave the symbol empty:+ --value=now,'""', --value=now,, -X '""' and -X '' all work.++ Valuation examples+ Here are some quick examples of -V:++ ; one euro is worth this many dollars from nov 1+ P 2016/11/01 a $1.10++ ; purchase some euros on nov 3+ 2016/11/3+ assets:euros a100+ assets:checking++ ; the euro is worth fewer dollars by dec 21+ P 2016/12/21 a $1.03++ How many euros do I have ?++ $ hledger -f t.j bal -N euros+ a100 assets:euros++ What are they worth at end of nov 3 ?++ $ hledger -f t.j bal -N euros -V -e 2016/11/4+ $110.00 assets:euros++ What are they worth after 2016/12/21 ? (no report end date specified, de-+ faults to today)++ $ hledger -f t.j bal -N euros -V+ $103.00 assets:euros++ Here are some examples showing the effect of --value, as seen with print:++ P 2000-01-01 A 1 B+ P 2000-02-01 A 2 B+ P 2000-03-01 A 3 B+ P 2000-04-01 A 4 B++ 2000-01-01+ (a) 1 A @ 5 B++ 2000-02-01+ (a) 1 A @ 6 B++ 2000-03-01+ (a) 1 A @ 7 B++ Show the cost of each posting:++ $ hledger -f- print --cost+ 2000-01-01+ (a) 5 B++ 2000-02-01+ (a) 6 B++ 2000-03-01+ (a) 7 B++ Show the value as of the last day of the report period (2000-02-29):++ $ hledger -f- print --value=end date:2000/01-2000/03+ 2000-01-01+ (a) 2 B++ 2000-02-01+ (a) 2 B++ With no report period specified, the latest transaction date or price date+ is used as valuation date (2000-04-01):++ $ hledger -f- print --value=end+ 2000-01-01+ (a) 3 B++ 2000-02-01+ (a) 3 B++ 2000-03-01+ (a) 3 B++ The value today is the same (the 2000-04-01 price is still in effect):++ $ hledger -f- print --value=now+ 2000-01-01+ (a) 4 B++ 2000-02-01+ (a) 4 B++ 2000-03-01+ (a) 4 B++ Show the value on 2000/01/15:++ $ hledger -f- print --value=2000-01-15+ 2000-01-01+ (a) 1 B++ 2000-02-01+ (a) 1 B++ 2000-03-01+ (a) 1 B++ Interaction of valuation and queries+ When matching postings based on queries in the presence of valuation, the+ following happens:++ 1. The query is separated into two parts:++ 1. the currency (cur:) or amount (amt:).++ 2. all other parts.++ 2. The postings are matched to the currency and amount queries based on+ pre-valued amounts.++ 3. Valuation is applied to the postings.++ 4. The postings are matched to the other parts of the query based on+ post-valued amounts.++ Related: #1625++ Effect of valuation on reports+ Here is a reference for how valuation is supposed to affect each part of+ hledger's reports. It may be useful when troubleshooting. Related: #329,+ #1083.++ First, a quick glossary:++ cost calculated using price(s) recorded in the transaction(s).++ value market value using available market price declarations, or the un-+ changed amount if no conversion rate can be found.++ report start+ the first day of the report period specified with -b or -p or date:,+ otherwise today.++ report or journal start+ the first day of the report period specified with -b or -p or date:,+ otherwise the earliest transaction date in the journal, otherwise+ today.++ report end+ the last day of the report period specified with -e or -p or date:,+ otherwise today.++ report or journal end+ the last day of the report period specified with -e or -p or date:,+ otherwise the latest transaction date in the journal, otherwise to-+ day.++ report interval+ a flag (-D/-W/-M/-Q/-Y) or period expression that activates the re-+ port's multi-period mode (whether showing one or many subperiods).++ Report -B, --cost -V, -X --value=then --value=end --value=DATE,+ type --value=now+ --------------------------------------------------------------------------------------------+ print+ posting cost value at re- value at posting value at re- value at+ amounts port end or date port or DATE/today+ today journal end+ balance unchanged unchanged unchanged unchanged unchanged+ asser-+ tions/as-+ signments++ register+ starting cost value at re- valued at day value at re- value at+ balance port or each historical port or DATE/today+ (-H) journal end posting was made journal end+ starting cost value at day valued at day value at day value at+ balance before re- each historical before re- DATE/today+ (-H) with port or posting was made port or+ report journal journal+ interval start start+ posting cost value at re- value at posting value at re- value at+ amounts port or date port or DATE/today+ journal end journal end+ summary summarised value at pe- sum of postings value at pe- value at+ posting cost riod ends in interval, val- riod ends DATE/today+ amounts ued at interval+ with re- start+ port in-+ terval+ running sum/average sum/average sum/average of sum/average sum/average+ total/av- of displayed of displayed displayed values of displayed of displayed+ erage values values values values++ balance+ (bs, bse,+ cf, is)+ balance sums of value at re- value at posting value at re- value at+ changes costs port end or date port or DATE/today of+ today of journal end sums of post-+ sums of of sums of ings+ postings postings+ budget like balance like balance like balance like bal- like balance+ amounts changes changes changes ances changes+ (--bud-+ get)+ grand to- sum of dis- sum of dis- sum of displayed sum of dis- sum of dis-+ tal played val- played val- valued played val- played values+ ues ues ues++ balance+ (bs, bse,+ cf, is)+ with re-+ port in-+ terval+ starting sums of value at re- sums of values of value at re- sums of post-+ balances costs of port start postings before port start ings before+ (-H) postings be- of sums of report start at of sums of report start+ fore report all postings respective post- all postings+ start before re- ing dates before re-+ port start port start+ balance sums of same as sums of values of balance value at+ changes costs of --value=end postings in pe- change in DATE/today of+ (bal, is, postings in riod at respec- each period, sums of post-+ bs period tive posting valued at ings+ --change, dates period ends+ cf+ --change)+ end bal- sums of same as sums of values of period end value at+ ances costs of --value=end postings from be- balances, DATE/today of+ (bal -H, postings fore period start valued at sums of post-+ is --H, from before to period end at period ends ings+ bs, cf) report start respective post-+ to period ing dates+ end+ budget like balance like balance like balance like bal- like balance+ amounts changes/end changes/end changes/end bal- ances changes/end+ (--bud- balances balances ances balances+ get)+ row to- sums, aver- sums, aver- sums, averages of sums, aver- sums, aver-+ tals, row ages of dis- ages of dis- displayed values ages of dis- ages of dis-+ averages played val- played val- played val- played values+ (-T, -A) ues ues ues+ column sums of dis- sums of dis- sums of displayed sums of dis- sums of dis-+ totals played val- played val- values played val- played values+ ues ues ues+ grand to- sum, average sum, average sum, average of sum, average sum, average+ tal, of column of column column totals of column of column to-+ grand av- totals totals totals tals+ erage+++ --cumulative is omitted to save space, it works like -H but with a zero+ starting balance.++Lots and capital gains+ When you buy (acquire) some amount of an investment commodity (a lot), it+ can be important (depending on your local tax rules) to keep track of its+ original cost and acquisition date (cost basis), so that when you sell+ (dispose) it, you can calculate capital gains (or losses), and document how+ you satisfied the rules about disposal order, short term vs long term+ gains, and so on.++ For many kinds of investment, each individual lot has its own cost basis,+ which must be tracked even if the lot is reduced, split up, or transferred.+ Also lots may need to be moved and disposed of in a prescribed order. All+ this can be very hard to keep track of by hand, so usually it is done by an+ investment broker, cryptocurrency exchange, or specialised tax software.+ Now, you can also do it yourself with hledger.++ Automated lot tracking and capital gains reporting is the biggest new fea-+ ture of hledger 2. Lot tracking was first shipped in Ledger, then improved+ in Beancount; hledger 2 evolves PTA lot tracking further, making it more+ powerful and ergonomic. You can record lot details explicitly, or let+ hledger infer them. hledger checks lot entries; tracks, infers and vali-+ dates lot movements; and calculates capital gains when lots are sold.++ Note hledger 2's lot processing happens only for entries that use lot nota-+ tion, or where lots are inferred. If you have hledger 1 journal files that+ you want to migrate, or use with both hledger 1 and hledger 2, see hledger+ 1 and hledger 2.++ For practical advice on turning on lot tracking in an existing journal, see+ Start tracking lots. For a more technical version of what's in this man-+ ual, see SPEC-lots.++ First lots example+ hledger's lot tracking does not require much extra work. Here is a small+ example, using just the familiar @ syntax, and new lots tag. (Several ways+ to write lot entries below shows the other notations.):++ commodity AAPL ; lots:++ 2026-01-15 buy+ assets:cash -$500+ assets:stocks 10 AAPL @ $50++ 2026-02-01 sell some+ assets:stocks -5 AAPL @ $70+ assets:cash $350++ Lot tracking is activated for AAPL by the lots tag, so hledger will++ * keep track of each lot that's acquired (and optionally show them in re-+ ports)++ * dispose of lots in the right order (FIFO by default)++ * calculate the resulting capital gain, and add the gain posting if missing++ * check for many kinds of error (such as selling more than you have).++ print shows the inferred cost basis annotations and gain posting (so its+ output can be re-read even without the commodity directive, if the default+ cost basis method is used):++ $ hledger print+ 2026-01-15 buy+ assets:cash $-500+ assets:stocks 10 AAPL {$50} @ $50++ 2026-02-01 sell some+ assets:stocks -5 AAPL {2026-01-15, $50} @ $70+ assets:cash $350+ revenues:gain $-100++ print's -a flag (short for --all) shows maximum detail, including the lots+ as subaccounts and tags showing how the entry was analysed:++ $ hledger print -a+ 2026-01-15 buy+ assets:cash $-500+ assets:stocks:{2026-01-15, $50} 10 AAPL {$50} @ $50 ; ptype: acquire++ 2026-02-01 sell some+ assets:stocks:{2026-01-15, $50} -5 AAPL {2026-01-15, $50} @ $70 ; ptype: dispose+ assets:cash $350+ revenues:gain $-100 ; ptype: gain, generated-posting:++ If anything looks wrong, see Troubleshooting lots below.++ Once you have lot entries, holdings will show an overview of your invest-+ ments - units held, per-unit and total cost and value, realised and unre-+ alised gain, and XIRR (extended internal rate of return). To see all of+ these, add at least one market price declaration, eg:++ P 2026-03-31 AAPL $72++ Then:++ $ hledger holdings -e 2026-04-01+ Holdings on 2026-03-31++ || Date Age Units Avg cost Unit price Total cost Total value Weight UGain UGain% RGain XIRR+ ===============++===============================================================================================================+ assets:stocks || 2026-01-15 75d 5 AAPL $50 $72 $250 $360 100.0% $110 44.0% $100 1865.3%+ ---------------++---------------------------------------------------------------------------------------------------------------+ || 5 AAPL $50 $250 $360 100.0% $110 44.0% $100 1865.3%++ You can add --lots to see the individual lots (this works with all re-+ ports):++ $ hledger holdings -e 2026-04-01 --lots+ Holdings on 2026-03-31++ || Date Age Units Unit cost Unit price Total cost Total value Weight UGain UGain% RGain XIRR+ =================================++================================================================================================================+ assets:stocks:{2026-01-15, $50} || 2026-01-15 75d 5 AAPL $50 $72 $250 $360 100.0% $110 44.0% $100 1865.3%+ ---------------------------------++----------------------------------------------------------------------------------------------------------------+ || 5 AAPL $50 $250 $360 100.0% $110 44.0% $100 1865.3%++ Writing lot entries+ Lot tracking can be enabled in two ways:++ * Per posting: write explicit cost basis annotations like in Ledger or+ Beancount, or explicit lot subaccount names. These postings will be+ tracked lotfully.++ * Per commodity: declare the commodity lotful with a lots tag. All of its+ postings are tracked lotfully, and the annotations are inferred for you.+ This is convenient, and recommended.++ A posting with any of these is called a lot posting.++ Cost basis annotations+ Each acquisition of an investment creates a lot, with a cost basis. In+ hledger, a lot's cost basis has 2-3 parts:++ 1. The nominal acquisition date (required). Usually this is the date you+ acquired the lot.++ 2. A short text label (optional). This can be used to distinguish lots ac-+ quired on the same date.++ 3. The nominal acquisition cost (required). Usually this is what you paid+ for it.++ In the journal, we can write cost basis annotations, enclosed in {} after+ an amount (the syntax is described in Cost basis), above. These often men-+ tion only part of the cost basis, typically just the cost ({$50}), or noth-+ ing at all ({}); hledger infers the rest.++ On an acquisition, the annotation records the new lot's cost basis. On a+ disposal or transfer, it is instead a lot selector, choosing which existing+ lot(s) to take from: a full or partial cost basis, like {2026-01-15, $50}+ or {2026-01-15}, identifies one specific lot, while {} (or no annotation)+ lets hledger choose, using the cost basis method.++ Lotful commodities+ A more convenient way to record lot transactions, is to declare commodities+ as lotful, by adding a lots tag in their declaration. Eg:++ commodity AAPL ; lots:++ This tells hledger that postings involving these commodities always involve+ lots, so it will infer cost basis annotations automatically, and you won't+ need to write them in the journal.++ The lots tag can also have a value, selecting the disposal order (see Cost+ basis methods); and on account declarations it disables or customises lot+ tracking per account, as described in Disabling lot tracking below.++ Lot subaccounts+ Internally, hledger tracks each lot in a subaccount, named like the cost+ basis. You don't need to write these subaccounts in the journal; hledger+ infers them automatically. They are hidden from reports by default, since+ there can be many lots. To show them, add the --lots flag to any report+ (the holdings command is designed for viewing them).++ If you do write a lot subaccount in the journal, it is equivalent to writ-+ ing a cost basis annotation on the amount:++ 2026-01-15 buy+ assets:stocks:{2026-01-15, $50} 10 AAPL+ assets:cash++ $ hledger print+ 2026-01-15 buy+ assets:stocks 10 AAPL {2026-01-15, $50}+ assets:cash++ A final account name part enclosed in { and } is reserved for lot subac-+ counts, and it must be a valid lot subaccount name (unless using -I or+ --ignore-lots). Lot subaccount names must be complete, including all cost+ basis parts - date, label if any, and cost.++ When strictly checking account names, lot subaccounts are ignored - you+ only need to declare the base account (eg assets:stocks), not the lot sub-+ accounts.++ Several ways to write lot entries+ Here are two acquisitions and a disposal, written in several ways. First,+ with explicit lot subaccounts:++ 2026-01-15 buy low+ assets:stocks:{2026-01-15, $50} 10 AAPL+ assets:cash -$500++ 2026-02-01 buy high+ assets:stocks:{2026-02-01, $60} 10 AAPL+ assets:cash -$600++ 2026-03-01 sell some+ assets:stocks:{2026-01-15, $50} -5 AAPL @ $70+ assets:cash $350++ Second, with cost basis annotations (here the {} selector means: use the+ default method, FIFO; and the @ costs could be omitted, since hledger can+ infer them from the cash postings):++ 2026-01-15 buy low+ assets:stocks 10 AAPL {$50}+ assets:cash -$500++ 2026-02-01 buy high+ assets:stocks 10 AAPL {$60}+ assets:cash -$600++ 2026-03-01 sell some+ assets:stocks -5 AAPL {} @ $70+ assets:cash $350++ Third, with a lots tag on the commodity, lots are inferred from the trans-+ acted costs:++ commodity AAPL ; lots:++ 2026-01-15 buy low+ assets:stocks 10 AAPL @ $50+ assets:cash -$500++ 2026-02-01 buy high+ assets:stocks 10 AAPL @ $60+ assets:cash -$600++ 2026-03-01 sell some+ assets:stocks -5 AAPL @ $70+ assets:cash $350++ All three notations produce the same lots and the same $100 gain; Lot re-+ ports below shows them.++ Disabling lot tracking+ If you want a commodity tracked lotfully in only some accounts, use annota-+ tions rather than the lots tag. Or if it should be tracked everywhere ex-+ cept certain accounts (eg tax-sheltered accounts where cost basis doesn't+ matter), use the lots tag, and add a lots: NONE tag to those accounts' dec-+ larations to disable lot tracking there:++ account assets:ira ; lots: NONE++ Postings in such accounts are not lot-tracked and get no lot subaccounts or+ gain postings, unless they have explicit lot annotations, which always en-+ able tracking. Moving a lotful commodity from a tracked account into such+ an account is a disposal; moving it out again needs a cost basis or price+ on the receiving posting.++ Sometimes you may want to disable lots/gains processing entirely, to si-+ lence lot-related errors when you are working with incomplete journals (eg,+ when piping hledger print into another hledger command, or when fixing a+ complex journal's problems one at a time). For this, use the --ignore-lots+ flag, or just -I. This skips lot tracking, capital gains calculation, and+ all lot error checking, while still doing enough lot inference that lot en-+ tries balance as usual. Reports then show no lot subaccounts or gains, and+ print shows lot entries as you wrote them, without inferred cost basis an-+ notations or gain postings (explicit annotations are kept, and may not be+ readable by hledger 1; if that's needed, use -O ledger to write them in+ Ledger's syntax, which hledger 1 accepts and ignores).++ Lot movements+ hledger understands three kinds of lot movement: acquire, transfer, and+ dispose. Other real-world lot events can usually be modelled using combi-+ nations of these (see Other lot events below). These are described for+ lots in asset accounts; in liability accounts, which hold short positions,+ the signs are reversed.++ Lots are calculated in date order, and entries on the same date in the or-+ der they are read (an included file is read at the point where it is in-+ cluded). So an entry which takes lots out of an account must come after+ the entries that put them there, even on the same date; hledger doesn't re-+ order entries to make lots available. When this goes wrong, the "no lots+ available" error names a later entry on the same date which would have sup-+ plied the lots, if there is one.++ Acquire+ A positive lot posting in an asset account creates a new lot.++ 2026-01-01 buy shares+ assets:cash -$500+ assets:broker 10 ETSY {$50}++ The asset posting's cost is the lot's cost basis; hledger balances the+ transaction and calculates gains with it. It can be written as a cost ba-+ sis annotation ({UNITCOST} or {{TOTALCOST}}) or as a transacted cost (@+ UNITCOST or @@ TOTALCOST); in an acquisition these mean the same thing.+ (Note, @ alone makes a lot posting only if the commodity is declared lotful+ or the account is named like a lot subaccount; otherwise it is just a con-+ version and creates no lot. To make it an acquisition, adding just {}+ would be enough, eg 10 ETSY {} @ $50.) Usually you write just one and the+ other is inferred; if both are written, they must agree (at the precision+ you wrote the basis with; the exact transacted cost is then used as the ba-+ sis; see also Basis and transacted cost must agree). (The total cost forms+ are useful when the unit cost is non-terminating.) The cost can also be+ inferred from a lot subaccount name, or, for a lotful commodity, from the+ transaction's other postings - so even a bare positive posting (no {} or @)+ can be an acquire.++ The other postings show what funded the basis, such as:++ * cash for what you paid (including fees if you want those capitalised in+ the basis; see Capitalising fees)++ * an expense posting for any part of what you paid that isn't basis (a fee+ you don't want to capitalise)++ * an income or equity posting for any part you didn't pay (as with a gift's+ carryover basis or shares received as compensation).++ Eg shares received as a gift, with the giver's basis carried over:++ 2026-01-01 gift of 10 AAPL, carryover basis $50/share+ equity:gifts received $-500+ assets:stocks 10 AAPL @ $50++ Other cases with a basis differing from what was paid include inheritance+ (stepped-up basis), stock options and RSUs, and wash sales; see+ https://en.wikipedia.org/wiki/Cost_basis. Recording them this way keeps+ the accounting equation balanced and shows where the basis came from.++ Basis and transacted cost must agree+ In an acquisition, if both a cost basis ({}) and a transacted cost (@) are+ written, they must be the same. (Ledger and Beancount allow them to dif-+ fer; hledger reports an error.) This is because:++ * In hledger, @ has one consistent meaning: the transacted cost, what was+ actually exchanged. It's what transactions balance with (except for lot+ disposals, which balance with the cost basis; see Gains). Market prices+ are recorded with P directives, and cost basis with {} annotations.+ (hledger may infer the {} from @ in a lot acquisition, as print -a will+ show.)++ * If @ and {} could differ, the difference would have no proper place. If+ the entry balanced with @ while gains were calculated from {}, the dif-+ ference would be unaccounted for: it would be neither gain nor income,+ and cost reports (eg bse -B) would be off by it. If it balanced with {}+ instead (as in Ledger and Beancount), @ would need a second meaning, an+ informational market price.++ * Real cases where the basis differs from what was paid (gifts, inheri-+ tance, RSUs..) don't need it. They are better recorded as shown above,+ with the difference funded by a separate posting, recording where it came+ from.++ * It catches mistakes. Otherwise, a typo in either amount would silently+ miscalculate gains.++ So, if you have such entries (eg from Ledger or Beancount), you can rewrite+ them depending on what was intended:++ * If @ was meant as a market price (the usual Ledger and Beancount mean-+ ing), drop it, and record the price with a P directive. Eg, this Ledger+ entry, which balances with the basis, and records a market price of 1.30+ USD:++ 2026-01-01 buy+ assets:test 10.00 EUR {1.23 USD} @ 1.30 USD+ assets:bank++ can be written for hledger like this:++ P 2026-01-01 EUR 1.30 USD++ 2026-01-01 buy+ assets:test 10.00 EUR {1.23 USD}+ assets:bank++ * If the basis really differs from what you paid, write the same amount in+ both (or just one of them), and record the difference with a separate+ posting, as in the gift example above.++ * If they differ only by rounding, write the basis with more decimal+ places, or use the total cost forms.++ * To load an old journal without errors (and without lot tracking), use+ -I/--ignore-lots.++ Capitalising fees+ hledger does not automatically capitalise fees into cost basis (as some tax+ treatments allow, for purchase or transfer fees). To capitalise an acqui-+ sition fee, fold it into the acquisition cost:++ 2026-01-15 buy 10 AAPL at $50, plus a $10 commission, capitalised+ assets:stocks 10 AAPL @@ $510+ assets:cash -$510++ This lot's cost basis is $51 per share. (Recording the commission as a+ separate expense posting would instead keep it out of the basis.) Capital-+ ising an in-kind transfer fee is possible too, but fiddly; see Other lot+ events.++ Transfer+ A matching pair of negative/positive lotful postings moves one or more ex-+ isting lots between accounts, preserving their cost basis.++ 2026-05-01 transfer to another broker+ assets:broker -10 ETSY+ assets:broker2 10 ETSY++ Transfer postings should not have a transacted price, and the total quanti-+ ties sent and received must match: transferred lots keep their identity.+ Within that, source and destination postings need not pair up one to one -+ one source posting can feed several destination accounts, or several+ sources one destination. The destination amount, or the source amount, can+ also be elided, even when the other posting carries a lot selector (eg as-+ sets:broker -10 ETSY {2026-01-01} balanced by a bare assets:broker2 post-+ ing, or vice versa).++ A consequence: a disposal entry mistakenly written without a selling price,+ and with the other amount left implicit, looks like a lot transfer, and is+ quietly read as one, without raising an error. If in doubt, print -a shows+ how an entry was read.++ Transfer fees+ If the destination receives less than the source sends (eg because an ex-+ change deducted a fee), record the fee as its own posting in the same com-+ modity, eg expenses:fees 0.001 ETH @ $3000 (or without the price); several+ fee postings which together make up the difference also work. hledger+ reads the fee as a small disposal (consuming lots in the usual cost basis+ method order, before the transfer) and transfers the rest. With a price,+ the fee disposal gets a gain calculated; without one, it doesn't. Other-+ wise, mismatched sent/received totals are an error. print --lots (or print+ -a) shows how the entry was read.++ Conversely, if the destination receives more than the source sends (eg a+ reclaimed fee, or dust from a past bookkeeping error), a fee can't explain+ that, and the extra should be recorded as its own acquisition: give it a+ real or dummy cost basis (or price) annotation, which keeps it out of the+ transfer matching. Eg:++ 2026-05-01 transfer, plus a reclaimed fee+ assets:broker -10 ETH+ assets:broker2 10 ETH+ expenses:fees -0.001 ETH+ assets:broker2 0.001 ETH {$0}++ Transfers recorded in two entries+ A transfer between your own accounts is sometimes recorded twice, once from+ each account's statement, the two entries meeting in a clearing account:++ 2026-01-03 send to wallet A ; from wallet B's statement+ assets:wallet B -0.11 ETH+ assets:transfers 0.10 ETH+ expenses:fees 0.01 ETH++ 2026-01-03 receive from wallet B ; from wallet A's statement+ assets:transfers -0.10 ETH+ assets:wallet A 0.10 ETH++ The receiving entry takes the lots out of the clearing account, so the+ sending entry must be read first (see Lot movements). When each statement+ is imported into its own file, this depends on the order the files are in-+ cluded in. Some ways to make it reliable:++ * Record the transfer as one entry, from one statement, and drop it from+ the other (eg with a skip rule in that account's CSV rules). This is the+ most accurate model of a single event, and doesn't depend on order.++ * Include the sending account's files before the receiving account's. This+ stops working if, on some date, transfers go both ways.++ Dispose+ A negative lot posting sells from one or more existing lots.++ 2026-08-01 sell at a gain+ assets:broker2 -10 ETSY {$50} @ $90 ; selecting the lot by specific identification+ assets:cash $900+ revenues:gain $-400 ; gain can be recorded explicitly or left implicit++ The disposal posting must have a transacted price (the selling price), ei-+ ther explicit or inferred: $90 here.++ One exception: an in-kind disposal, where the entry's non-asset postings+ receive the disposed units (the same commodity, in the same total quantity,+ possibly split across postings), may be priceless. Eg a transfer fee de-+ ducted in the commodity, or an in-kind donation. This is a simple way to+ record such outflows when you don't need a gain calculated: the disposed+ units leave their lot(s) carrying their own cost basis, so the remaining+ units' basis is unchanged, but no gain or loss is recognised, and the re-+ ceiving posting holds unpriced commodity units. To have the gain calcu-+ lated, give the receiving posting a transacted price.++ When the gain posting is inferred, it is calculated from the entry's dis-+ pose postings only (the quantity times the difference between selling price+ and cost basis, summed); acquire postings in the same entry don't con-+ tribute.++ Short positions+ A short position - units sold before they are bought, with the broker lend-+ ing them - is recorded as lots in a liability account (type L, declared or+ inferred from the account name). There the signs are reversed: a negative+ lot posting opens a short lot (it is an acquire, whose cost basis is the+ short-sale price), and a positive lot posting closes it, by buying units+ back (it is a disposal, whose transacted price is the buying price). A+ short lot's gain is its basis minus the buying price, so it is positive+ when the price has fallen:++ commodity XYZ ; lots:++ 2026-01-02 sell short+ liabilities:broker:XYZ -10 XYZ @ $100+ assets:broker:cash++ P 2026-01-31 XYZ $90++ 2026-02-02 cover+ liabilities:broker:XYZ 10 XYZ @ $90+ assets:broker:cash+ revenues:gain++ $ hledger -f short.journal print -x+ 2026-01-02 sell short+ liabilities:broker:XYZ -10 XYZ {$100} @ $100+ assets:broker:cash $1000++ 2026-02-02 cover+ liabilities:broker:XYZ 10 XYZ {2026-01-02, $100} @ $90+ assets:broker:cash $-900+ revenues:gain $-100++ Reports work as for long positions. While the position is open, bs -B+ shows the liability at cost ($1000), offsetting the cash received; bs -V+ shows it at market value ($900), so the net worth includes the unrealised+ gain; bal --gain shows that gain ($100); and holdings shows negative units+ and cost (but no XIRR, which is not meaningful for a short position). Af-+ ter covering, the realised gain is in revenues:gain, and bse balances.++ Everything else is as for lots in asset accounts: cost basis annotations+ and lot subaccounts, lot selectors and cost basis methods, generated or+ user-written gain postings, and lots: NONE to opt out. Note that HIFO cov-+ ers the highest short-sale price first, which realises the largest gain+ first; use SPECID to choose. Long lots and short lots of the same commod-+ ity are separate pools, so they may use different methods.++ Transferring a short position between accounts is not yet supported: cover+ it in one account and open it in the other, with prices. (close --lots can+ move short lots to and from equity, though.) A negative posting in an as-+ set account holding no lots is still an error, since it is usually a mis-+ take.++ Other lot events+ Other real-world events - a gift received with a carryover cost basis,+ bonus shares, a stock split, capitalising an in-kind transfer fee - can be+ recorded as combinations of acquires, transfers and disposals. Other lot+ events on hledger.org has worked examples. The right treatment varies by+ jurisdiction, so check your local tax rules.++ Cost basis methods+ If a lot transfer or a lot disposal doesn't specifically identify the+ lot(s) involved, hledger selects from the available lots automatically, us-+ ing a cost basis method (AKA disposal method / reduction method / booking+ method).++ Use the method your tax jurisdiction requires or allows. The default+ method is FIFO (first in, first out). You can override this with a lots+ tag value on the commodity or account declaration. (An account tag will+ take precedence; on an account, the tag requires a method value.) Eg:++ commodity FUND ; lots: AVERAGE+ account assets:stocks ; lots: LIFO++ These methods are supported:++ Method Lots selected Disposal Error checking+ cost basis+ --------------------------------------------------------------------------------+ SPECID one specific specified A matching lot, with sufficient bal-+ lot lot's cost ance, exists in the account.+ FIFO oldest first each lot's Sufficient lot(s) exist in the ac-+ cost count.+ LIFO newest first each lot's "+ cost+ HIFO highest cost each lot's "+ first cost+ AVERAGE oldest first average cost "+ FIFOALL oldest first each lot's Sufficient lot(s) exist in the ac-+ (all accounts) cost count, and are highest priority+ across all accounts.+ LIFOALL newest first each lot's "+ (all accounts) cost+ HIFOALL highest cost each lot's "+ first (all ac- cost+ counts)+ AVER- oldest first average cost Sufficient lot(s) exist across all+ AGEALL (all accounts) (all ac- accounts.+ counts)++ SPECID (specific identification) is what you're using when a disposal names+ its lot(s), with a lot selector like {2026-01-15, $50} or an explicit lot+ subaccount. Select by date (and label) rather than by cost alone: costs+ shown in lot names may be rounded (see Cost basis precision), so a+ cost-only selector like {$50} can match more lots than intended (an ambigu-+ ity error under SPECID; under other methods, consumed in the method's or-+ der).++ AVERAGE keeps one running average cost per account (pool), recalculated at+ each acquisition and applied to every lot in the pool; disposals use it,+ consuming lots in FIFO order so acquisition dates stay meaningful for hold-+ ing periods. Lot names omit the cost ({2026-01-15}), the average appears+ in the holdings Avg cost column and in disposal postings shown by print -x,+ and transferring lots into or out of the pool carries the average with them+ (a lot's original cost can't be recovered from a pool). close --lots+ writes each lot with the pool's average cost as of the closing date+ ({2026-01-15, $55}), so that its output can be read back, eg to start a new+ file. (print --lots output for AVERAGE lots can't be read back yet.)++ The *ALL variants additionally check that the lots selected are the ones+ that would be chosen across all accounts holding the commodity, and raise+ an error naming the other account otherwise; use them to enforce a global+ disposal order across brokers, exchanges and wallets. Since they involve+ every account, declare them on the commodity, not on accounts. AVERAGEALL+ likewise keeps a single average across all accounts.++ Changing the cost basis method+ hledger recalculates all lots on each run, using the currently declared+ methods. So changing a declared method also reinterprets past history un-+ der the new method. Sometimes that's fine; but usually you'll want past+ disposals to keep their original lot selections and gains (tax authorities+ generally expect a method change to apply only going forward). Things to+ know:++ * Disposals recorded without explicit lot selectors or gain amounts will+ select different lots under the new method, changing their cost bases and+ realised gains.++ * Disposals which do record the old method's selections - as explicit gain+ amounts, lot selectors, lot subaccount names, or balance assertions -+ will be checked against the new method's selections, and any differences+ will be reported as errors.++ hledger doesn't yet support declaring different methods for different time+ periods, but you can make a method change apply only to the future, in ei-+ ther of two ways:++ 1. Make past disposals fully explicit, with lot selectors and gain amounts,+ so they no longer depend on the declared method (print -x and print+ --lots can help with this). Then change the method.++ 2. Or, start a new journal file at the changeover date, using close+ --clopen --lots to carry the current lots into it, and declare the new+ method in the new file.++ Gains+ Each disposal transaction has a gain posting, usually on a Gain-type ac-+ count, recording the capital gain (or loss) as revenue (or negative rev-+ enue). (Following the usual PTA style, a negative number here means+ profit, a positive number means loss.)++ A disposal balances at cost basis, not at transacted cost: the disposed+ units count as their quantity times their cost basis (what they cost you),+ the proceeds are what you received, and the gain posting accounts for the+ difference. Eg selling 5 AAPL bought at $50 for $70 each: -5 AAPL {$50} @+ $70 counts as -$250, $350 is received, and revenues:gain $-100 balances the+ entry. (This is the historical cost accounting convention, and is how+ hledger 1 users have recorded gains. Unrealised gains are not recorded as+ postings, but can be reported from market prices, eg with holdings or+ --gain. Consequently the accounting equation stays balanced through dis-+ posals.)++ The gain posting can be left implicit (and hledger will infer it); or it+ can be written explicitly in the journal. Recording gains below shows ex-+ amples of both.++ In an inferred gain posting, the gain amount will be rounded to the entry's+ local precision for the gain commodity (or if the local precision is zero,+ two decimal digits will be shown - except when both of those digits are+ zero). More decimals can be seen by increasing the display precision (eg+ hledger print --round=soft -c '$1.0000').++ An explicit gain posting can also be written without an amount, in which+ case hledger fills in the calculated gain (as when the gain posting is+ omitted, but with your choice of account). At most one gain posting per+ entry can be left amountless.++ Gain accounts+ The Gain (G) account type is a subtype of Revenue. Declaring an account+ with the G type serves three purposes:++ 1. Recognising gain postings - explicit gain postings which use the G ac-+ count will be detected reliably by account type, and error messages may+ be clearer.++ 2. Customising account names - inferred gain postings will use the+ first-declared G account, rather than the default (revenues:gain). (If+ no account is declared with the G type, they use the alphabetically+ first account whose type is inferred as G, if any.)++ 3. Categorising - when reporting, you can match on the G account type+ specifically.++ G is inferred from conventional English account names (eg revenues:gain,+ income:capital-gains; see the regex table under Account types). You can+ also declare it explicitly:++ account revenues:capital gain ; type: G++ (There is also an UnrealisedGain (U) account type, a subtype of Equity, for+ accounts like equity:unrealised-gain; hledger does not currently generate+ postings to these.)++ Why do we post both gains and losses to a revenue account ? It's more con-+ venient than using separate revenue and expense accounts, and the sign+ keeps things correct.++ Recording gains+ In a disposal entry, you can leave the gain posting out and let hledger in-+ fer it. This is the simplest style, and avoids most problems:++ 2026-02-01 sell+ assets:stocks -1 AAPL {$50} @ $60+ assets:cash $60++ Or you can write it, on an account declared with the G account type.+ hledger then checks your amount against the calculated gain, catching more+ errors:++ account revenues:gain ; type:G++ 2026-02-01 sell+ assets:stocks -1 AAPL {$50} @ $60+ assets:cash $60+ revenues:gain $-10++ Multiple gain postings are allowed, eg one per lot when disposing from sev-+ eral lots.++ Your amount needs to match the calculated gain only at the entry's preci-+ sion (the most decimal places used by the entry's amounts in that commod-+ ity, as in transaction balancing). hledger then uses the exact calculated+ gain, so that the small difference isn't left unaccounted for (with several+ gain postings, it adjusts the last one). print still shows your amount as+ written.++ A written gain posting also protects your history, like a balance asser-+ tion: hledger recalculates lots and gains from the whole journal each time+ it runs, so if a past acquisition is edited, an inferred gain could+ silently change, whereas a written one no longer matches and is reported as+ an error. hledger print -x shows the inferred gain postings, if you want+ to write them into the journal.++ A gain posting on an undeclared account also works: hledger detects it+ heuristically (roughly: a posting to a non-asset/liability/equity account,+ not itself a lot posting, without which the rest of the entry balances).+ But the heuristic fails when the entry has another such posting, eg a fee,+ and the entry is then reported as unbalanced. So if you write gain post-+ ings, declare the account's type. hledger print -a shows what was de-+ tected.++ (Earlier hledger 2 previews also generated an equity:unrealised-gain+ counter posting in each disposal, so that disposals balanced at transacted+ cost. This is no longer done, and such postings, if written explicitly,+ will now leave the entry unbalanced; remove them.)++ Lot reports+ Once lot entries are in the journal, all the usual reports work as normal,+ hiding lot detail by default; --lots shows it. Using the several ways+ journal above (any version):++ holdings gives an overview of your investments: units held, cost, value,+ unrealised and realised gain, and XIRR (see First lots example; add --lots+ for per-lot detail, -e to choose the date).++ balance --lots (or bs --lots) shows the current lots:++ $ hledger bal assets:stocks --lots -N+ 5 AAPL assets:stocks:{2026-01-15, $50}+ 10 AAPL assets:stocks:{2026-02-01, $60}++ Realised gains+ Realised gains are on the Gain-type account (see Gain accounts), so type:G+ queries select them. The total for a period:++ $ hledger bal type:G -p 2026+ $-100 revenues:gain+ --------------------+ $-100++ Each disposal's gain, with a running total:++ $ hledger reg type:G+ 2026-03-01 sell some revenues:gain $-100 $-100++ The disposal entries, with the lots and gain amounts hledger inferred (-x+ shows inferred amounts, --lots the lot subaccounts, -a everything including+ each posting's classification):++ $ hledger print tag:ptype=dispose -x --lots+ 2026-03-01 sell some+ assets:stocks:{2026-01-15, $50} -5 AAPL {2026-01-15, $50} @ $70+ assets:cash $350+ revenues:gain $-100++ When using the roi command with a journal that records lots, make sure+ --pnl matches the gain account, eg:++ $ hledger roi --inv assets:stocks --pnl revenues:gain++ so that realised gains are counted as profit rather than as cash flows out+ of the investment.++ Unrealised gains+ Unrealised gains - on the units you still hold - are not recorded in the+ journal (see Gains); hledger calculates them from market prices when asked.+ Adding some month-end prices to the journal above:++ P 2026-01-31 AAPL $55+ P 2026-02-28 AAPL $65+ P 2026-03-31 AAPL $80++ holdings shows the unrealised gain (UGain) next to the realised gain+ (RGain), per commodity or per lot (--lots), as of today or some other date+ (-e).++ balance --gain shows the unrealised gain per account: the current value of+ the units held, minus what they cost. Like -V, it uses the market price at+ the end of the report period (today, unless you specify -e or a period):++ $ hledger bal assets:stocks --gain+ $350 assets:stocks+ --------------------+ $350++ That is: 15 AAPL are held, which cost $850 and are worth $1200 at $80.+ --lots breaks it down by lot:++ $ hledger bal assets:stocks --gain --lots -N+ $150 assets:stocks:{2026-01-15, $50}+ $200 assets:stocks:{2026-02-01, $60}++ With a report interval, -H shows the unrealised gain as of each period end,+ and without -H, how much it changed during each period:++ $ hledger bal assets:stocks --gain -M -H+ Historical gain in 2026Q1, valued at period ends:++ || 2026-01-31 2026-02-28 2026-03-31+ ===============++====================================+ assets:stocks || $50 $200 $350+ ---------------++------------------------------------+ || $50 $200 $350++ (This is not the same as --valuechange, which shows how much an account's+ value changed in each period, from price movements and from buying and+ selling.)++ --gain needs a market price for the units; where none is found, the units+ are shown unconverted, alongside the negated cost. Realised and unrealised+ gains don't overlap: the gain on units sold is realised, the gain on units+ held is unrealised, and together they are the total gain on the investment+ so far (here, $100 + $350).++ Lot details+ Some finer points, for reference.++ Lot labels+ Internally, each lot is identified by its cost basis date plus an optional+ label. Lots of a commodity acquired on the same date (even in different+ accounts) must have unique labels to help identify them. If you don't pro-+ vide these, hledger adds sequential labels automatically ("0001", "0002",+ ..). Labels are used for sorting, so if you write your own, make them+ sortable.++ Automatic labels depend on which transactions hledger reads, so the same+ lot can get a different label when files are combined (eg yearly files with+ closing and opening balances). If a lot needs a stable label, eg an acqui-+ sition dated to an earlier purchase's date after a split or demerger, write+ your own. Use a descriptive label, eg "demerger", not numbers like "0001",+ which can clash with automatic labels. (More detail: SPEC-lots.)++ Cost basis precision+ An inferred cost basis can be a non-terminating decimal (eg 3 ABC @@ $10+ gives a $10/3 unit cost). hledger keeps such costs at high precision in-+ ternally and calculates gains from the unrounded value, but in lot names it+ displays at most 8 decimal digits, or more if the cost commodity's declared+ display style has more. Two consequences: when lots are carried into a new+ file as text (eg with close --lots), only the displayed digits survive, so+ if you track commodities needing finer cost precision, declare a wider dis-+ play style for the cost commodity up front; and changing a commodity's dis-+ play precision can change how lot names render, so lot selectors written+ with the old rendering will need updating (see Troubleshooting lots). Se-+ lectors using just the date (and label) don't embed a cost, and are unaf-+ fected. (More detail: SPEC-lots.)++ Lot postings and balance assertions+ See also Assertions and lot subaccounts above.++ On a dispose or transfer posting without an explicit lot subaccount, a bal-+ ance assertion always refers to the parent account's balance. So if lot+ subaccounts are added with --lots, the assertion is not affected.++ By contrast, in a journal entry where the lot subaccounts are recorded ex-+ plicitly, a balance assertion refers to the lot subaccount's balance.++ This means that hledger print --lots, if it adds explicit lot subaccounts+ to a journal entry, could potentially change the meaning of balance asser-+ tions, breaking them. To avoid this, in such cases it will move the bal-+ ance assertion to a new zero-amount posting to the parent account (and make+ sure it's subaccount-inclusive). (So eg hledger -f- print --lots -x |+ hledger -f- check assertions will still pass.)++ Troubleshooting lots+ hledger analyses lot entries carefully, but it won't understand every pos-+ sible shape. When it reports a lot-related error, or a report looks wrong:++ * hledger print -a shows how each entry was read: the inferred cost basis,+ lot subaccounts and gain posting, and each posting's classification+ (ptype: acquire, dispose, transfer-from, transfer-to or gain). If an en-+ try was misread, rewrite it more explicitly, eg by adding a cost basis+ annotation, or a transacted cost.++ * "no lots matching ..." means a lot selector matched nothing in that ac-+ count; the error lists the account's actual lots. Common causes: the lot+ is in another account, or a cost-only selector no longer matches the dis-+ played cost (see Cost basis precision; date selectors avoid this).++ * A disposal written without a selling price, with the other amount left+ implicit, is silently read as a transfer. Add the price.++ * "realised gain amount is wrong" means a written gain posting doesn't+ match the calculated gain; the error shows both amounts. Check which+ lots were selected (print -a) and the amounts.++ * "cost basis ... differs from its transacted cost" means an acquisition+ wrote both a {} basis and an @ cost which don't agree. Write just one of+ them, or see Basis and transacted cost must agree for other fixes.++ * "no ... lots available for disposal" means a sale from an account hold-+ ing none of the commodity. If it is a short sale, record it in a liabil-+ ity account (see Short positions). If the purchases were written with+ just an @ cost (common in Ledger journals), they did not create lots; de-+ clare the commodity lotful.++ * For more detail, --debug=5 (eg hledger check --debug=5) traces lot pro-+ cessing step by step. It's verbose, and mostly useful for advanced trou-+ bleshooting or bug reports.++ * To silence lot processing while fixing other problems, use -I or --ig-+ nore-lots.++Generating data+ hledger can enrich the data provided to it, or generate new data, in a num-+ ber of ways. Mostly, this is done only if you request it:++ * Missing amounts, costs, cost basis, and capital gain amounts are inferred+ automatically when possible.++ * Lot subaccounts are also inferred (invisibly by default; --lots makes+ them visible in reports).++ * The --infer-equity flag infers missing conversion equity postings from+ @/@@ costs.++ * The --infer-costs flag infers missing costs from conversion equity post-+ ings.++ * The --infer-market-prices flag infers P price directives from costs.++ * The --auto flag adds extra postings to transactions matched by auto post-+ ing rules.++ * The --forecast option generates transactions from periodic transaction+ rules.++ * The balance --budget report infers budget goals from periodic transaction+ rules.++ * Commands like close, rewrite, and hledger-interest generate transactions+ or postings.++ * CSV data is converted to transactions by applying CSV conversion rules..+ etc.++ Such generated data is temporary, existing only at report time. You can+ convert it to permanent recorded data by, eg, capturing the output of+ hledger print and saving it in your journal file. This can sometimes be+ useful as a data entry aid.++ If you are curious what data is being generated and why, run hledger print+ -a (equivalent to --explicit --lots --verbose-tags). -x/--explicit shows+ inferred amounts and conversion prices, --lots shows lot subaccounts and+ lot-specific postings, and --verbose-tags shows the hidden tags which+ hledger uses for analysing transactions .++Forecasting+ Forecasting, or speculative future reporting, can be useful for estimating+ future balances, or for exploring different future scenarios.++ The simplest and most flexible way to do it with hledger is to manually+ record a bunch of future-dated transactions. You could keep these in a+ separate future.journal and include that with -f only when you want to see+ them.++ --forecast+ There is another way: with the --forecast option, hledger can generate tem-+ porary "forecast transactions" for reporting purposes, according to peri-+ odic transaction rules defined in the journal. Each rule can generate mul-+ tiple recurring transactions, so by changing one rule you can change many+ forecasted transactions.++ Forecast transactions usually start after ordinary transactions end. By+ default, they begin after your latest-dated ordinary transaction, or today,+ whichever is later, and they end six months from today. (The exact rules+ are a little more complicated, and are given below.)++ This is the "forecast period", which need not be the same as the report pe-+ riod. You can override it - eg to forecast farther into the future, or to+ force forecast transactions to overlap your ordinary transactions - by giv-+ ing the --forecast option a period expression argument, like --fore-+ cast=..2099 or --forecast=2023-02-15... Note that the = is required.++ Inspecting forecast transactions+ print is the best command for inspecting and troubleshooting forecast+ transactions. Eg:++ ~ monthly from 2022-12-20 rent+ assets:bank:checking+ expenses:rent $1000++ $ hledger print --forecast --today=2023/4/21+ 2023-05-20 rent+ ; generated-transaction: ~ monthly from 2022-12-20+ assets:bank:checking+ expenses:rent $1000++ 2023-06-20 rent+ ; generated-transaction: ~ monthly from 2022-12-20+ assets:bank:checking+ expenses:rent $1000++ 2023-07-20 rent+ ; generated-transaction: ~ monthly from 2022-12-20+ assets:bank:checking+ expenses:rent $1000++ 2023-08-20 rent+ ; generated-transaction: ~ monthly from 2022-12-20+ assets:bank:checking+ expenses:rent $1000++ 2023-09-20 rent+ ; generated-transaction: ~ monthly from 2022-12-20+ assets:bank:checking+ expenses:rent $1000++ Here there are no ordinary transactions, so the forecasted transactions be-+ gin on the first occurrence after today's date. (You won't normally use+ --today; it's just to make these examples reproducible.)++ Forecast reports+ Forecast transactions affect all reports, as you would expect. Eg:++ $ hledger areg rent --forecast --today=2023/4/21+ Transactions in expenses:rent and subaccounts:+ 2023-05-20 rent as:ba:checking $1000 $1000+ 2023-06-20 rent as:ba:checking $1000 $2000+ 2023-07-20 rent as:ba:checking $1000 $3000+ 2023-08-20 rent as:ba:checking $1000 $4000+ 2023-09-20 rent as:ba:checking $1000 $5000++ $ hledger bal -M expenses --forecast --today=2023/4/21+ Balance changes in 2023-05-01..2023-09-30:++ || May Jun Jul Aug Sep+ ===============++===================================+ expenses:rent || $1000 $1000 $1000 $1000 $1000+ ---------------++-----------------------------------+ || $1000 $1000 $1000 $1000 $1000++ Forecast tags+ Forecast transactions generated by --forecast have a hidden tag, _gener-+ ated-transaction. So if you ever need to match forecast transactions, you+ could use tag:_generated-transaction (or just tag:generated) in a query.++ For troubleshooting, you can add the --verbose-tags flag. Then, visible+ generated-transaction tags will be added also, so you can view them with+ the print command. Their value indicates which periodic rule was responsi-+ ble.++ Forecast period, in detail+ Forecast start/end dates are chosen so as to do something useful by default+ in almost all situations, while also being flexible. Here are (with luck)+ the exact rules, to help with troubleshooting:++ The forecast period starts on:++ * the later of++ * the start date in the periodic transaction rule++ * the start date in --forecast's argument++ * otherwise (if those are not available): the later of++ * the report start date specified with -b/-p/date:++ * the day after the latest ordinary transaction in the journal++ * otherwise (if none of these are available): today.++ The forecast period ends on:++ * the earlier of++ * the end date in the periodic transaction rule++ * the end date in --forecast's argument++ * otherwise: the report end date specified with -e/-p/date:++ * otherwise: 180 days (~6 months) from today.++ Forecast troubleshooting+ When --forecast is not doing what you expect, one of these tips should+ help:++ * Remember to use the --forecast option.++ * Remember to have at least one periodic transaction rule in your journal.++ * Test with print --forecast.++ * Check for typos or too-restrictive start/end dates in your periodic+ transaction rule.++ * Leave at least 2 spaces between the rule's period expression and descrip-+ tion fields.++ * Check for future-dated ordinary transactions suppressing forecasted+ transactions.++ * Try setting explicit report start and/or end dates with -b, -e, -p or+ date:++ * Try adding the -E flag to encourage display of empty periods/zero trans-+ actions.++ * Try setting explicit forecast start and/or end dates with --fore-+ cast=START..END++ * Consult Forecast period, in detail, above.++ * Check inside the engine: add --debug=2 (eg).++Budgeting+ With the balance command's --budget report, each periodic transaction rule+ generates recurring budget goals in specified accounts, and goals and ac-+ tual performance can be compared. See the balance command's doc below.++ You can generate budget goals and forecast transactions at the same time,+ from the same or different periodic transaction rules: hledger bal -M+ --budget --forecast ...++ See also: Budgeting on hledger.org.++Posting types+ hledger detects and tags certain kinds of postings, to help it understand+ complex transactions. Here is quick overview of the posting detection+ rules.++ By default, these tags are hidden (with a _ prefix), so they can be queried+ but they won't appear in print output. To also add visible tags, for trou-+ bleshooting, use print's --verbose-tags or -a/--all flags.++ Tag Detected pattern Effect+ ------------------------------------------------------------------------------------+ con- A pair of adjacent, single-commodity, Helps transaction bal-+ ver- costless postings to Conversion-type ac- ancer infer costs or+ sion-post- counts, with a nearby corresponding avoid redundancy in com-+ ing costful or potentially corresponding modity conversions+ costless posting+ cost-post- A costful posting whose amount and Helps transaction bal-+ ing transacted cost correspond to a conver- ancer infer costs or+ sion postings pair; or a costless post- avoid redundancy in com-+ ing matching one of the pair modity conversions+ gener- Postings generated at runtime Helps users understand+ ated-post- or find postings added+ ing at runtime by hledger+ ptype:ac- Positive postings with lot annotations, Creates a new lot+ quire or in a lotful commodity, with no match-+ ing counterposting (negative, in a lia-+ bility account: a short position)+ ptype:dis- Negative postings with lot annotations, Selects and reduces ex-+ pose or in a lotful commodity, with no match- isting lots+ ing counterposting (positive, in a lia-+ bility account: covering a short posi-+ tion)+ ptype:trans- The negative posting of a pair of coun- Moves lots between ac-+ fer-from terpostings, at least one with lot anno- counts, preserving cost+ tation or a lotful commodity; or a nega- basis+ tive lot posting with an equity counter-+ part (equity transfer)+ ptype:trans- The positive posting of a transfer pair; As above+ fer-to or a positive lot posting with an equity+ counterpart (equity transfer, e.g.+ opening balances)+ ptype:gain In a disposal: a user-written posting to Records the realised+ a Gain-type account (or, failing that, a capital gain/loss; set+ non-asset/liability/equity posting with- aside by the transaction+ out which the entry balances); or the balancer, so the dis-+ realised-gain posting hledger generates posal balances at cost+ basis++PART 5: MORE ABOUT THE COMMAND LINE+Output+ Output destination+ hledger commands send their output to the terminal by default. You can of+ course redirect this, eg into a file, using standard shell syntax:++ $ hledger print > foo.txt++ Some commands (print, register, stats, the balance commands) also provide+ the -o/--output-file option, which does the same thing without needing the+ shell. Eg:++ $ hledger print -o foo.txt+ $ hledger print -o - # write to stdout (the default)++ These commands (except stats) also provide --view, which writes the output+ to a file and opens it in your system's default viewer for that kind of+ file, eg a web browser for HTML. The file is the one given by -o, or else+ view.FMT in hledger's cache directory ($XDG_CACHE_HOME/hledger/ or+ ~/.cache/hledger/, or %LOCALAPPDATA%\hledger\ on Windows), replaced each+ time, and readable only by you (on unix systems). hledger shows the file's+ path; if the report is sensitive, you can delete the file when you're done+ with it, or use -o to save it somewhere else. The output format is HTML+ unless you choose another, with -O or the -o file's extension. Eg:++ $ hledger is -M --chart --view # see an income statement chart and table in a web browser+ $ hledger reg -O csv --view # or a register in a spreadsheet++ To view several reports at once, on one page, use run with --view:++ $ hledger run --view -- is -M --chart -- bs -Q --chart -- reg expenses -p thismonth++ Output format+ Some commands offer other kinds of output, not just text on the terminal.+ Here are those commands and the formats currently supported:++ command txt journal html csv/tsv fods ledger beancount sql json svg+ -----------------------------------------------------------------------------------------------------+ aregister Y Y Y Y Y Y+ balance Y Y Y Y Y Y+ balancesheet Y Y Y Y Y Y+ balancesheete- Y Y Y Y Y Y+ quity+ cashflow Y Y Y Y Y Y+ holdings Y Y Y Y Y+ incomestatement Y Y Y Y Y Y+ print Y Y Y Y Y Y Y Y+ register Y Y Y Y Y Y++ You can also see which output formats a command supports by running hledger+ CMD -h and looking for the -O/--output-format=FMT option,++ You can select the output format by using that option:++ $ hledger print -O csv # print CSV to standard output++ or by choosing a suitable filename extension with the -o/--out-+ put-file=FILE.FMT option:++ $ hledger balancesheet -o foo.csv # write CSV to foo.csv++ The -O option can be combined with -o to override the file extension if+ needed:++ $ hledger balancesheet -o foo.txt -O csv # write CSV to foo.txt++ Here are some notes about the various output formats.++ Text output+ This is the default: human readable, plain text report output, suitable for+ viewing with a monospace font in a terminal. If your data contains unicode+ or wide characters, you'll need a terminal and font that render those cor-+ rectly. (This can be challenging on MS Windows.)++ Some reports (register, aregister) will normally use the full window width.+ If this isn't working or you want to override it, you can use the+ -w/--width option.++ Balance reports (balance, balancesheet, incomestatement...) use whatever+ width they need. Multi-period multi-currency reports can often be wider+ than the window. Besides using a pager, helpful techniques for this situa-+ tion include --layout=bare, -X COMM, cur:, --transpose, --tree, --depth,+ --drop, switching to html output, etc.++ The display style of amounts (symbol placement, decimal and digit group+ marks, number of decimal digits) is inferred per commodity, and can be+ overridden with -c/--commodity-style; see Amount formatting.++ Box-drawing characters+ hledger draws simple table borders by default, to minimise the risk of dis-+ play problems caused by a terminal/font not supporting box-drawing charac-+ ters.++ But your terminal and font probably do support them, so we recommend using+ the --pretty flag to show prettier tables in the terminal. This is a good+ flag to add to your hledger config file.++ Colour+ hledger tries to automatically detect ANSI colour and text styling support+ and use it when appropriate. (Currently, it is used rather minimally: some+ reports show negative numbers in red, and help output uses bold text for+ emphasis.) Colour is not used when the TERM environment variable is dumb,+ or NO_COLOR is set, or output is not going to a colour-capable terminal.++ You can override this by setting the NO_COLOR environment variable to dis-+ able it, or by using the --color/--colour option, perhaps in your config+ file, with a y/yes or n/no value to force it on or off.++ Paging+ In unix-like environments, when displaying large output (in any output for-+ mat) in the terminal, hledger tries to use a pager when appropriate. (You+ can disable this with the --pager=no option, perhaps in your config file.)++ The pager shows one page of text at a time, and lets you scroll around to+ see more. While it is active, usually SPACE shows the next page, h shows+ help, and q quits. The home/end/page up/page down/cursor keys, and mouse+ scrolling, may also work.++ hledger will use the pager specified by the PAGER environment variable,+ otherwise less if available, otherwise more if available. (With one excep-+ tion: hledger help -p TOPIC will always use less, so that it can scroll to+ the topic.)++ The pager is expected to display hledger's ANSI colour and text styling.+ If you see junk characters, you might need to configure your pager to han-+ dle ANSI codes. Or you could disable colour as described above.++ If you are using the less pager, hledger tries to provide a consistently+ pleasant experience by running it with some extra options added to your+ LESS environment variable:++ --chop-long-lines --hilite-unread --ignore-case --no-init+ --quit-if-one-screen --shift=8 --squeeze-blank-lines --use-backslash++ and when colour output is enabled:++ --RAW-CONTROL-CHARS++ You can prevent this by setting your preferred options in the HLEDGER_LESS+ variable, which will be used instead of LESS.++ HTML output+ HTML output has some default styling built in; eg, it prevents wrapping+ within dates and individual commodity amounts. It can be customised (or+ overridden) by an optional hledger.css file in the same directory (there is+ a sample in the hledger repo).++ With --chart, commands that can show charts show one (as inline SVG), with+ the text report collapsed below it (see Balance charts).++ HTML output will be a HTML fragment, not a complete HTML document. It has+ a newline after each table row, for readability. Like other hledger out-+ put, for non-ascii characters it will use the system locale's text encoding+ (see Text encoding).++ CSV / TSV output+ In CSV or TSV output, digit group marks (such as thousands separators) are+ disabled automatically.++ FODS output+ FODS is the OpenDocument Spreadsheet format as plain XML, as read by Libre-+ Office and OpenOffice. For those spreadsheet applications it is better+ than CSV. It works across locales: decimal point or comma, and the charac-+ ter encoding is stored in the XML header, so non-ascii text is safe. It+ supports fixed header rows and columns, cell types (string, number, date),+ styles (bold) and borders. And it keeps number and currency separate, so+ amounts show their currency but remain numbers usable in formulas. You can+ still extract CSV from FODS/ODS if needed, with utilities like libreoffice+ --headless or ods2csv.++ ODS supports only the locale's thousands separator as a digit group mark,+ so FODS output enables thousands separators if your commodity style has any+ digit groups.++ Ledger output+ This is a Ledger-specific journal format supported by the print command.+ It is currently identical to hledger's default print output except that+ cost basis annotations will use Ledger's syntax, ({COST} [DATE] (NOTE)),+ not hledger's ({DATE, "LABEL", COST}). With print --export, directives and+ comments are also reproduced, and directives which Ledger does not support+ are commented out.++ Beancount output+ This is Beancount's journal format, supported by the print command. You+ can use this to export your hledger data to Beancount, eg to use the Fava+ web app.++ hledger will try to adjust your data to suit Beancount, automatically. By+ default only transactions are converted; with print --export, the options+ and commodity, open and price directives Beancount needs are generated too,+ and top-level comments are converted, so the output can be read by Bean-+ count directly. Be cautious and check the conversion until you are confi-+ dent it is good. If you plan to export to Beancount often, you may want to+ follow its conventions, for a cleaner conversion:++ * use Beancount-friendly account names++ * use currency codes instead of currency symbols++ * use cost notation instead of equity conversion postings++ * avoid virtual postings, balance assignments, and secondary dates.++ There is one big adjustment: for Beancount, the top level account names+ must be Assets, Liabilities, Equity, Income, and/or Expenses. A top level+ hledger account named revenue or revenues (case insensitive) will be con-+ verted to Income. Any other top level account whose account type is known+ (declared or inferred) will have the corresponding Beancount top level ac-+ count prepended; eg with account bonds ; type:A, bonds:treasury becomes+ Assets:Bonds:Treasury. Otherwise, you should use --alias (see --alias op-+ tion, or this hledger2beancount.conf file).++ Other adjustments hledger makes:++ * Account names: aside from the top-level names, hledger makes valid Bean-+ count account names by capitalising each part, replacing spaces and un-+ derscores with -, replacing other unsupported characters with+ C<HEXBYTES>, prepending A to parts which don't begin with a letter or+ digit, and appending :A to account names which have only one part.++ * Commodity names: hledger makes valid Beancount commodity/currency names,+ which must be 2-24 uppercase letters, digits, or ', ., _, -, beginning+ with a letter and ending with a letter or digit. Known currency symbols+ become ISO 4217 currency codes; otherwise letters are capitalised, spaces+ become -, other unsupported characters become C<HEXBYTES>, and C is+ prepended or appended if needed. One-letter symbols are doubled, and the+ no-symbol commodity becomes CC. (hledger tries to keep your commodities+ distinct, but collisions are possible with short symbols like CC, C and+ no-symbol, which are distinct in hledger but all become CC in Beancount.)++ * Balance assignments are not supported by Beancount, so they are converted+ to explicit amounts.++ * Virtual postings are not allowed by Beancount, so any virtual postings+ are omitted.++ * Tags become Beancount metadata (except tags whose name begins with _).+ Metadata names are adjusted to be Beancount-compatible: beginning with a+ lowercase letter, at least two characters long, with unsupported charac-+ ters encoded; values use Beancount's string type. A tag repeated with+ multiple values (eg an account with both type:Asset and type:Cash) be-+ comes one metadata entry with the values comma separated: type: "Asset,+ Cash".++ * Costs: Beancount doesn't allow redundant costs and conversion postings as+ hledger does; if you have any, the conversion postings are omitted. Cur-+ rently at most one cost + conversion postings group per transaction is+ supported.++ * Directives: with print --export, hledger generates a commodity directive+ for each declared commodity, and an open directive for each declared or+ used account, dated on the account's earliest posting (or the earliest+ transaction date). Account and commodity tags become metadata on these+ directives, and an account's lots: tag becomes its Beancount booking+ method. Other hledger directives have no Beancount equivalent and are+ dropped.++ * Tolerance: with print --export, a sample inferred_tolerance_default op-+ tion is provided, commented out. If Beancount complains that transac-+ tions aren't balanced, this is an easy workaround.++ * Operating currency: declaring one or more improves Beancount and Fava re-+ ports. With print --export, hledger declares each currency used in cost+ amounts as an operating currency. If needed, replace these with your own+ declaration, like option "operating_currency" "USD".++ SQL output+ SQL output is expected to work at least with SQLite, MySQL and Postgres.++ The SQL statements are expected to be executed in the empty database. If+ you already have tables created via SQL output of hledger, you would proba-+ bly want to either clear data from these (via delete or truncate SQL state-+ ments) or drop the tables completely before import; otherwise your postings+ would be duplicated.++ For SQLite, it is more useful if you modify the generated id field to be a+ PRIMARY KEY. Eg:++ $ hledger print -O sql | sed 's/id serial/id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL/g' | ...++ JSON output+ Our JSON is rather large and verbose, since it is a faithful representation+ of hledger's internal data types. To understand its structure, read the+ Haskell type definitions, which are mostly in+ https://github.com/hledgerorg/hledger/blob/main/hledger-lib/Hledger/Data/Types.hs.+ hledger-web's OpenAPI specification may also be relevant.++ hledger stores numbers with sometimes up to 255 significant digits. This+ is too many digits for most JSON consumers, so in JSON output we round num-+ bers to at most 10 decimal places. (We don't limit the number of integer+ digits.) Related: #1195++ SVG output+ SVG output shows a chart of the report, rather than the report's table (as+ the --chart flag does with text output; see Balance charts). It is a+ self-contained image file, viewable in web browsers and many image viewers.+ It has a light and a dark colour scheme, chosen by the viewer's preference,+ and tooltips showing each bar's or point's values. Currently the aregis-+ ter, balance, balancesheet, balancesheetequity, cashflow, incomestatement+ and register commands can produce it. Eg:++ $ hledger bal -M expenses -o expenses.svg++ Debug output+ We intend hledger to be relatively easy to troubleshoot, introspect and de-+ velop. You can add --debug[=N] to any hledger command line to see addi-+ tional debug output. N ranges from 1 (least output, the default) to 9+ (maximum output). Typically you would start with 1 and increase until you+ are seeing enough. At level 1 or higher, the output includes timing lines,+ showing the run time and memory allocation of each phase of hledger's work:+ reading and parsing data, each stage of journal finalising, and running the+ command. These can show where the time goes when processing a large jour-+ nal. Debug output goes to stderr, and is not affected by -o/--output-file+ (unless you redirect stderr to stdout, eg: 2>&1). It will be interleaved+ with normal output, which can help reveal when parts of the code are evalu-+ ated. To capture debug output in a log file instead, you can usually redi-+ rect stderr, eg:++ hledger bal --debug=3 2>hledger.log++ (This option doesn't work in a config file yet.)++ Built-in tests+ hledger's unit tests are built in to the executable, and --test runs them,+ printing the results and exiting with a non-zero code if any fail.+ --test=PATTERN runs just the tests whose names contain PATTERN (it can also+ be a tasty pattern). Eg:++ $ hledger --test # run all unit tests+ $ hledger --test=balance # run tests with "balance" in their name++ This can be a sanity check of an unusual hledger build; failures are un-+ likely, but if you see one, please report it as a bug. (hledger-web also+ has a --test flag, which runs its own tests.)++Charts+ hledger can show many reports as a chart: add --chart to a balance, bal-+ ancesheet, balancesheetequity, cashflow, incomestatement, aregister, regis-+ ter or holdings report. (The activity command always shows one.) A suit-+ able kind of chart is chosen for the report: eg stacked bars per period for+ balance changes, lines for balances over time, or a bar per account for a+ single period. In the terminal the chart is drawn with text characters,+ filling the terminal's width (or the width set by -w):++ $ hledger bal -Q expenses income --chart -w 50+ Balance changes in 2008:++ a expenses:food a expenses:supplies+ a income:gifts a income:salary++ 2008Q1 $-1 aaaaaaaaaaaaa+ 2008Q2 $1 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa+ 2008Q3 0 a+ 2008Q4 0 a++ With SVG output (eg -o chart.svg) it is a graphical chart; with HTML output+ it is shown with the report's table collapsed below it; and with CSV, TSV+ or JSON output you get the chart's data. To see a graphical chart quickly,+ add --view, eg hledger is -M --chart --view. --chart also accepts a chart+ kind, net (to draw the net total, which charts leave out by default), and a+ fixed scale, eg to compare charts. For the details, see Balance charts,+ aregister, Register charts and Holdings charts.++Command line tips+ Here are some tips for using hledger at the command line; feel free to skip+ these until you need them.++ Special characters+ In commands you type at the command line, certain characters have special+ meaning and sometimes need to be "escaped" or "quoted", by prefixing back-+ slashes or enclosing in quotes.++ If you are able to minimise the use of special characters in your data, you+ won't have to deal with this as much. For example, you could use hyphen -+ or underscore _ instead of spaces in account names, and you could use the+ USD currency code instead of the $ currency symbol in amounts.++ But if you prefer to use spaced account names and $, it's fine. Just be+ aware of this topic so you can check this doc when needed. (These examples+ are mostly tested on unix; some details might need to be adapted if you're+ on Windows.)++ Escaping shell special characters+ These are some characters which may have special meaning to your shell (the+ program which interprets command lines):++ * SPACE, <, >, (, ), |, \, %++ * $ if followed by a word character++ So for example, to match an account name containing spaces, like "credit+ card", don't write:++ $ hledger register credit card++ Instead, enclose the name in single quotes:++ $ hledger register 'credit card'++ On unix or in Windows powershell, if you use double quotes your shell will+ silently treat $ as variable interpolation. So you should probably avoid+ double quotes, unless you want that behaviour, eg in a script:++ $ hledger register "assets:$SOMEACCT"++ But in an older Windows CMD.EXE window, you must use double quotes:++ C:\Users\Me> hledger register "credit card"++ On unix or in Windows powershell, as an alternative to quotes you can write+ a backslash before each special character:++ $ hledger register credit\ card++ Finally, since hledger's query arguments are regular expressions (described+ below), you could also fill that gap with . which matches any character:++ $ hledger register credit.card++ Escaping regular expression special characters+ Some characters also have special meaning in regular expressions, which+ hledger's arguments often are. Those include:++ * ., ^, $, [, ], (, ), |, \++ To escape one of these, write \ before it. But note this is in addition to+ the shell escaping above. So for characters which are special to both+ shell and regular expressions, like \ and $, you will sometimes need two+ levels of escaping.++ For example, a balance report that uses a cur: query restricting it to just+ the $ currency, should be written like this:++ $ hledger balance cur:\\$++ Explanation:++ 1. Add a backslash \ before the dollar sign $ to protect it from regular+ expressions (so it will be matched literally with no special meaning).++ 2. Add another backslash before that backslash, to protect it from the+ shell (so the shell won't consume it).++ 3. $ doesn't need to be protected from the shell in this case, because it's+ not followed by a word character; but it would be harmless to do so.++ But here's another way to write that, which tends to be easier: add back-+ slashes to escape from regular expressions, then enclose with quotes to es-+ cape from the shell:++ $ hledger balance cur:'\$'++ Escaping in other situations+ hledger options and arguments are sometimes used in places other than the+ command line, where the escaping/quoting rules are different. For example,+ backslash-quoting may not be available. Here's a quick reference:++ In unix shell Use single quotes and/or backslash (or double quotes+ for variable interpolation)+ In Windows power- Use single quotes (or double quotes for variable in-+ shell terpolation)+ In Windows cmd Use double quotes+ In hledger-ui's Use single or double quotes+ filter prompt+ In hledger-web's Use single or double quotes+ search form+ In an argument Don't use spaces, don't shell-escape, do regex-es-+ file cape, write one argument/option per line+ In a config file Use single or double quotes, enclosing all or part+ of an argument ('desc:a b' or desc:'a b', as in the+ unix shell)+ In repl or a run Use single or double quotes, enclosing all or part+ script of an argument+ In ghci (the Use double quotes, and enclose the whole argument+ Haskell REPL)++ Unicode characters+ hledger is expected to handle non-ascii characters correctly:++ * they should be parsed correctly in input files and on the command line,+ by all hledger tools (add, iadd, hledger-web's search/add/edit forms,+ etc.)++ * they should be displayed correctly by all hledger tools, and on-screen+ alignment should be preserved.++ This requires a well-configured environment. Here are some tips:++ * A system locale must be configured, which can decode the characters being+ used. This is essential - see Text encoding and Install: Text encoding.++ * Your terminal software (eg Terminal.app, iTerm, CMD.exe, xterm..) must+ support unicode. On Windows, you may need to use Windows Terminal.++ * The terminal must be using a font which includes the required unicode+ glyphs.++ * The terminal should be configured to display wide characters as double+ width (for report alignment).++ * On Windows, for best results you should run hledger in the same kind of+ environment in which it was built. Eg hledger built in the standard+ CMD.EXE environment (like the binaries on our download page) might show+ display problems when run in a cygwin or msys terminal, and vice versa.+ (See eg #961).++ Regular expressions+ A regular expression (regexp) is a small piece of text where certain char-+ acters (like ., ^, $, +, *, (), |, [], \) have special meanings, forming a+ tiny language for matching text precisely - very useful in hledger and+ elsewhere. To learn all about them, visit regular-expressions.info.++ hledger supports regexps whenever you are entering a pattern to match some-+ thing, eg in query arguments, account aliases, CSV if rules, hledger-web's+ search form, hledger-ui's / search, etc. You may need to wrap them in+ quotes, especially at the command line (see Special characters above).+ Here are some examples:++ Account name queries (quoted for command line use):++ Regular expression: Matches:+ ------------------- ------------------------------------------------------------+ bank assets:bank, assets:bank:savings, expenses:art:banksy, ...+ :bank assets:bank:savings, expenses:art:banksy+ :bank: assets:bank:savings+ '^bank' none of those ( ^ matches beginning of text )+ 'bank$' assets:bank ( $ matches end of text )+ 'big \$ bank' big $ bank ( \ disables following character's special meaning )+ '\bbank\b' assets:bank, assets:bank:savings ( \b matches word boundaries )+ '(sav|check)ing' saving or checking ( (|) matches either alternative )+ 'saving|checking' saving or checking ( outer parentheses are not needed )+ 'savings?' saving or savings ( ? matches 0 or 1 of the preceding thing )+ 'my +bank' my bank, my bank, ... ( + matches 1 or more of the preceding thing )+ 'my *bank' mybank, my bank, my bank, ... ( * matches 0 or more of the preceding thing )+ 'b.nk' bank, bonk, b nk, ... ( . matches any character )++ Some other queries:++ desc:'amazon|amzn|audible' Amazon transactions+ cur:EUR amounts with commodity symbol EUR+ cur:\\$ amounts with commodity symbol $+ cur:....? amounts with 3- or 4-character symbols+ tag:.=202[1-3] things with any tag whose value contains 2021, 2022 or 2023++ Account name aliases: accept . instead of : as account separator:++ alias /\./=: replaces all periods in account names with colons++ Show multiple top-level accounts combined as one:++ --alias='/^[^:]+/=combined' ( [^:] matches any character other than : )++ Show accounts with the second-level part removed:++ --alias '/^([^:]+):[^:]+/ = \1'+ match a top-level account and a second-level account+ and replace those with just the top-level account+ ( \1 in the replacement text means "whatever was matched+ by the first parenthesised part of the regexp"++ CSV rules: match CSV records containing dining-related MCC codes:++ if \?MCC581[124]++ Match CSV records with a specific amount around the end/start of month:++ if %amount \b3\.99+ & %date (29|30|31|01|02|03)$++ hledger's regular expressions+ hledger's regular expressions come from the regex-tdfa library. If they're+ not doing what you expect, it's important to know exactly what they sup-+ port:++ 1. they are case insensitive++ 2. they are infix matching (they do not need to match the entire thing be-+ ing matched)++ 3. they are POSIX ERE (extended regular expressions)++ 4. they also support GNU word boundaries (\b, \B, \<, \>)++ 5. backreferences are supported when doing text replacement in account+ aliases or CSV rules, where backreferences can be used in the replace-+ ment string to reference capturing groups in the search regexp. Other-+ wise, if you write \1, it will match the digit 1.++ 6. they do not support lazy quantifiers (*?), mode modifiers ((?s)), char-+ acter classes (\w, \d), or anything else not mentioned above.++ 7. they may not (I'm guessing not) properly support right-to-left or bidi-+ rectional text.++ Some things to note:++ * In the alias directive and --alias option, regular expressions must be+ enclosed in forward slashes (/REGEX/). Elsewhere in hledger, these are+ not required.++ * In queries, to match a regular expression metacharacter like $ as a lit-+ eral character, prepend a backslash. Eg to search for amounts with the+ dollar sign in hledger-web, write cur:\$.++ * On the command line, some metacharacters like $ have a special meaning to+ the shell and so must be escaped at least once more. See Special charac-+ ters.++ Argument files+ You can save a set of command line options and arguments in a file, and+ then use them by writing @FILE.args as a hledger command argument. The+ .args file extension is conventional, but not required. In an argument+ file,++ * Each line can contain one argument, flag, or option.++ * Blank lines or lines beginning with # are ignored.++ * An option's flag and value should be joined by =.++ * An option value or an argument may contain spaces. Don't use single or+ double quotes.++ * And generally, use one less level of quoting/escaping than at the command+ line. Eg cur:\$, not cur:\\$ as on the command line.++ For example:++ # cash.args++ assets:cash+ assets:charles schwab:sweep+ cur:\$+ -c=$1.++ $ hledger bal @cash.args++ Shell completions+ If you use the bash, zsh or fish shells, you can optionally set up con-+ text-sensitive autocompletion for hledger command lines. Try pressing+ hledger<SPACE><TAB><TAB> (should list all hledger commands) or hledger reg+ acct:<TAB><TAB> (should list your top-level account names). If completions+ aren't working, or for more details, see Install > Shell completions.++PART 6: COMMON TASKS+ For a gentle, step by step introduction to hledger - installing, starting a+ journal, recording transactions, and running the main reports - see hledger+ by example on the website. For a faster tour, see the 5 minute quick+ start. Here are a few more tasks which aren't covered there.++Setting LEDGER_FILE+ hledger looks for your accounting data in a journal file,+ $HOME/.hledger.journal by default. You can override this by setting the+ LEDGER_FILE environment variable (see Environment), eg to ~/fi-+ nance/main.journal. Here's how to do that on different systems:++ Set LEDGER_FILE on unix+ It depends on your shell, but running these commands in the terminal will+ work for many people; adapt if needed:++ $ echo 'export LEDGER_FILE=~/finance/main.journal' >> ~/.profile+ $ source ~/.profile++ When correctly configured:++ * env | grep LEDGER_FILE will show your new setting++ * and so should hledger setup and hledger files.++ Set LEDGER_FILE on mac+ In a terminal window, follow the unix procedure above.++ Note GUI applications started from the Dock or Spotlight, such as a GUI+ Emacs, don't see variables set in your shell profile. If needed, you can+ set the variable for them too, until the next reboot, with launchctl setenv+ LEDGER_FILE ~/finance/main.journal (then restart the application).++ Set LEDGER_FILE on Windows+ It can be easier to create a default file at C:\Users\USER\.hledger.jour-+ nal, and have it include your other files. See I'm on Windows, how do I+ keep my files in AppData\Roaming ?++ Otherwise: using the gui is easiest:++ 1. In task bar, search for environment variables, and choose "Edit environ-+ ment variables for your account".++ 2. Create or change a LEDGER_FILE setting in the User variables pane. A+ typical value would be C:\Users\USER\finance\main.journal.++ 3. Click OK to complete the change.++ 4. And open a new powershell window. (Existing windows won't see the+ change.)++ Or at the command line, you can do it this way:++ 1. In a powershell window, run [Environment]::SetEnvironmentVari-+ able("LEDGER_FILE", "C:\User\USER\finance\main.journal", [System.Envi-+ ronmentVariableTarget]::User)++ 2. And open a new powershell window. (Existing windows won't see the+ change.)++ Other methods you may find online are often unreliable: they may not per-+ sist, may not affect the current window, or may need administrator rights+ or a newer powershell. If you still have trouble, see eg Setting Windows+ PowerShell environment variables or Adding path permanently to windows us-+ ing powershell doesn't appear to work.++ When correctly configured:++ * in a new powershell window, $env:LEDGER_FILE will show your new setting++ * and so should hledger setup and (once the file exists) hledger files.++Reconciling+ Periodically you should reconcile - compare your hledger-reported balances+ against external sources of truth, like bank statements or your bank's web-+ site - to be sure that your ledger accurately represents the real-world+ balances (and, that the real-world institutions have not made a mistake!).+ This gets easy and fast with (1) practice and (2) frequency. If you do it+ daily, it can take 2-10 minutes. If you let it pile up, expect it to take+ longer as you hunt down errors and discrepancies.++ A typical workflow:++ 1. Reconcile cash. Count what's in your wallet. Compare with what hledger+ reports (hledger bal cash). If they are different, try to remember the+ missing transaction, or look for the error in the already-recorded+ transactions. A register report can be helpful (hledger reg cash). If+ you can't find the error, add an adjustment transaction. Eg if you have+ $105 in your wallet but hledger says $107, and can't explain the missing+ $2, it could be:++ 2023-01-16 * adjust cash+ assets:cash $-2 = $105+ expenses:misc++ 2. Reconcile checking. Log in to your bank's website. Compare today's+ (cleared) balance with hledger's cleared balance (hledger bal checking+ -C). If they are different, track down the error or record the missing+ transaction(s) or add an adjustment transaction, similar to the above.+ Unlike the cash case, you can usually compare the transaction history+ and running balance from your bank with the one reported by hledger reg+ checking -C. This will be easier if you generally record transaction+ dates quite similar to your bank's clearing dates.++ 3. Repeat for other asset/liability accounts.++ Tip: an institution's numbers can be rounded differently in different+ places - its website, its CSV or other exports, its emailed and paper+ statements. Choose one as your reference (usually the official statement),+ and aim to reproduce its numbers: adjust hledger's display precision with+ -c or --round (see Display rounding), and record any small remaining dif-+ ferences with an adjustment transaction, eg to an expenses:rounding ac-+ count.++ Tip: instead of the register command, use hledger-ui to see a live-updating+ register while you edit the journal: hledger-ui --register checking -C++ After reconciling, it could be a good time to mark the reconciled transac-+ tions' status as "cleared and confirmed", if you want to track that, by+ adding the * marker after the date.++ If you're using version control, this can be a good time to commit:++ $ git commit -m 'txns' 2023.journal++Closing a journal file+ At the end of the year, you may want to continue your journal in a new+ file, so that old transactions don't slow down or clutter your reports, and+ to help ensure the integrity of your accounting history. See the close+ command.++ If using version control, don't forget to git add the new file.++hledger 1 and hledger 2+ hledger 2 (the 1.99.x previews, and 2.0 when released) reads hledger 1+ data, and most hledger 1 journals work unchanged. hledger 1 (1.52.x) con-+ tinues to receive essential fixes, and both can be installed side by side+ (eg by renaming the hledger 1 executable to hledger1).++ To upgrade from hledger 1:++ 1. Back up your data files, or commit them to version control.++ 2. Run hledger check with hledger 2. If you import CSV, also run your+ usual import command with --dry-run.++ 3. Compare your usual reports with hledger 1's (eg hledger1 bs and hledger+ bs), and investigate any differences.++ Things that can need attention include cost basis annotations like {$50},+ which hledger 1 ignored but hledger 2 uses to track lots, and a few checks+ that are now stricter. Upgrading to hledger 2 describes them all, with+ fixes, and how to switch back, or keep data usable with both versions.++BUGS+ We welcome bug reports in the hledger issue tracker+ (https://bugs.hledger.org), or on the hledger chat or mail list+ (https://hledger.org/support).++ Some known issues and limitations:++ hledger uses the system's text encoding when reading non-ascii text. If no+ system encoding is configured, or if the data's encoding is different,+ hledger will give an error. (See Text encoding and Troubleshooting.)++ On Microsoft Windows, depending what kind of terminal window you use,+ non-ascii characters, ANSI text formatting, and/or the add command's TAB+ key, may not be fully supported. (For best results, try a powershell win-+ dow.)++ When showing colour, hledger sometimes asks the terminal for its background+ colour, to choose colours that suit it (for headings, and for charts in+ terminals advertising 24-bit colour). Occasionally this can misbehave: a+ terminal that doesn't answer (eg some tmux setups) can delay the output by+ up to half a second; over a slow connection, a late answer may appear as+ stray characters at your shell prompt; on macOS, hledger can hang if its+ input is explicitly redirected from /dev/tty; and hledger may be stopped if+ it is run in the background. --color=no avoids these.++ When processing large data files, hledger uses more memory than Ledger.+ You can cap its memory use with GHC runtime system options, eg hledger +RTS+ -M2G -RTS ... (if it needs more, it will stop with an error), and see mem-+ ory and garbage collection statistics with +RTS -s -RTS. To use less mem-+ ory at some cost in speed, add +RTS -c -RTS to use the compacting garbage+ collector; on large journals this can reduce memory use by 20-40%, while+ running 40-60% slower. (A RTS -M limit also enables this automatically, as+ memory use approaches the limit.) A multi-period report with more than+ 10,000 periods, or a --forecast that would generate more than 100,000+ transactions (which in practice means a mistyped date somewhere, making the+ report or the forecast span thousands of years), prints a warning before+ starting, since it may need a lot of memory, so that you can cancel it.++ Troubleshooting+ Here are some common issues you might encounter when you run hledger, and+ how to resolve them (and remember also you can usually get quick Support):++ PATH issues: I get an error like "No command 'hledger' found"+ Depending how you installed hledger, the executables may not be in your+ shell's PATH. Eg on unix systems, stack installs hledger in ~/.local/bin+ and cabal installs it in ~/.cabal/bin. You may need to add one of these+ directories to your shell's PATH, and/or open a new terminal window.++ LEDGER_FILE issues: I configured LEDGER_FILE but hledger is not using it++ * LEDGER_FILE should be a real environment variable, not just a shell vari-+ able. Eg on unix, the command env | grep LEDGER_FILE should show it.+ You may need to use export (see https://stackoverflow.com/a/7411509). On+ Windows, $env:LEDGER_FILE should show it.++ * You may need to force your shell to see the new configuration. A simple+ way is to close your terminal window and open a new one.++ Text decoding issues: I get errors like "Illegal byte sequence" or "Invalid+ or incomplete multibyte or wide character" or "commitAndReleaseBuffer: in-+ valid argument (invalid character)"+ hledger usually needs its input to be decodable with the system locale's+ text encoding. See Text encoding and Install: Text encoding.++ COMPATIBILITY ISSUES: hledger gives an error with my Ledger file+ Not all of Ledger's journal file syntax or feature set is supported. See+ hledger and Ledger for full details.++++AUTHORS+ Simon Michael <simon@joyful.com> and contributors.+ See http://hledger.org/CREDITS.html+++COPYRIGHT+ Copyright 2007-2023 Simon Michael and contributors.+++LICENSE+ Released under GNU GPL v3 or later.+++SEE ALSO+ hledger(1), hledger-ui(1), hledger-web(1), ledger(1)++hledger-2.0 December 2026 HLEDGER(1)
− hledger-cli.hs
@@ -1,6 +0,0 @@-#!/usr/bin/env runhaskell--- the hledger command-line executable; see Hledger/Cli/Main.hs--module Main (main)-where-import Hledger.Cli.Main (main)
hledger.cabal view
@@ -1,128 +1,377 @@-name: hledger-version: 0.16.1-category: Finance-synopsis: The main command-line interface for the hledger accounting tool.-description:- hledger is a library and set of user tools for working- with financial data (or anything that can be tracked in a- double-entry accounting ledger.) It is a haskell port and- friendly fork of John Wiegley's Ledger. hledger provides- command-line, curses and web interfaces, and aims to be a- reliable, practical tool for daily use.+cabal-version: 2.2 -license: GPL-license-file: LICENSE+-- This file has been generated from package.yaml by hpack version 0.39.6.+--+-- see: https://github.com/sol/hpack++name: hledger+version: 2.0+synopsis: Command-line interface for the hledger accounting system+description: The command-line interface for the hledger accounting system.+ Its basic function is to read a plain text file describing+ financial transactions and produce useful reports.+ .+ hledger is a robust, cross-platform set of tools for tracking money,+ time, or any other commodity, using double-entry accounting and a+ simple, editable file format, with command-line, terminal and web+ interfaces. It is a Haskell rewrite of Ledger, and one of the leading+ implementations of Plain Text Accounting. Read more at:+ <https://hledger.org>+category: Finance, Console+stability: stable+homepage: http://hledger.org+bug-reports: http://bugs.hledger.org author: Simon Michael <simon@joyful.com> maintainer: Simon Michael <simon@joyful.com>-homepage: http://hledger.org-bug-reports: http://code.google.com/p/hledger/issues-stability: beta-tested-with: GHC==6.12, GHC==7.0-cabal-version: >= 1.8+license: GPL-3.0-or-later+license-file: LICENSE build-type: Simple--- data-dir: data--- data-files:-extra-tmp-files:+tested-with:+ ghc==9.6.7, ghc==9.8.4, ghc==9.10.3, ghc==9.12.4, ghc==9.14.1 extra-source-files:---- Cabal-Version: >= 1.9.2--- Test-Suite test-hledger--- type: exitcode-stdio-1.0--- main-is: test-hledger.hs--- build-depends: base+ CHANGES.md+ README.md+ quickref.txt+ shell-completion/hledger-completion.bash+ test/unittest.hs+ embeddedfiles/hledger-accounts.md+ embeddedfiles/hledger-add.md+ embeddedfiles/hledger-aregister.md+ embeddedfiles/hledger-balance.md+ embeddedfiles/hledger-balancesheet.md+ embeddedfiles/hledger-import.md+ embeddedfiles/hledger-incomestatement.md+ embeddedfiles/hledger-print.md+ embeddedfiles/hledger-ui.md+ embeddedfiles/hledger-web.md+ embeddedfiles/hledger.md+ embeddedfiles/hledger.1+ embeddedfiles/hledger.txt+ embeddedfiles/hledger.info+ embeddedfiles/hledger-ui.1+ embeddedfiles/hledger-ui.txt+ embeddedfiles/hledger-ui.info+ embeddedfiles/hledger-web.1+ embeddedfiles/hledger-web.txt+ embeddedfiles/hledger-web.info+ embeddedfiles/file-layouts/simple/main.journal+ embeddedfiles/file-layouts/default/main.journal+ embeddedfiles/file-layouts/default/accounts.journal+ embeddedfiles/file-layouts/default/commodities.journal+ embeddedfiles/file-layouts/default/payees.journal+ embeddedfiles/file-layouts/default/data/getdata+ embeddedfiles/file-layouts/default/data/bankofireland-checking.csv+ embeddedfiles/file-layouts/default/data/archive/README.md+ embeddedfiles/file-layouts/default/prices/getprices+ embeddedfiles/file-layouts/default/rules/bankofireland-checking.csv.rules+ embeddedfiles/file-layouts/years/2026.journal+ embeddedfiles/file-layouts/years/all.journal+ Hledger/Cli/Commands/Accounts.txt+ Hledger/Cli/Commands/Activity.txt+ Hledger/Cli/Commands/Add.txt+ Hledger/Cli/Commands/Aregister.txt+ Hledger/Cli/Commands/Balance.txt+ Hledger/Cli/Commands/Balancesheet.txt+ Hledger/Cli/Commands/Balancesheetequity.txt+ Hledger/Cli/Commands/Cashflow.txt+ Hledger/Cli/Commands/Check.txt+ Hledger/Cli/Commands/Close.txt+ Hledger/Cli/Commands/Codes.txt+ Hledger/Cli/Commands/Commodities.txt+ Hledger/Cli/Commands/Descriptions.txt+ Hledger/Cli/Commands/Diff.txt+ Hledger/Cli/Commands/Files.txt+ Hledger/Cli/Commands/Get.txt+ Hledger/Cli/Commands/Help.txt+ Hledger/Cli/Commands/Holdings.txt+ Hledger/Cli/Commands/Import.txt+ Hledger/Cli/Commands/Incomestatement.txt+ Hledger/Cli/Commands/Init.txt+ Hledger/Cli/Commands/Notes.txt+ Hledger/Cli/Commands/Payees.txt+ Hledger/Cli/Commands/Prices.txt+ Hledger/Cli/Commands/Print.txt+ Hledger/Cli/Commands/Register.txt+ Hledger/Cli/Commands/Rewrite.txt+ Hledger/Cli/Commands/Repl.txt+ Hledger/Cli/Commands/Roi.txt+ Hledger/Cli/Commands/Run.txt+ Hledger/Cli/Commands/Setup.txt+ Hledger/Cli/Commands/Stats.txt+ Hledger/Cli/Commands/Tags.txt+ Hledger/Cli/Commands/Transactions.txt source-repository head- type: darcs- location: http://joyful.com/repos/hledger+ type: git+ location: https://github.com/hledgerorg/hledger +flag debug+ description: Build with GHC 9.10+ stack traces enabled+ manual: True+ default: False+ library- -- XXX should set patchlevel here as in Makefile- cpp-options: -DPATCHLEVEL=0- ghc-options: -W- -- should be the same as below exposed-modules:- Hledger.Cli- Hledger.Cli.Main- Hledger.Cli.Format- Hledger.Cli.Options- Hledger.Cli.Tests- Hledger.Cli.Utils- Hledger.Cli.Version- Hledger.Cli.Add- Hledger.Cli.Balance- Hledger.Cli.Convert- Hledger.Cli.Histogram- Hledger.Cli.Print- Hledger.Cli.Register- Hledger.Cli.Stats- -- should be the same as below+ Hledger.Cli+ Hledger.Cli.Anchor+ Hledger.Cli.Anon+ Hledger.Cli.Chart+ Hledger.Cli.CliOptions+ Hledger.Cli.Commands+ Hledger.Cli.Commands.Accounts+ Hledger.Cli.Commands.Activity+ Hledger.Cli.Commands.Add+ Hledger.Cli.Commands.Aregister+ Hledger.Cli.Commands.Balance+ Hledger.Cli.Commands.Balancesheet+ Hledger.Cli.Commands.Balancesheetequity+ Hledger.Cli.Commands.Cashflow+ Hledger.Cli.Commands.Check+ Hledger.Cli.Commands.Close+ Hledger.Cli.Commands.Codes+ Hledger.Cli.Commands.Commodities+ Hledger.Cli.Commands.Descriptions+ Hledger.Cli.Commands.Diff+ Hledger.Cli.Commands.Files+ Hledger.Cli.Commands.Get+ Hledger.Cli.Commands.Help+ Hledger.Cli.Commands.Holdings+ Hledger.Cli.Commands.Import+ Hledger.Cli.Commands.Incomestatement+ Hledger.Cli.Commands.Init+ Hledger.Cli.Commands.Notes+ Hledger.Cli.Commands.Payees+ Hledger.Cli.Commands.Prices+ Hledger.Cli.Commands.Print+ Hledger.Cli.Commands.Quickref+ Hledger.Cli.Commands.Register+ Hledger.Cli.Commands.Rewrite+ Hledger.Cli.Commands.Roi+ Hledger.Cli.Commands.Run+ Hledger.Cli.Commands.Setup+ Hledger.Cli.Commands.Stats+ Hledger.Cli.Commands.Tags+ Hledger.Cli.Commands.Transactions+ Hledger.Cli.CompoundBalanceCommand+ Hledger.Cli.Conf+ Hledger.Cli.DocFiles+ Hledger.Cli.GitInfo+ Hledger.Cli.Script+ Hledger.Cli.Utils+ Hledger.Cli.Version+ Hledger.Cli.Xirr+ other-modules:+ Hledger.Cli.Commands.Balance.Internal+ Paths_hledger+ autogen-modules:+ Paths_hledger+ hs-source-dirs:+ ./+ ghc-options: -Wall -Wno-incomplete-uni-patterns -Wno-missing-signatures -Wno-orphans -Wno-type-defaults -Wno-unused-do-bind -optP-Wno-nonportable-include-path+ cpp-options: -DVERSION="2.0" build-depends:- hledger-lib == 0.16.1- ,base >= 3 && < 5- ,containers- ,cmdargs >= 0.8 && < 0.9- ,csv- ,directory- ,filepath- ,haskeline == 0.6.*- ,HUnit- ,mtl- ,old-locale- ,old-time- ,parsec- ,process- ,regexpr >= 0.5.1- ,safe >= 0.2- ,split == 0.1.*- ,time- ,utf8-string >= 0.3.5 && < 0.4+ Decimal >=0.5.1+ , Diff >=1.0+ , aeson >=2.2.5.1 && <2.4+ , ansi-terminal >=0.9+ , base >=4.18 && <4.23+ , blaze-html+ , bytestring+ , cmdargs >=0.10+ , containers >=0.5.9+ , data-default >=0.5+ , directory+ , extra >=1.7.11+ , filepath+ , githash >=0.1.6.2+ , hashable >=1.2.4+ , haskeline >=0.6+ , hledger-lib ==2.0.*+ , http-client+ , http-types+ , math-functions >=0.3.3.0+ , megaparsec >=7.0.0 && <9.8 || >=9.8.1 && <9.9+ , microlens >=0.4+ , modern-uri >=0.3+ , mtl >=2.2.1+ , open-browser >=0.5+ , pretty+ , process+ , regex-tdfa+ , req+ , safe >=0.3.20+ , split >=0.1+ , tabular >=0.2+ , tasty >=1.2.3+ , temporary+ , text >=1.2.4.1+ , text-ansi >=0.2.1+ , time >=1.5+ , timeit+ , transformers+ , unordered-containers+ , utf8-string >=0.3.5+ , utility-ht >=0.0.13+ , wizards >=1.0+ default-language: GHC2021+ if (flag(debug))+ cpp-options: -DDEBUG --- should depend on the above to avoid double compilation but this is--- still too complicated as of 2011/6/1 because:--- - breaks haddock, http://hackage.haskell.org/trac/hackage/ticket/656--- - library and executable must have different hs-source-dirs--- - the exe may need to list all the lib's dependencies--- - how it works seems ghc version dependent--- leksah is reported to have this working, http://hackage.haskell.org/packages/archive/leksah/0.10.0.4/leksah.cabal executable hledger- main-is: hledger-cli.hs- -- should be the same as above+ main-is: hledger-cli.hs other-modules:- Hledger.Cli- Hledger.Cli.Main- Hledger.Cli.Format- Hledger.Cli.Options- Hledger.Cli.Tests- Hledger.Cli.Utils- Hledger.Cli.Version- Hledger.Cli.Add- Hledger.Cli.Balance- Hledger.Cli.Convert- Hledger.Cli.Histogram- Hledger.Cli.Print- Hledger.Cli.Register- Hledger.Cli.Stats- -- XXX should set patchlevel here as in Makefile- cpp-options: -DPATCHLEVEL=0- ghc-options: -threaded -W- -- should be the same as above+ Paths_hledger+ autogen-modules:+ Paths_hledger+ hs-source-dirs:+ app+ ghc-options: -Wall -Wno-incomplete-uni-patterns -Wno-missing-signatures -Wno-orphans -Wno-type-defaults -Wno-unused-do-bind -optP-Wno-nonportable-include-path -threaded -rtsopts -with-rtsopts=-T+ cpp-options: -DVERSION="2.0" build-depends:- hledger-lib == 0.16.1- ,base >= 3 && < 5- ,containers- ,cmdargs >= 0.8 && < 0.9- ,csv- ,directory- ,filepath- ,haskeline == 0.6.*- ,HUnit- ,mtl- ,old-locale- ,old-time- ,parsec- ,process- ,regexpr >= 0.5.1- ,safe >= 0.2- ,split == 0.1.*- ,time- ,utf8-string >= 0.3.5 && < 0.4+ Decimal >=0.5.1+ , aeson >=2.2.5.1 && <2.4+ , ansi-terminal >=0.9+ , base >=4.18 && <4.23+ , bytestring+ , cmdargs >=0.10+ , containers >=0.5.9+ , data-default >=0.5+ , directory+ , extra >=1.7.11+ , filepath+ , githash >=0.1.6.2+ , haskeline >=0.6+ , hledger+ , hledger-lib ==2.0.*+ , http-client+ , http-types+ , math-functions >=0.3.3.0+ , megaparsec >=7.0.0 && <9.8 || >=9.8.1 && <9.9+ , microlens >=0.4+ , mtl >=2.2.1+ , open-browser >=0.5+ , process+ , regex-tdfa+ , req+ , safe >=0.3.20+ , split >=0.1+ , tabular >=0.2+ , tasty >=1.2.3+ , temporary+ , text >=1.2.4.1+ , text-ansi >=0.2.1+ , time >=1.5+ , timeit+ , transformers+ , unordered-containers+ , utf8-string >=0.3.5+ , utility-ht >=0.0.13+ , wizards >=1.0+ default-language: GHC2021+ if (flag(debug))+ cpp-options: -DDEBUG++test-suite unittest+ type: exitcode-stdio-1.0+ main-is: unittest.hs+ hs-source-dirs:+ test+ ghc-options: -Wall -Wno-incomplete-uni-patterns -Wno-missing-signatures -Wno-orphans -Wno-type-defaults -Wno-unused-do-bind -optP-Wno-nonportable-include-path+ cpp-options: -DVERSION="2.0"+ build-depends:+ Decimal >=0.5.1+ , aeson >=2.2.5.1 && <2.4+ , ansi-terminal >=0.9+ , base >=4.18 && <4.23+ , bytestring+ , cmdargs >=0.10+ , containers >=0.5.9+ , data-default >=0.5+ , directory+ , extra >=1.7.11+ , filepath+ , githash >=0.1.6.2+ , haskeline >=0.6+ , hledger+ , hledger-lib ==2.0.*+ , http-client+ , http-types+ , math-functions >=0.3.3.0+ , megaparsec >=7.0.0 && <9.8 || >=9.8.1 && <9.9+ , microlens >=0.4+ , mtl >=2.2.1+ , open-browser >=0.5+ , process+ , regex-tdfa+ , req+ , safe >=0.3.20+ , split >=0.1+ , tabular >=0.2+ , tasty >=1.2.3+ , temporary+ , text >=1.2.4.1+ , text-ansi >=0.2.1+ , time >=1.5+ , timeit+ , transformers+ , unordered-containers+ , utf8-string >=0.3.5+ , utility-ht >=0.0.13+ , wizards >=1.0+ default-language: GHC2021+ if (flag(debug))+ cpp-options: -DDEBUG++benchmark bench+ type: exitcode-stdio-1.0+ main-is: bench.hs+ hs-source-dirs:+ bench+ ghc-options: -Wall -Wno-incomplete-uni-patterns -Wno-missing-signatures -Wno-orphans -Wno-type-defaults -Wno-unused-do-bind -optP-Wno-nonportable-include-path+ cpp-options: -DVERSION="2.0"+ build-depends:+ Decimal >=0.5.1+ , aeson >=2.2.5.1 && <2.4+ , ansi-terminal >=0.9+ , base >=4.18 && <4.23+ , bytestring+ , cmdargs >=0.10+ , containers >=0.5.9+ , criterion+ , data-default >=0.5+ , directory+ , extra >=1.7.11+ , filepath+ , githash >=0.1.6.2+ , haskeline >=0.6+ , hledger+ , hledger-lib ==2.0.*+ , html+ , http-client+ , http-types+ , math-functions >=0.3.3.0+ , megaparsec >=7.0.0 && <9.8 || >=9.8.1 && <9.9+ , microlens >=0.4+ , mtl >=2.2.1+ , open-browser >=0.5+ , process+ , regex-tdfa+ , req+ , safe >=0.3.20+ , split >=0.1+ , tabular >=0.2+ , tasty >=1.2.3+ , temporary+ , text >=1.2.4.1+ , text-ansi >=0.2.1+ , time >=1.5+ , timeit+ , transformers+ , unordered-containers+ , utf8-string >=0.3.5+ , utility-ht >=0.0.13+ , wizards >=1.0+ buildable: False+ default-language: GHC2021+ if (flag(debug))+ cpp-options: -DDEBUG
+ quickref.txt view
@@ -0,0 +1,24 @@+HLEDGER QUICK REFERENCE+Usage: hledger [COMMAND] [OPTIONS] [ARGS]+Common commands: (hledger help commands to see all)+ Entering data add get import+ Reports acc act areg bs comm files holdings is payees print reg tx+ Maintenance setup check close interest stats+ User interfaces ui web repl run help+repl commands: HLEDGERCMD !SHELLCMD echo h q C-d C-c C-z+help topics: (hledger help -h to see all)+ commands examples manual usage MANUALTOPIC+ home docs install relnotes sponsor support+Common flags: (hledger -h, hledger COMMAND -h to see all)+ Input -f -I -s --forecast --rules+ Reports -p/-b/-e -E -C/-U -D/-W/-M/-Q/-Y -B/-V/-X/--value --lots+ Output --pretty --title -c -o/-O --chart --view+Formats, input: csv journal rules ssv timeclock timedot tsv+ output: beancount csv fods journal json html ledger sql svg tsv txt+Checks, default: parseable autobalanced assertions lots+ strict: balanced commodities accounts+ other: tags payees ordereddates recentassertions uniqueleafnames+Account types: A/Asset L/Liability E/Equity R/Revenue X/Expense+ subtypes: C/Cash V/Conversion, M/Imbalance G/Gain+Query types: acct: amt: code: cur: date: depth: desc: note: payee:+ real: status: tag: type: not: all: any: expr: find: ::
+ shell-completion/hledger-completion.bash view
@@ -0,0 +1,2204 @@+# -*- mode: sh; sh-basic-offset: 4; indent-tabs-mode: nil -*-+# ex: ft=sh ts=4 sw=4 et+# shellcheck disable=2034,2154++# Completion script for hledger.+# Created using a Makefile and real hledger.++# This script is sourced by an interactive shell, so do NOT do things like+# 'set -o pipefail' or mangle the global environment in any other way!+# That said, we *do* remove colon (:) from COMP_WORDBREAKS which impacts+# the rest of the session and completion for other programs.++# INSTALLATION:+# To install you can simply source this file from your shell's startup files.+#+# Alternatively, copy/symlink it into `${BASH_COMPLETION_USER_DIR}/completions`+# or `${XDG_DATA_HOME:-$HOME/.local/share}/bash-completion/completions`, rename+# it to either `hledger`, `_hledger` or `hledger.bash`, and it will be loaded+# dynamically the first time you use the `hledger` command. Optionally, create+# symlinks to this file for any extensions used e.g.:+#+# mkdir -p "${BASH_COMPLETION_USER_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/bash-completion}/completions" &&+# cd "${BASH_COMPLETION_USER_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/bash-completion}/completions" &&+# cp /path/to/hledger-completion.bash hledger &&+# ln -s hledger hledger-ui &&+# ln -s hledger hledger-web &&+# : done.+++_hledger_completion() {+ local cur prev words cword+ _init_completion -n : || return 0++ # Current treatment for special characters:+ # - exclude colon (:) from COMP_WORDBREAKS+ # - option processing assumes that `=` is in COMP_WORDBREAKS+ # - use compopt -o filenames selectively to escape the rest+ COMP_WORDBREAKS=${COMP_WORDBREAKS//:}+ case $COMP_WORDBREAKS in+ *=*) : ;;+ *) COMP_WORDBREAKS=$COMP_WORDBREAKS= ;;+ esac++ local subcommand+ local subcommandOptions+ local i+ for ((i=1; i<${#words[@]}; i++)); do+ subcommand=${words[i]}+ if ! grep -Fxqe "$subcommand" <<< "$_hledger_complist_commands"; then+ subcommand=+ continue+ fi+ # There could be other commands begining with $subcommand, e.g.:+ # $subcommand == reg --> register, register-match,+ # $subcommand == bal --> balance, balancesheet, balancesheetequity, etc.+ # Do not ignore them!+ if ((i == cword)); then+ _hledger_compreply "$(+ _hledger_compgen "$_hledger_complist_commands"+ )"+ return 0+ fi++ # Replace dashes with underscores and use indirect expansion+ subcommandOptions=_hledger_complist_options_${subcommand//-/_}++ if [[ $cur == -* ]]; then+ _hledger_compreply "$(_hledger_compgen "${!subcommandOptions}")"+ # Suspend space on completion of long options requiring an argument+ [[ ${COMPREPLY[0]} == --*= ]] && compopt -o nospace++ return 0+ fi+ break+ done++ # Option argument completion+ _hledger_compreply_optarg && return++ if [[ -z $subcommand ]]; then+ if [[ $cur == -* ]]; then+ _hledger_compreply "$(+ _hledger_compgen "$_hledger_complist_generic_options"+ )"+ # Suspend space on completion of long options requiring an argument+ [[ ${COMPREPLY[0]} == --*= ]] && compopt -o nospace+ else+ _hledger_compreply "$(+ _hledger_compgen "$_hledger_complist_commands"+ )"+ fi++ return 0+ fi++ # Set this from here on because queries tend to have lots of special chars+ # TODO: better handling of special characters+ compopt -o filenames++ # Query completion+ _hledger_compreply_query && return++ # Subcommand specific+ case $subcommand in+ # These do not expect or support any query arguments+ commodities|check|files|help|import|print-unique|test)+ return 0+ ;;+ esac++ # Offer query filters and accounts for the rest+ _hledger_compreply "$(_hledger_compgen "$_hledger_complist_query_filters")"+ if [[ -z $cur ]]; then+ _hledger_compreply_append "$(+ _hledger_compgen "$(_hledger accounts --flat --depth 1)"+ )"+ else+ _hledger_compreply_append "$(+ _hledger_compgen "$(_hledger accounts --flat)"+ )"+ fi++ # Suspend space on completion of query prefix+ # Do not sort, keep accounts and query filters grouped separately+ [[ ${COMPREPLY[0]} == *: ]] && compopt -o nospace+ compopt -o nosort++ return 0+}++_hledger_extension_completion() {+ local cmd=${1##*/}+ local ext=${cmd#hledger-}+ # Pretend that hledger is called with the given extension+ # as the first argument and call main completion function+ COMP_WORDS=("hledger" "$ext" "${COMP_WORDS[@]:1}")+ COMP_CWORD=$((COMP_CWORD + 1))+ _hledger_completion "hledger" "${@:1}"+}++# Register completion function for hledger:+complete -F _hledger_completion hledger++# Register completion functions for hledger extensions:+complete -F _hledger_extension_completion hledger-ui hledger-web++# Helpers++# Comment out when done+_hledger_debug() {+ ((HLEDGER_DEBUG)) || return 0+ local var vars=(words)+ (($#)) && vars=("$@")+ for var in "${vars[@]}"; do+ printf '\ndebug: %s\n' "$(declare -p "$var")" >&2+ done+}++# Stolen from bash-completion+# This function quotes the argument in a way so that readline dequoting+# results in the original argument. This is necessary for at least+# `compgen' which requires its arguments quoted/escaped:+_hledger_quote_by_ref()+{+ printf -v "$2" %q "$1"++ # If result becomes quoted like this: $'string', re-evaluate in order to+ # drop the additional quoting. See also: http://www.mail-archive.com/+ # bash-completion-devel@lists.alioth.debian.org/msg01942.html+ [[ ${!2} == \$* ]] && eval "$2=${!2}"+}++# Set the value of COMPREPLY from newline delimited completion candidates+_hledger_compreply() {+ local IFS=$'\n'+ # shellcheck disable=2206+ COMPREPLY=($1)+}++# Append the value of COMPREPLY from newline delimited completion candidates+_hledger_compreply_append() {+ local IFS=$'\n'+ # shellcheck disable=2206+ COMPREPLY+=($1)+}++# Generate input suitable for _hledger_compreply() from newline delimited+# completion candidates. It doesn't seem there is a way to feed a literal+# word list to compgen -- it will eat your quotes, drink your booze and...+# Completion candidates are quoted accordingly first and then we leave it to+# compgen to deal with readline.+#+# Arguments:+# $1: a newline separated list with completion cadidates+# $2: (optional) a prefix string to add to generated completions+# $3: (optional) a word to match instead of $cur, the default.+# If $match is null and $prefix is defined the match is done against $cur+# stripped of $prefix. If both $prefix and $match are null we match against+# $cur and no prefix is added to completions.+_hledger_compgen() {+ local complist=$1+ local prefix=$2+ local match=$3+ local quoted=()+ local word+ local i=0++ while IFS= read -r word; do+ _hledger_quote_by_ref "$word" word+ quoted[i++]=$word+ done <<< "$complist"++ if (($# < 3)); then+ match=${cur:${#prefix}}+ fi++ local IFS=$'\n'+ compgen -P "$prefix" -W "${quoted[*]}" -- "$match"+}++# Try required option argument completion. Set COMPREPLY and return 0 on+# success, 1 if option doesn't require an argument or out of context+_hledger_compreply_optarg() {+ local option=${words[cword - 1]}+ local match=$cur+ local wordlist++ # Match the empty string on --file=<TAB>, not the equal sign itself+ if [[ $cur == = ]]; then+ match=""+ # Once input is present, cword is incremented so we compensate+ elif [[ $prev == = ]]; then+ option=${words[cword - 2]}+ fi++ [[ $option == -* ]] || return++ case $option in+ --alias)+ compopt -o nospace -o filenames+ _hledger_compreply "$(+ _hledger_compgen "$(_hledger accounts --flat)" "" "$match"+ )"+ ;;+ -f|--file|--rules-file|-o|--output-file)+ compopt -o filenames+ _hledger_compreply "$(compgen -f -- "$match")"+ ;;+ --pivot)+ compopt -o nosort+ wordlist="code description note payee"+ _hledger_compreply "$(compgen -W "$wordlist" -- "$match")"+ _hledger_compreply_append "$(+ _hledger_compgen "$(_hledger tags)" "" "$match"+ )"+ ;;+ --value)+ wordlist="cost then end now"+ _hledger_compreply "$(compgen -W "$wordlist" -- "$match")"+ ;;+ -X|--exchange)+ _hledger_compreply "$(+ _hledger_compgen "$(_hledger commodities)" "" "$match"+ )"+ ;;+ --color|--colour)+ compopt -o nosort+ wordlist="auto always yes never no"+ _hledger_compreply "$(compgen -W "$wordlist" -- "$match")"+ ;;+ -O|--output-format)+ wordlist="txt csv json sql"+ _hledger_compreply "$(compgen -W "$wordlist" -- "$match")"+ ;;+ --close-acct|--open-acct)+ compopt -o filenames+ _hledger_compreply "$(+ _hledger_compgen "$(_hledger accounts --flat)" "" "$match"+ )"+ ;;+ --debug)+ wordlist="{1..9}"+ _hledger_compreply "$(compgen -W "$wordlist" -- "$match")"+ ;;+ # Argument required, but no handler (yet)+ -b|-e|-p)+ _hledger_compreply ""+ ;;+ # Check if an unhandled long option requires an argument+ *)+ local optionList argRequired++ if [[ -n $subcommandOptions ]]; then+ optionList=${!subcommandOptions}+ else+ optionList=$_hledger_complist_generic_options+ fi++ while IFS= read -r argRequired; do+ if [[ $argRequired == "$option=" ]]; then+ _hledger_compreply ""+ return 0+ fi+ done <<< "$optionList"++ return 1+ ;;+ esac++ return 0+}++# Query filter completion through introspection+_hledger_compreply_query() {+ [[ $cur =~ .: ]] || return+ local query=${cur%%:*}:+ local match=${cur#*:}+ grep -Fxqe "$query" <<< "$_hledger_complist_query_filters" || return++ local hledgerArgs=()+ case $query in+ acct:)+ if (( ${#match} )); then+ hledgerArgs=(accounts --flat)+ else+ hledgerArgs=(accounts --flat --depth 1)+ fi+ ;;+ code:) hledgerArgs=(codes) ;;+ cur:) hledgerArgs=(commodities) ;;+ desc:) hledgerArgs=(descriptions) ;;+ note:) hledgerArgs=(notes) ;;+ payee:) hledgerArgs=(payees) ;;+ tag:) hledgerArgs=(tags) ;;+ *)+ local wordlist+ case $query in+ amt:) wordlist="< <= > >=" ;;+ real:) wordlist="\ 0" ;;+ status:) wordlist="\ * !" ;;+ *) return 1 ;;+ esac+ _hledger_compreply "$(+ compgen -P "$query" -W "$wordlist" -- "$match"+ )"+ return 0+ ;;+ esac++ _hledger_compreply "$(+ _hledger_compgen "$(_hledger "${hledgerArgs[@]}")" "$query"+ )"++ return 0+}++# Parse the command line so far and fill the array $optarg with the arguments to+# given options. $optarg should be declared by the caller+_hledger_optarg() {+ local options=("$@")+ local i j offset+ optarg=()++ # hledger balance --file ~/ledger _+ # 0 1 2 3 4+ for ((i=1; i < ${#words[@]} - 2; i++)); do+ offset=0+ for j in "${!options[@]}"; do+ if [[ ${words[i]} == "${options[j]}" ]]; then+ if [[ ${words[i+1]} == '=' ]]; then+ offset=2+ else+ offset=1+ fi+ # Pass it through compgen to unescape it+ optarg+=("$(compgen -W "${words[i + offset]}")")+ fi+ done+ ((i += offset))+ done+}++# Get ledger file from -f --file arguments from COMP_WORDS and pass it to the+# 'hledger' call. Note that --rules-file - if present - must also be passed!+# Multiple files are allowed so pass them all in the order of appearance.+_hledger() {+ local hledgerArgs=("$@")+ local file+ local -a optarg++ _hledger_optarg -f --file+ for file in "${optarg[@]}"; do+ [[ -f $file ]] && hledgerArgs+=(--file "$file")+ done++ _hledger_optarg --rules-file+ for file in "${optarg[@]}"; do+ [[ -f $file ]] && hledgerArgs+=(--rules-file "$file")+ done++ # Discard errors. Is there a way to validate files before using them?+ hledger "${hledgerArgs[@]}" 2>/dev/null+}++# Include lists of commands and options generated by the Makefile using the+# m4 macro processor.+# Included files must have exactly one newline at EOF to prevent weired errors.++read -r -d "" _hledger_complist_commands <<"__TEXT__"+accounts+activity+add+areg+aregister+bal+balance+balancesheet+balancesheetequity+bs+bse+cashflow+cf+check+close+codes+commodities+descriptions+diff+files+help+import+incomestatement+is+notes+payees+prices+print+reg+register+rewrite+roi+stats+tags+test+__TEXT__++read -r -d "" _hledger_complist_query_filters <<"__TEXT__"+acct:+amt:+code:+cur:+date:+date2:+depth:+desc:+inacct:+not:+note:+payee:+real:+status:+tag:+__TEXT__++read -r -d "" _hledger_complist_generic_options <<"__TEXT__"+--alias=+--auto+--begin=+--cleared+--color=+--commodity-style=+--conf=+--cost+--daily+--date2+--debug=+--depth=+--empty+--end=+--exchange=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--market+--monthly+--no-conf+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--rules=+--strict+--tldr+--today=+--unmarked+--value=+--verbose-tags+--version+--weekly+--yearly+__TEXT__++# Dashes are replaced by m4 with underscores to form valid identifiers+# Referenced by indirect expansion of $subcommandOptions++read -r -d "" _hledger_complist_options_accounts <<"__TEXT__"+--alias=+--auto+--begin=+--cleared+--color=+--commodity-style=+--cost+--daily+--date2+--debug=+--declared+--depth=+--directives+--drop=+--empty+--end=+--exchange=+--file=+--find+--flat+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--locations+--man+--market+--monthly+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--rules=+--strict+--tldr+--today=+--tree+--types+--undeclared+--unmarked+--unused+--used+--value=+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_activity <<"__TEXT__"+--alias=+--auto+--begin=+--cleared+--color=+--commodity-style=+--cost+--daily+--date2+--debug=+--depth=+--empty+--end=+--exchange=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--market+--monthly+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--rules=+--strict+--tldr+--today=+--unmarked+--value=+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_add <<"__TEXT__"+--alias=+--auto+--debug=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--no-new-accounts+--pivot=+--rules=+--strict+--tldr+--verbose-tags+--version+__TEXT__++read -r -d "" _hledger_complist_options_areg <<"__TEXT__"+--alias=+--align-all+--auto+--begin=+--cleared+--color=+--commodity-style=+--cost+--daily+--date2+--debug=+--depth=+--empty+--end=+--exchange=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--market+--monthly+--no-elide+--output-file=+--output-format=+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--rules=+--strict+--tldr+--today=+--txn-dates+--unmarked+--value=+--verbose-tags+--version+--weekly+--width=+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_aregister <<"__TEXT__"+--alias=+--align-all+--auto+--begin=+--cleared+--color=+--commodity-style=+--cost+--daily+--date2+--debug=+--depth=+--empty+--end=+--exchange=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--market+--monthly+--no-elide+--output-file=+--output-format=+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--rules=+--strict+--tldr+--today=+--txn-dates+--unmarked+--value=+--verbose-tags+--version+--weekly+--width=+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_bal <<"__TEXT__"+--alias=+--auto+--average+--begin=+--budget+--change+--cleared+--color=+--commodity-style=+--cost+--count+--cumulative+--daily+--date2+--debug=+--declared+--depth=+--drop=+--empty+--end=+--exchange=+--file=+--flat+--forecast+--format=+--gain+--help+--historical+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--invert+--layout+--layout=+--man+--market+--monthly+--no-elide+--no-total+--output-file=+--output-format=+--pending+--percent+--period=+--pivot=+--pretty+--quarterly+--real+--related+--row-total+--rules=+--sort-amount+--strict+--sum+--summary-only+--tldr+--today=+--transpose+--tree+--unmarked+--value=+--valuechange+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_balance <<"__TEXT__"+--alias=+--auto+--average+--begin=+--budget+--change+--cleared+--color=+--commodity-style=+--cost+--count+--cumulative+--daily+--date2+--debug=+--declared+--depth=+--drop=+--empty+--end=+--exchange=+--file=+--flat+--forecast+--format=+--gain+--help+--historical+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--invert+--layout+--layout=+--man+--market+--monthly+--no-elide+--no-total+--output-file=+--output-format=+--pending+--percent+--period=+--pivot=+--pretty+--quarterly+--real+--related+--row-total+--rules=+--sort-amount+--strict+--sum+--summary-only+--tldr+--today=+--transpose+--tree+--unmarked+--value=+--valuechange+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_balancesheet <<"__TEXT__"+--alias=+--auto+--average+--begin=+--budget+--change+--cleared+--color=+--commodity-style=+--cost+--cumulative+--daily+--date2+--debug=+--declared+--depth=+--drop=+--empty+--end=+--exchange=+--file=+--flat+--forecast+--format=+--gain+--help+--historical+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--layout=+--man+--market+--monthly+--no-elide+--no-total+--output-file=+--output-format=+--pending+--percent+--period=+--pivot=+--pretty+--quarterly+--real+--row-total+--rules=+--sort-amount+--strict+--sum+--summary-only+--tldr+--today=+--tree+--unmarked+--value=+--valuechange+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_balancesheetequity <<"__TEXT__"+--alias=+--auto+--average+--begin=+--budget+--change+--cleared+--color=+--commodity-style=+--cost+--cumulative+--daily+--date2+--debug=+--declared+--depth=+--drop=+--empty+--end=+--exchange=+--file=+--flat+--forecast+--format=+--gain+--help+--historical+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--layout=+--man+--market+--monthly+--no-elide+--no-total+--output-file=+--output-format=+--pending+--percent+--period=+--pivot=+--pretty+--quarterly+--real+--row-total+--rules=+--sort-amount+--strict+--sum+--summary-only+--tldr+--today=+--tree+--unmarked+--value=+--valuechange+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_bs <<"__TEXT__"+--alias=+--auto+--average+--begin=+--budget+--change+--cleared+--color=+--commodity-style=+--cost+--cumulative+--daily+--date2+--debug=+--declared+--depth=+--drop=+--empty+--end=+--exchange=+--file=+--flat+--forecast+--format=+--gain+--help+--historical+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--layout=+--man+--market+--monthly+--no-elide+--no-total+--output-file=+--output-format=+--pending+--percent+--period=+--pivot=+--pretty+--quarterly+--real+--row-total+--rules=+--sort-amount+--strict+--sum+--summary-only+--tldr+--today=+--tree+--unmarked+--value=+--valuechange+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_bse <<"__TEXT__"+--alias=+--auto+--average+--begin=+--budget+--change+--cleared+--color=+--commodity-style=+--cost+--cumulative+--daily+--date2+--debug=+--declared+--depth=+--drop=+--empty+--end=+--exchange=+--file=+--flat+--forecast+--format=+--gain+--help+--historical+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--layout=+--man+--market+--monthly+--no-elide+--no-total+--output-file=+--output-format=+--pending+--percent+--period=+--pivot=+--pretty+--quarterly+--real+--row-total+--rules=+--sort-amount+--strict+--sum+--summary-only+--tldr+--today=+--tree+--unmarked+--value=+--valuechange+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_cashflow <<"__TEXT__"+--alias=+--auto+--average+--begin=+--budget+--change+--cleared+--color=+--commodity-style=+--cost+--cumulative+--daily+--date2+--debug=+--declared+--depth=+--drop=+--empty+--end=+--exchange=+--file=+--flat+--forecast+--format=+--gain+--help+--historical+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--layout=+--man+--market+--monthly+--no-elide+--no-total+--output-file=+--output-format=+--pending+--percent+--period=+--pivot=+--pretty+--quarterly+--real+--row-total+--rules=+--sort-amount+--strict+--sum+--summary-only+--tldr+--today=+--tree+--unmarked+--value=+--valuechange+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_cf <<"__TEXT__"+--alias=+--auto+--average+--begin=+--budget+--change+--cleared+--color=+--commodity-style=+--cost+--cumulative+--daily+--date2+--debug=+--declared+--depth=+--drop=+--empty+--end=+--exchange=+--file=+--flat+--forecast+--format=+--gain+--help+--historical+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--layout=+--man+--market+--monthly+--no-elide+--no-total+--output-file=+--output-format=+--pending+--percent+--period=+--pivot=+--pretty+--quarterly+--real+--row-total+--rules=+--sort-amount+--strict+--sum+--summary-only+--tldr+--today=+--tree+--unmarked+--value=+--valuechange+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_check <<"__TEXT__"+--alias=+--auto+--begin=+--cleared+--color=+--commodity-style=+--cost+--daily+--date2+--debug=+--depth=+--empty+--end=+--exchange=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--market+--monthly+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--rules=+--strict+--tldr+--today=+--unmarked+--value=+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_close <<"__TEXT__"+--alias=+--assert+--assertion-type=+--assign+--auto+--begin=+--cleared+--close+--close-acct=+--close-desc=+--color=+--commodity-style=+--cost+--daily+--date2+--debug=+--depth=+--empty+--end=+--exchange=+--explicit+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--interleaved+--man+--market+--migrate+--monthly+--open+--open-acct=+--open-desc=+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--retain+--round=+--rules=+--show-costs+--strict+--tldr+--today=+--unmarked+--value=+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_codes <<"__TEXT__"+--alias=+--auto+--begin=+--cleared+--color=+--commodity-style=+--cost+--daily+--date2+--debug=+--depth=+--empty+--end=+--exchange=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--market+--monthly+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--rules=+--strict+--tldr+--today=+--unmarked+--value=+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_commodities <<"__TEXT__"+--alias=+--auto+--debug=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--pivot=+--rules=+--strict+--tldr+--verbose-tags+--version+__TEXT__++read -r -d "" _hledger_complist_options_descriptions <<"__TEXT__"+--alias=+--auto+--begin=+--cleared+--color=+--commodity-style=+--cost+--daily+--date2+--debug=+--depth=+--empty+--end=+--exchange=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--market+--monthly+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--rules=+--strict+--tldr+--today=+--unmarked+--value=+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_diff <<"__TEXT__"+--alias=+--auto+--debug=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--pivot=+--rules=+--strict+--tldr+--verbose-tags+--version+__TEXT__++read -r -d "" _hledger_complist_options_files <<"__TEXT__"+--alias=+--auto+--debug=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--pivot=+--rules=+--strict+--tldr+--verbose-tags+--version+__TEXT__++read -r -d "" _hledger_complist_options_help <<"__TEXT__"+--debug=+--help+--info+--man+--tldr+--version+__TEXT__++read -r -d "" _hledger_complist_options_import <<"__TEXT__"+--alias=+--auto+--begin=+--catchup+--cleared+--color=+--commodity-style=+--cost+--daily+--date2+--debug=+--depth=+--dry-run+--empty+--end=+--exchange=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--market+--monthly+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--rules=+--strict+--tldr+--today=+--unmarked+--value=+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_incomestatement <<"__TEXT__"+--alias=+--auto+--average+--begin=+--budget+--change+--cleared+--color=+--commodity-style=+--cost+--cumulative+--daily+--date2+--debug=+--declared+--depth=+--drop=+--empty+--end=+--exchange=+--file=+--flat+--forecast+--format=+--gain+--help+--historical+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--layout=+--man+--market+--monthly+--no-elide+--no-total+--output-file=+--output-format=+--pending+--percent+--period=+--pivot=+--pretty+--quarterly+--real+--row-total+--rules=+--sort-amount+--strict+--sum+--summary-only+--tldr+--today=+--tree+--unmarked+--value=+--valuechange+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_is <<"__TEXT__"+--alias=+--auto+--average+--begin=+--budget+--change+--cleared+--color=+--commodity-style=+--cost+--cumulative+--daily+--date2+--debug=+--declared+--depth=+--drop=+--empty+--end=+--exchange=+--file=+--flat+--forecast+--format=+--gain+--help+--historical+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--layout=+--man+--market+--monthly+--no-elide+--no-total+--output-file=+--output-format=+--pending+--percent+--period=+--pivot=+--pretty+--quarterly+--real+--row-total+--rules=+--sort-amount+--strict+--sum+--summary-only+--tldr+--today=+--tree+--unmarked+--value=+--valuechange+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_notes <<"__TEXT__"+--alias=+--auto+--begin=+--cleared+--color=+--commodity-style=+--cost+--daily+--date2+--debug=+--depth=+--empty+--end=+--exchange=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--market+--monthly+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--rules=+--strict+--tldr+--today=+--unmarked+--value=+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_payees <<"__TEXT__"+--alias=+--auto+--begin=+--cleared+--color=+--commodity-style=+--cost+--daily+--date2+--debug=+--declared+--depth=+--empty+--end=+--exchange=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--market+--monthly+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--rules=+--strict+--tldr+--today=+--unmarked+--used+--value=+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_prices <<"__TEXT__"+--alias=+--auto+--begin=+--cleared+--color=+--commodity-style=+--cost+--daily+--date2+--debug=+--depth=+--empty+--end=+--exchange=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--market+--monthly+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--rules=+--show-reverse+--strict+--tldr+--today=+--unmarked+--value=+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_print <<"__TEXT__"+--alias=+--auto+--begin=+--cleared+--color=+--commodity-style=+--cost+--daily+--date2+--debug=+--depth=+--empty+--end=+--exchange=+--explicit+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--market+--match=+--monthly+--new+--output-file=+--output-format=+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--round=+--rules=+--show-costs+--strict+--tldr+--today=+--unmarked+--value=+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_reg <<"__TEXT__"+--alias=+--align-all+--auto+--average+--begin=+--cleared+--color=+--commodity-style=+--cost+--cumulative+--daily+--date2+--debug=+--depth=+--empty+--end=+--exchange=+--file=+--forecast+--help+--historical+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--invert+--man+--market+--match=+--monthly+--output-file=+--output-format=+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--related+--rules=+--sort=+--strict+--tldr+--today=+--unmarked+--value=+--verbose-tags+--version+--weekly+--width=+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_register <<"__TEXT__"+--alias=+--align-all+--auto+--average+--begin=+--cleared+--color=+--commodity-style=+--cost+--cumulative+--daily+--date2+--debug=+--depth=+--empty+--end=+--exchange=+--file=+--forecast+--help+--historical+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--invert+--man+--market+--match=+--monthly+--output-file=+--output-format=+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--related+--rules=+--sort=+--strict+--tldr+--today=+--unmarked+--value=+--verbose-tags+--version+--weekly+--width=+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_rewrite <<"__TEXT__"+--add-posting=+--alias=+--auto+--begin=+--cleared+--color=+--commodity-style=+--cost+--daily+--date2+--debug=+--depth=+--diff+--empty+--end=+--exchange=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--market+--monthly+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--rules=+--strict+--tldr+--today=+--unmarked+--value=+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_roi <<"__TEXT__"+--alias=+--auto+--begin=+--cashflow+--cleared+--color=+--commodity-style=+--cost+--daily+--date2+--debug=+--depth=+--empty+--end=+--exchange=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--investment=+--man+--market+--monthly+--pending+--period=+--pivot=+--pretty+--profit-loss=+--quarterly+--real+--rules=+--strict+--tldr+--today=+--unmarked+--value=+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_stats <<"__TEXT__"+--alias=+--auto+--begin=+--cleared+--color=+--commodity-style=+--cost+--daily+--date2+--debug=+--depth=+--empty+--end=+--exchange=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--market+--monthly+--output-file=+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--rules=+--strict+--tldr+--today=+--unmarked+--value=+--verbose+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_tags <<"__TEXT__"+--alias=+--auto+--begin=+--cleared+--color=+--commodity-style=+--cost+--daily+--date2+--debug=+--depth=+--empty+--end=+--exchange=+--file=+--forecast+--help+--ignore-assertions+--infer-costs+--infer-equity+--infer-market-prices+--info+--man+--market+--monthly+--parsed+--pending+--period=+--pivot=+--pretty+--quarterly+--real+--rules=+--strict+--tldr+--today=+--unmarked+--value=+--values+--verbose-tags+--version+--weekly+--yearly+__TEXT__++read -r -d "" _hledger_complist_options_test <<"__TEXT__"+--debug=+--help+--info+--man+--tldr+--version+__TEXT__++return 0
+ test/unittest.hs view
@@ -0,0 +1,14 @@+{-+Run the hledger package's unit tests using the tasty test runner+(the same as hledger --test, limited to Hledger.Cli tests).+-}++import Hledger.Cli (tests_Hledger_Cli)+import System.Environment (setEnv)+import Test.Tasty (defaultMain)++main :: IO ()+main = do+ setEnv "TASTY_HIDE_SUCCESSES" "true"+ setEnv "TASTY_ANSI_TRICKS" "false" -- helps the above+ defaultMain tests_Hledger_Cli